MATLAB: For the remaining problems, we\'ll revisit two more problems from Assign
ID: 3865017 • Letter: M
Question
MATLAB:
For the remaining problems, we'll revisit two more problems from Assignment 3. For these two problems, 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
%}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.