Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

MATLAB: you are prohibited from using explicit loops (i.e., for-loop or while-lo

ID: 3802089 • Letter: M

Question

MATLAB:

you are prohibited from using explicit loops (i.e., for-loop or while-loop). You must use logical indexing instead. Note that an ifstatement is not a loop and can be used in your solution. Write a function called problem5 that takes an at most two-dimensional matrix A as its sole input. The function returns a row vector v containing all elements of A that are prime numbers. The elements of v are stored according to row-major ordering of A. You are allowed to use the isprime built-in function.

Explanation / Answer

%matlab cde

function [v] = problem5( A )
v=[];
% determine primes and store in vector v
v=A(isprime(A(:,:)));

[n m] = size(v);
% convert column vector to row vector
v = v';

if m > 1
v = v';
end

end

A = [1 2 3 4 5 6 7 8 9 10];
v = problem5( A )

A =[15 3 69 67; 61 41 52 69; 98 6 58 5; 45 69 87 1];
v = problem5( A )

%{
output:

v =
2 3 5 7

v =
61 3 41 67 5

%}