9.8k views
4 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)] THIS CONTENT IS PROTECTED AND MAY NOT BE SHARED, UPLOADED, SOLD OR DISTRIBUTED 2019 v8 Copyright@ School of Mathematical and Statistical Sciences, Arizona State University 8 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 each column of C). Call the file columnproduct.m. Test your function on a random 5×2 matrix A and a random 2×4 matrix B . Compare the output with A*B. Repeat with 4 × 5 and 5 × 2 matrices and with 4 × 5 and 2 × 5 matrices. Use the command rand to generate the random matrices for testing. Include in your lab report the function M-file and the output obtained by running it.

User Sven Bauer
by
5.0k points

1 Answer

0 votes

Answer:

Here is the code in Matlab for the function.

I have also attached the m file for function as well as the test run of the code here and screenshot of the result.

Code:

function [ C ] = columnproduct( A, B )

% get the dimesnions of A

sizeA = size(A);

sizeB = size(B);

% check if columns of A are same as rows of B

if(sizeA(2) ~= sizeB(1))

error('matrix dimensions do not match')

end

% initialize resultant matrix

C = [];

for i = 1:sizeB(2)

% concatenating product of matrix A with each column of B

C = [C A*B(:,i)];

end

end

Write a function M-file that takes as input two matrices A and B, and as output produces-example-1
User Mick F
by
3.9k points