To find prime numbers using for loop in MATLAB, we can use the modulo operator to check if a number is divisible by any number other than 1 and itself.
Here's the code:
main.m638 chars29 lines
Here we have initialized a vector primes
to store prime numbers. We loop through each number within the range from 2
to n
. We assume each number is prime to start, and then we use a nested for loop to check if the number is divisible by any number other than 1
and itself using the modulo %
operator. If the number is found to be not prime during the inner for loop, we break out early and move on to the next number in the outer loop. If the number is prime, we add it to the primes
vector. Finally, we display the vector of prime numbers using disp()
.
One way to optimize this code would be to only check divisibility up to the square root of the number, since any factors beyond the square root would have already been checked. Another optimization would be to use logical indexing instead of a vector to store the prime numbers, since we don't know how many prime numbers there will be within the range beforehand.
gistlibby LogSnag