MATLAB: Prime number list checker

for loopMATLABprime numbers

Ok so just for fun and practice 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.

Best Answer

Your code for resetting "counter" is inside an if-test. You need to move it so that it always executes. E.g.,
%#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; % <-- Moved from below
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; % <-- Moved to up above
end
end
toc