where row i A is the ith row of matrix A and col j B is the jth column of the ma
ID: 2261792 • Letter: W
Question
where rowiA is the ith row of matrix A and coljB is the jth column of the matrix B. Follow the following instructions and define a function mat_prod in MATLAB taking two matrices as input and their product as the output.
i. Check the dimension of the input matrices and make sure the matrix product is defined. (hint:size)
ii. Initialize the output matrix C as zero matrix with the right size.
iii. Use TWO loops to iterate over each row and column in C to update the value of Cij.
iv. In each iteration, use the vector dot function in part (a) to update the element in C. <----im still working on part a
Write an m script to test your function with the following cases:
i.A=ones(3), B=hilb(3).
ii.A=ones(3,2), B=hilb(2).
iii.A=(1:3)’, B=1:3.
iv.A=ones(2,3), B=hilb(4).
Include the output in your homework.
The matrix product between A ER"Xm and B e s defined by Cij row A col,B, i1, ,n;j-1,..I. 23Explanation / Answer
MATLAB code
close all
clear
clc
fprintf('Example (i) ');
A = ones(3); B = hilb(3);
C = mat_prod(A,B)
fprintf(' Example (ii) ');
A = ones(3,2); B = hilb(2);
C = mat_prod(A,B)
fprintf(' Example (iii) ');
A = (1:3)'; B = 1:3;
C = mat_prod(A,B)
fprintf(' Example (iv) ');
A = ones(2,3); B = hilb(4);
C = mat_prod(A,B)
function C = mat_prod(A,B)
if size(A,2) ~= size(B,1)
disp('Invalid Dimensions');
C = 0;
else
C = zeros(size(A,1), size(B,2));
for i=1:size(C,1)
for j=1:size(C,2)
C(i,j) = vec_dot_prod(A(i,:),B(:,j));
end
end
end
end
function D = vec_dot_prod(A,B)
if length(A) ~= length(B)
disp('Vector Dimensions Doesn''t Match');
D = 0;
else
D = 0;
for i=1:length(A)
D = D + A(i)*B(i);
end
end
end
output
Example (i)
C =
1.8333 1.0833 0.7833
1.8333 1.0833 0.7833
1.8333 1.0833 0.7833
Example (ii)
C =
1.5000 0.8333
1.5000 0.8333
1.5000 0.8333
Example (iii)
C =
1 2 3
2 4 6
3 6 9
Example (iv)
Invalid Dimensions
C =
0
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.