Consider two matrices A (2 Times 4) and B (4 Times 3). Write a MATLAB script to
ID: 3564447 • Letter: C
Question
Consider two matrices A (2 Times 4) and B (4 Times 3). Write a MATLAB script to calculate the product C = AB. Create the product matrix C before you begin the calculation. Write your script in terms of matrix entries cij, aij and bij as described in class. Recall that each element in the product matrix is the dot product of the rows in the first matrix with the columns in the second matrix or, as an equation, cij = k =1n aij bij where n is the inner dimension when forming the product AB. Test that the inner dimensions arc correct before performing the calculation. If the inner dimensions arc not correct display an error and stop. Note that the script should be general and thus should be able to perform the product for any A of dimension 2 Times 4 and B of dimension 4 times 3 specified by the user. Show that your script works by computing the product AB for A = B =Explanation / Answer
A=[3 4 1;
2 3 4];
B=[ 1 2 3;
4 5 6;
7 8 9];
[nRow1,nCol1]=size(A);
[nRow2,nCol2]=size(B);
if nCol1 ~= nRow2
error('inner dimensions must match');
end
C = zeros(nRow1,nCol2);
for i = 1:nRow1
for j = 1:nCol2
for k = 1:nCol1
C(i,j) = C(i,j) + A(i,k)*B(k,j);
end
end
end
C
-------------------------
This gives
C =
26 34 42
42 51 60
To verify
A*B
ans =
26 34 42
42 51 60