***MATLAB**Write a function M-file that takes as input two matrices A and B, and
ID: 3787079 • Letter: #
Question
***MATLAB**Write a function M-file that takes as input two matrices A and B, and as output produces the product by rows of the two matrices.
(b) Write a function M-file that takes as input two matrices A and B, and as output produces the product by rows of the two matrices. For instance, if A is 3 x 4 and B is 4 x 5, the product AB is given by the matrix CA (1, B; A (2, :)*B; A(3, :)*B] The function file should work for any dimension of A and and it should perform a check to see if the dimensions match (Hint: use a for loop to define the rows of C). Call the file product Test your function on a random 2 x 3 matrix A and a random 3 x 2 matrix B. Compare the output with A B. Repeat with 3 x 4 and 4 x 2 matrices and with 3 x 4 and 2x 4 matrices Include in your lab report the function M-file and the output obtained by running itExplanation / Answer
The Matlab Function rowproduct.m
function C = rowproduct( A,B) % The function rowproduct.m
M = size(A); % Getting the dimension of matrix A
N = size(B); % Getting the dimension of matrix B
if(M(2)~=N(1)) % Checking the dimension
fprintf('Error in matrix dimension '); % print error if dimension mismatch
return; % And end the further execution of function
end % End of if condition
C = []; % initilizing the result matrix C
for k = 1:M(1) % Loop to perform the row product
C = [C;A(k,:)*B];% Computing row product and updating matrix C
end % End of loop
end % End of function
Testing the function rowproduct.m
The 2x3, 3x2 Matrix:
>> A = [ 1 2 3; 1 2 3];
>> B = [1 2; 1 2; 1 2];
>> C = rowproduct(A,B)
C =
6 12
6 12
>> A*B
ans =
6 12
6 12
The 3x4, 4x2 matrix:
>> A = [ 1 2 3 4; 1 2 3 4; 1 2 3 4];
>> B = [1 2; 1 2; 1 2; 1 2];
>> C = rowproduct(A,B)
C =
10 20
10 20
10 20
>> A*B
ans =
10 20
10 20
10 20
The 3x4 and 2x4 matrix:
>> A = [ 1 2 3 4; 1 2 3 4; 1 2 3 4];
>> B = [1 2 1 2; 1 2 1 2];
>> rowproduct(A,B)
Error in matrix dimension
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.