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

MATLAB: Y ou are prohibited from using explicit loops (i.e., for-loop or while-l

ID: 3108903 • 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 hw4_problem4 that takes a matrix A of positive integers as its sole input. If the assumption is wrong, the function returns an empty matrix. Otherwise, the function doubles every odd element of A and returns the resulting matrix. Notice that the output matrix will have all even elements. For example, the call B = hw4_problem4([1 4; 5 2; 3 1], will make B equal to [2 4; 10 2; 6 2].

Explanation / Answer

function B=hw4_problem4(A)
%fprintf('The input matrix: ');
%disp(A)

[r c]=size(A);
% to find whether matrix a has elements which are all positive integers
m=((A>=0)&(mod(A,1)==0));

if (isequal(m,ones(r,c))==1)
    s=mod(A,2);
    % to find even elements
    a=(s==0);
    % to find odd elements
    b=(s==1);
    evens=a.*A;
    odds=b.*A*2;
    B=evens+odds;
   % fprintf('The result matrix: ');
   % disp(B)
else
   B=zeros(0,0);
   %fprintf('The result matrix:[] ',B);
% disp(B)
end
end

function B=hw4_problem4(A)
%fprintf('The input matrix: ');
%disp(A)

[r c]=size(A);
% to find whether matrix a has elements which are all positive integers
m=((A>=0)&(mod(A,1)==0));

if (isequal(m,ones(r,c))==1)
    s=mod(A,2);
    % to find even elements
    a=(s==0);
    % to find odd elements
    b=(s==1);
    evens=a.*A;
    odds=b.*A*2;
    B=evens+odds;
   % fprintf('The result matrix: ');
   % disp(B)
else
   B=zeros(0,0);
   %fprintf('The result matrix:[] ',B);
% disp(B)
end
end