Matlab: assume you are given two matrices M1 and M2, both with the same dimensio
ID: 2988004 • Letter: M
Question
Matlab: assume you are given two matrices M1 and M2, both with the same dimensions. Using nested for loops, write a function named MatComp that will return a matrix D with the same dimensions as M1 and M2 with each element containing either 1,0,or -1 based on the contents of M1 and M2 as described below For all r and c within the matrix size: -If M1(r,c)=M2(r,c), then D(r,c)=0 -If M1(r,c)-M2(r,c)>0 , then D(r,c)=1 If M1(r,c)-M2(r,c)<0, thenD(r,c)=-1 If the matrices passed to the function are not the same size, an error message should appear on the screen and an empty matrix be returned for D(D=[ ] will establish D as an empty matrix).
Explanation / Answer
The function MatComp.
function D = MatComp(M1,M2)
[m1,n1] = size(M1);
[m2,n2] = size(M2);
if m1==m2 && n1==n2
for i=1:m1
for j=1:n1
if M1(i,j)-M2(i,j)==0
D(i,j)=0;
elseif M1(i,j)-M2(i,j)>0
D(i,j)=1;
else
D(i,j)=-1;
end
end
end
else
D=[];
disp('Error!!! Matrixes are not of same size');
end
end