Matlab: Missing something simple.

100 Views Asked by At

hi there so i'm about to return to uni and so i thought id brush up on my ole matlab skills before returning so i went back to basics. at the moment im going through previous exams and the question issued was.

(b) (15 marks) Write a matlab script which counts the number of primes less than or equal to an integer n, say, where $n=2,3,...,1000$ and stores the result in an array count(n).

for e.g. count(7) would take the value 4 as there are four primes (2,3,5,7) less than or equal to 7

so heres my code (im not actually being tested so im being a bit lenient at this stage)

Matlab Code

sooo i have it accurately telling me the number of primes between 1 and n at least so far as i can tell. but it's not storing A,

now i assume (like i said, im quite rusty at this and it's taking longer than id like) that the reason why its not storing A is because im running a function and i'm missing a "store vector A for later use" command.

Further i know i could technically get around this by making it actually a script (like it asks admittedly) with a few inputs and prompts to do the same thing as a function but you know....learning and stuff.

any help would be greatly appreciated.

2

There are 2 best solutions below

0
On BEST ANSWER

Functions only return what you tell them to in the first line; that is, when you write function [outputs] = name(inputs) you specify what, in which order, you want to return.

Here's how I'd write this function.

function [num_primes, prime_list] = primesless(n)
    prime_list = [];
    for j = 1:n
        if isprime(j) == 1
            prime_list = [prime_list j];
        end
    end

    num_primes = len(prime_list);
end

Why this? I give variable names that make sense in what they are storing, and I give the user the option to return the number of primes, the list of primes, or both. To return just the list of primes, the user types [~, prime_list] = primesless(n) in the console. The character ~ supresses the output of the item in that position.

0
On

id like to thank everyone for the feedback i learnt some very useful commands, and again apologise for not posting the rest of the question... for context the entire question was

(b) (15 marks) Write a matlab script which counts the number of primes less than or equal to an integer n, say, where n=2,3,...,1000 and stores the result in an array count(n).

for e.g. count(7) would take the value 4 as there are four primes (2,3,5,7) less than or equal to 7 your script should also plot the values of count(n) against n as a line and, on the same graph include a plot of n/log(n).

(c) Add a third curve to your graph to represent $\int_2^{n} \frac{dt}{ln(t)}dt$ using matlab's integral command.

this was why i was requesting information on why A was not being stored, as i would have then used that stored vector to continue on.

in the end i just used enter image description here

which does the job