In MATLAB the isprime function is used to check whether or n

In MATLAB, the isprime() function is used to check whether or not a given number is prime. By combining this function with a while loop and other MATLAB functions (which you have learned), it is possible to generate matrices of prime numbers (a feat that is not normally possible using analytical methods, since prime numbers have no pattern).

a. Write a script that will create a 20 element column vector of the first twenty prime numbers above 34. (Hint: consider using two different “counters” in your while loop. One that increments every iteration, and one that increments every time you find a prime number. Consider which counter should be used as your loop control variable.)

b. Write a script that will create a 20 element column vector of random prime numbers between 2 and 101. (Hint: the round() function may be useful for this task. Make sure your script is designed so that 2 and 101 have the same odds of showing up as any other prime number in the given range by taking into account how round() works)

Solution

k = 34; %initialize k to 34
primes = zeros(20, 1); %initializing first column vector
n = 1; %initializing counter for number of primes
while n<=20
    k = k+1; %update k after each iteration
    if isprime(k)
        primes(n) = k; %add a prime k to primes vector
        n = n+1;
    end
end
disp(primes); %displaying 20 primes from 34


primes2 = zeros(20, 1); %initialize array with zeros
n = 1; %initialise counter
while n<=20
    r = randi(100); %random integer from 1 to 100
    if isprime(r+1)
        primes2(n) = r+1; %adding to primes
        n = n+1; %updating counter
    end
end
disp(primes2);

In MATLAB, the isprime() function is used to check whether or not a given number is prime. By combining this function with a while loop and other MATLAB functio

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site