Hello I am relatively new to the matlab program and am struggling with this assignment.
Recall that if A is an m n matrix and B is a p q matrix, then the product C = AB is defined 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 rows of the two matrices. For instance, if A is 3 4 and B is 4 5, 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 define the rows of C).
I have been able to clear my function of errors so that it returns an answer, however its not coming back as a matrix of the correct dimensions. I get the answer returned row by row it appears. My function is written as follows:
I have typed the following elements into matrices A and B in the command window with the ans following.
I expected a 2x2 matrix with elements [14,14;42,42].
Thanks for the help!

댓글 수: 2

Your first version of this post, with code I could actually copy and run, was preferable. I edited it with the [{}Code] button so the code showed clearly, something you can easily do.
Please do not use screencaps of code! Nobody wants to type it in, and that’s what we have to do in that situation.
The essence (with my edit), copied from the previous correct version:
A=[1,1,1;3,3,3];
B=[2,2;5,5;7,7];
[m,n]=size(A);%Determines dimensions of A
[p,q]=size(B);%Determines dimensions of B
if (p==n) %Check the dimensions of the matrix to determine if its possible
C=zeros(m,q) %Creates a matrix, C, to be filled, initially zeros.
for i=1:m;
C(i,:)=A(i,:)*B %Computes every row of A times matrix B
end
else disp('dimensions do not match') %Dimesions do not match message
C=[];
end
thank you! the C(i,:) part was what we were forgetting... (it was C= in the post)

댓글을 달려면 로그인하십시오.

 채택된 답변

Star Strider
Star Strider 2015년 1월 24일

1 개 추천

You forgot to index ‘C’ !
C(i,:)=A(i,:)*B %Computes every row of A times matrix B
That works.
(It’s best not to use i and j as variables, because MATLAB uses them as its imaginary operators. Not a problem here, but it can cause confusion if you’re dealing with complex numbers.)

댓글 수: 2

WOW fast response!!! That was what I needed. I had attempted variations of this and didn't quite get it.
Much appreciated!
Star Strider
Star Strider 2015년 1월 24일
My pleasure!
And greetings from Albuquerque!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

질문:

2015년 1월 24일

댓글:

2017년 3월 19일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by