How to get my code running

3 次查看(过去 30 天)
Linda Grafen
Linda Grafen 2017-8-14
编辑: Stephen23 2017-8-14
Hello, I have tried to generate a code that returns all the primes from 2 to N (Sieve of Eratosthenes algorithm). Unfortunately, I get some errors and I don't know how to solve them. I've already looked in the Matlab prime function (edit primes), but it didn't help me further. I hope you can help me. Below my code:
function p =listofprimes(N)
% listofprimes(N) Generates a list of prime numbers from 2 to N.
% Input: scalar value N
% Output: a row vector of prime numbers from 2 to N.
% check if input is a scalar
if ~isscalar(N)
error(message('N must be a scalar'));
elseif ~isreal(N)
error(message('N must be a scalar'))
end
% 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;
% loop through all integers from 2 to sqrt(N)
for k = 2:sqrt(N)
% setting a value of the array to 0 indicates the value is crossed out
% check if the number k is not crossed out
if p(k)==0
% cross out all multiples of k starting from k^2, i.e.
% cross out k^2, k^2+k, k^2+2*k, ...
p((k*k):k:length(p)) = 0
end
end
% return all values that are not crossed out
if p(listofprimes>0);
return
end
end
  1 个评论
Stephen23
Stephen23 2017-8-14
编辑:Stephen23 2017-8-14
What is message ? I cannot find it in the list of MATLAB functions.
% 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

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by