- 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.
How to get my code running
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commento
Stephen23
il 14 Ago 2017
Modificato: Stephen23
il 14 Ago 2017
% 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:
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
Risposte (0)
Vedere anche
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!