MATLAB: Nested for loop help

for loop

I'm trying to make a nested for loop to find prime numbers between 1 and 1000000 but I'm pretty sure I'm doing it wrong/got it stuck in an infinite loop because it's taking very long.
clear all
close all
primes = [ ];
tic
j=1
for m = 1:1000000 % outer loop
if isprime(m) == 1 % inner loop
primes(j) = m
j = j + 1;
m = m + 1;
else
end
m = m + 1;
end
toc

Best Answer

Your logic is correct. However, in MATLAB, you don't need to increment the loop variable yourself, for the loop will automatically increment it. Apart from that, there is no infinite loop, it just takes a long time to complete
clear all;
close all;
primes_num = []; % name is changed because primes is also name of MATLAB built-in function
tic
j=1;
for m = 1:1000000 % outer loop
if isprime(m) == 1 % inner loop
primes_num(j) = m;
j = j + 1;
end
end
toc
You can also get the same answer using MATLAB built-in function
primes_num = primes(1000000);