Row product and column product
4 views (last 30 days)
Show older comments
5. Recall that if A is an m n matrix and B is a p q matrix, then the product C = AB is denoted if and only if n = p, in which case C is an m q matrix.
(a) 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 3x4 and B is 4x5, 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 denote each column of C). Call the file columnproduct.m.Test your function on a random 5x3 matrix A and a random 3x5 matrix B . Compare the output with A*B. Repeat with 3 x 6 and 6 x 4 matrices and with 3 x 6 and 4 x 6 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.
(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 4x5, the product AB is given by the matrix C = [A(1,:)*B; A(2,:)*B; A(3,:)*B] 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 denote each row of C). Call the file rowproduct.m. Test your function on a random 5x3 matrix A and a random 3x5 matrix B . Compare the output with A*B. Repeat with 3 x 6 and 6 x 4 matrices and with 3 x 6 and 4 x 6 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.
3 Comments
Steven Lord
on 31 Oct 2019
Your code is not correct. You receive A and B from the user of your function (likely your professor) then promptly discard the A and B matrices you received as input and create your own random ones. Just use the matrices you were given.
Once you've corrected that problem, try calling your function with (small) A and B inputs for which you know or can manually compute the correct answer, and see if your function returns the answer you expect. Each time you receive the known / manually computed correct answer, that increases your confidence that your code is correct. If it doesn't return the answer you expect debug the code by stepping through it, section by section or line by line. Then if you made a change to fix the bug, rerun your previous test cases to make sure you haven't broken something that was working previously.
Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!