% check if input is greater or equal to 2; else return empty array
if N < 2,
p = [];
end
% create an array for the numbers from 2 to N
p = 2:N;
You define p and then immediately redefine p: why? Note that 2:1 is empty anyway, so there is not point in the first allocation.
Your code does not seem to actually test anything other than p(k)==0, but none of the p values are zero because you define p with 1:N.
if p(listofprimes>0);
return
end
is unlikely to be a useful operation for you. Why not simply use logical indexing? The if is not required, nor is the return.
If you want to write code then do NOT do this: write many lines of code without knowing what they do and without testing them, and then trying to run it and not having any idea why it does not work. Writing one line of code means:
- read the documentation for every operator and function that you use.
- test that line carefully.
- check its output by hand and for several different inputs.
- consider edge-cases too.
- write comments as required.
Only then should you move on to the next line. You would have avoided being in the situation that you are in now. https://www.mathworks.com/matlabcentral/answers/228557-experts-of-matlab-how-did-you-learn-any-advice-for-beginner-intermediate-users