225k views
5 votes
Write a function M-file that takes as input two matrices A and B, and as output produces

the product by columns of the two matrix.
For instance, if A is 3 � 4 and B is 4 � 5, the product is given by the matrix
C = [A*B(:,1), A*B(:,2), A*B(:,3), A*B(:,4), A*B(:,5)]
The function file should work for any dimension of A and B and it should perform a check to
see if the dimensions match (Hint: use a for loop to define the columns of C). Call the file
columnproduct.m. Generate two random matrices A and B and compare the output of your
function file with the product A*B.
Include in your lab report the function M-file and the output obtained by running it

User Saiwing
by
4.0k points

1 Answer

1 vote

Answer:

Step-by-step explanation:

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

User Dhiresh Budhiraja
by
4.4k points