IN MATLAB Code in MATLAB, Write a function with the header: function [C] = myMat
ID: 3864909 • Letter: I
Question
IN MATLAB
Code in MATLAB,
Write a function with the header:
function [C] = myMatMat (A, B) that implements three nested for-loops to multiply A and B.
• If A and B are not compatible, myMatMat should return -1 for C.
• Do it the way we did in class. Do not use the colon operator or Matlab’s built-in matrix
multiplication operator (i.e., don’t just type C = A*B; )
Test Cases:
>> A = [1 6 0 7;7 2 9 3;0 4 5 4];
>> B = [2 4;6 8;10 12;14 16];
>> C = myMatMat(A,B)
C=
136 164
158 200
130 156
>> A*B ans =
136 164
158 200
130 156
>> D = [1 2 3;42 43 44];
>> C = myMatMat(A,D)
Matrix dimension mismatch
C= -1
Explanation / Answer
%matlab code
function [C] = myMatMat(A,B)
[n1 m1] = size(A);
[n2 m2] = size(B);
if(n2 != m1)
disp('Matrix dimension mismatch');
quit
end
C = zeros(n1,m2); % Initialise the matrix D
for i1 = 1:n1
for i2 = 1:m2
for i3 = 1:m1
C(i1,i2) = C(i1,i2) + A(i1,i3)*B(i3,i2);
end
end
end
end
A = [1 6 0 7;7 2 9 3;0 4 5 4];
B = [2 4;6 8;10 12;14 16];
C = myMatMat(A,B)
D = [1 2 3;42 43 44];
C = myMatMat(A,D)
%output: Matrix dimension mismatch
%{
output:
C =
136 164
158 200
130 156
%}