largest = 0;
num = 0;
temp = 0;
num_flip = 0;
for x = 100 : 999
for y = x : 999
num = x*y;
temp = num2str(num);
num_flip = str2double(fliplr(temp));
if num/num_flip == 1
largest = num;
one = x;
two = y;
end
end
end
I'm trying to find the largest palindrome made from the product of two 3-digit numbers but for some reason my the loop stops at x = 924 and y = 962 but I know that's not answer. The code works fine for 2-digit numbers(10 : 99) though.
You are not testing if largest is truly the largest with that code. As you go through the loops it is possible that a smaller palindrome will be detected after a larger one, and you are reassigning largest to it.
Try this with an added test for whether a new palindrome is larger than the current largest:
largest = 0;
num = 0;
temp = 0;
num_flip = 0;
for x = 100 : 999
for y = x : 999
num = x*y;
temp = num2str(num);
num_flip = str2double(fliplr(temp));
if ((num/num_flip) == 1) && (num > largest)
largest = num;
end
end
end
I removed these assignments
one = x;
two = y;
because it's not clear what they are for from your question. Add them back if they are needed for a reason not shown.
Related
I am attempting to create a gamma distribution in MATLAB; however, I keep receiving the error:
Index in Position 1 exceeds array bounds (must not exceed 100).
Assuming I am reading this correctly, it is referring to variable M that is simply = 2500 (the number of pseudo-random variables I am using for this project).
I was hoping someone can explain what is wrong with my logic and possibly a solution.
alpha = 0.5;
w = gamma_rdn(M,alpha);
x1 = (0.0001:0.001:1); % For plot
figure(5)
subplot(2,1,1);hist(w);title('Histogram of Gamma RDN');
subplot(2,1,2);plot(x1,pdf('gam',x1,alpha,1));title('Theoretical Gamma Density with \alpha = 0.5');
axis([0 1 0 100]);
% The gamma_rdn function is implemented as follows:
function[w] = gamma_rdn(M,alpha)
% Generate random numbers from the gamma distribution with parameter
% alpha <= 1, beta = 1
pe = exp(1);
w = zeros(M,1);
u = rand(100,1);
b = (alpha + pe)/pe;
i = 0;
j = 0;
while j < M
i = i+1;
y = b*u(i,1);
if y <= 1
z = y^(1/alpha);
i = i+1;
if u(i,1) <= exp(-z)
j = j+1;
w(j,1) = z;
else
i = i+1;
end
else
z = -log((b-y)/alpha);
i = i+1;
if u(i,1) <= z^(alpha - 1)
j = j+1;
w(j,1) = z;
else
i = i+1;
end
end
end
if i > 95
u = rand(100,1);
i = 0;
end
end
Is there a particular reason you chose u = rand(100,1)?
The problem is coming because in while loop, as soon as variable i exceeds 100 (say i=101), y = b*u(i,1) becomes invalid. That is, you are trying to access u(101,1) while the size of u is (100,1).
If there's not particular reason, try a large enough size, like, u = rand(10000,1).
Tried to ask this at Matlab Central, and didn't get much replies.
This is the code:
for
... creates "cent"
end
e = 5 ;
per = zeros(e,e)
for u = 1:e
rsum = 0;
a = 0;
for p=1:e
u
p
Xdiff = 0;
Ydiff = 0;
Zdiff = 0;
Xdiff = (cent(u,1)-cent(:,1)).^2
Ydiff = (cent(u,2)-cent(:,2)).^2
Zdiff = (cent(u,3)-cent(:,3)).^2
a = (Xdiff + Ydiff + Zdiff).^0.5
rsum = cent(u,6) + cent(:,6) ;
if a == rsum(p)
per(p,u) = p ;
else
per(p,u) = 0 ;
end
end
end
The script runs just fine, and I get no error messages. However, i get no display of u and p, and per is returned as a matrix with only zeros if i create it before the first for loop. If i create per as shown over, between the first and second, it is not created at all. I thus think that the code stops after the first loop. Why?
Ok so I have been having a go at creating a prime number checker. I have been successful in making it work for a specific number. The code is here.
#To test if number is prime
prompt = input("number to test if prime: ");
n = prompt;
i = 2; #start of mod test
t = floor(sqrt(n));
counter = 0;
tic
for i = 2:t
if mod(n,i) == 0
disp('n is not prime')
break
else
counter = (counter + 1);
end
end
if counter == t-1
disp('n is prime')
end
toc
I then tried to make a program which would test a range of numbers. It's been successful for n=10, but when I go higher than that it doesn't seem to pick up the primes. I'm not sure where I'm going wrong.
#Want to test numbers 2:n if they're prime
prompt = input("max number to test: ");
n = prompt;
l = 2; #start of mod test
counter = 0;
tic
for i = 2:n #cycle to test 2 up to n
t = floor(sqrt(i)) #Only need to test up to root of number
for l = 2:t
if mod(i,l) == 0
break
else
counter = (counter + 1);
end
end
if counter == t-1 # if tested up to the root of the number, it must be prime
prime = sprintf('%d is prime', round(i));
disp(prime)
counter = 0;
end
end
toc
Any help in getting it to work for larger values would be greatly appreciated and also any ways to make the code more efficient. The top program can test 982451653 in 0.268 seconds on my laptop.
Just a way to linearize your algorithm:
n = 997 %test number
t1 = n./([2,3:2:n/2]);
t2 = t1 - round(t1);
res = sum(t2 == 0); %can n be divided ?
if res == 0
fprintf('%s','prime');
else
fprintf('%s','not prime');
end
I got help on the issue and found that 'counter' was constantly re-setting and needed to be moved up. Fixed code is here
#Want to test numbers 2:n if they're prime
prompt = input("max number to test: ");
n = prompt;
l = 2; #start of mod test
counter = 0;
tic
for i = 2:n #cycle to test 2 up to n
t = floor(sqrt(i)); #Only need to test up to root of number
counter = 0;
for l = 2:t
if mod(i,l) == 0
break
else
counter = (counter + 1);
end
end
if counter == t-1; # if tested up to the root of the number, it must be prime
prime = sprintf('%d is prime', round(i));
disp(prime)
end
end
toc
I'm working on the following problem:
I realize my code is a bit off, but I want to create a for loop that will determine whether or not the integer x (the input value) is at least less than or equal to the sum of a harmonic series.
Here is what I have so far:
function n =one_per_n(x)
if x > 10000
n = -1;
end
total = 0;
i = 0;
for i = 1:10000
if x >= total
n = ceil(total);
else
total = (1/i) + total;
end
end
I've added my attempt at a while loop. I realize it's wrong, but any help would be appreciated.
function n =one_per_n(x)
if x > 10000
n = -1;
end
total = 0;
i = 0;
for i = 1:10000
while total <= x
total = (1/i) + total;
end
end
n = total;
you don't need to use some loops:
function n = one_per_n(x)
lim = min(10000,exp(x));
value = cumsum(1./(1:lim));
n = find(value >= x,1);
if isempty(n)
n = -1;
end
A while loop is a better option in this case I think
function [total, n] = one_per_n(x)
% This is a good initial check, good work
if x > 10000
n = -1;
return;
end
% Initialize the variables
total = 0;
n = 0;
% While not finished
while (total < x)
% Number of terms
n = n + 1;
total = total + 1/n;
end
end
I have a vector. I want to remove outliers. I got bin and no of values in that bin. I want to remove all points based on the number of elements in each bin.
Data:
d1 =[
360.471912914169
505.084636471948
514.39429429184
505.285068055647
536.321181755858
503.025854206322
534.304229816684
393.387035881967
396.497969729985
520.592172434431
421.284713703215
420.401106087984
537.05330275495
396.715779872694
514.39429429184
404.442344469518
476.846474245118
599.020867750031
429.163139144079
514.941744277933
445.426761656729
531.013596812737
374.977332648255
364.660115724218
538.306752697753
519.042387479096
1412.54699036882
405.571202133485
516.606049132218
2289.49623498271
378.228766753667
504.730621222846
358.715764917016
462.339366699398
512.429858614816
394.778786157514
366
498.760463549388
366.552861126468
355.37022947906
358.308526273099
376.745272034036
366.934599077274
536.0901883079
483.01740134285
508.975480745389
365.629593988233
536.368800360349
557.024236456548
366.776498701866
501.007025898839
330.686029339009
508.395475983019
429.563732174866
2224.68806802212
534.655786464525
518.711297351426
534.304229816684
514.941744277933
420.32368479542
367.129404978681
525.626188464768
388.329756778952
1251.30895065927
525.626188464768
412.313764019587
513.697381733643
506.675438520558
1517.71183364959
550.276294237722
543.359917550053
500.639590923451
395.129864728041];
Histogram computation:
[nelements,centers] = hist(d1);
nelements=55 13 0 0 1 1 1 0 0 2
I want to remove all points apearing less than 5 (in nelements). It means only first 2 elements in nelements( 55, 13 ) remains.
Is there any function in matlab.
You can do it along these lines:
threshold = 5;
bin_halfwidth = (centers(2)-centers(1))/2;
keep = ~any(abs(bsxfun(#minus, d1, centers(nelements<threshold))) < bin_halfwidth , 2);
d1_keep = d1(keep);
Does this do what you want?
binwidth = centers(2)-centers(1);
centersOfRemainingBins = centers(nelements>5);
remainingvals = false(length(d1),1);
for ii = 1:length(centersOfRemainingBins )
remainingvals = remainingvals | (d1>centersOfRemainingBins (ii)-binwidth/2 & d1<centersOfRemainingBins (ii)+binwidth/2);
end
d_out = d1(remainingvals);
I don't know Matlab function for this problem, but I think, that function with follow code is what are you looking for:
sizeData = size(data);
function filter_hist = filter_hist(data, binCountRemove)
if or(max(sizeData) == 0, binCountRemove < 1)
disp('Error input!');
filter_hist = [];
return;
end
[n, c] = hist(data);
sizeN = size(n);
intervalSize = c(2) - c(1);
if sizeData(1) > sizeData(2)
temp = transpose(data);
else
temp = data;
end
for i = 1:1:max(sizeN)
if n(i) < binCountRemove
a = c(i) - intervalSize / 2;
b = c(i) + intervalSize / 2;
sizeTemp = size(temp);
removeInds = [];
k = 0;
for j = 1:1:max(sizeTemp)
if and(temp(j) > a, less_equal(temp(j), b) == 1)
k = k + 1;
removeInds(k) = j;
end
end
temp(removeInds) = [];
end
end
filter_hist = transpose(temp);
%Determines when 'a' less or equal to 'b' by accuracy
function less_equal = less_equal(a, b)
delta = 10^-6; %Accuracy
if a < b
less_equal = 1;
return;
end
if abs(b - a) < delta
less_equal = 1;
return;
end
less_equal = 0;
You can do something like this
nelements=nelements((nelements >5))