I'll suggest your mistake is one of definition.
What do you expect when you multiply the elements of the first column with the elements of the first row? In your example, there are 3 products, so that multiplication must result in a vector of length 3.
Oh, do you want to add the elements too? In that case, this is just a matrix multiply.
Taking the columns of matrix a times the rows of matrix b, we get simply:
Learn to use MATLAB!
Do you wish to compute it using loops for homework? While I don't do your homework, you have made a credible effort.
a=[1 2 3;4 5 6;7 8 9];
b=[1 2 3;4 5 6;7 8 9];
sa = size(a,2);
sb = size(b,1);
c= zeros(sa,sb);
for i=1:sa
for j=1:sb
c(i,j)=dot(a(:,i),b(j,:));
end
end
Note my use of size instead of length. length is dangerous here. (Read the help for length to understand why.) As well, I used a dot product. Finally, see that I preallocated c with zeros. This is important.
Your teacher won't even let you use dot?
a=[1 2 3;4 5 6;7 8 9];
b=[1 2 3;4 5 6;7 8 9];
sa = size(a,2);
sb = size(b,1);
sk = size(a,1);
c= zeros(sa,sb);
for i=1:sa
for j=1:sb
for k = 1:sk
c(i,j)= c(i,j) + a(k,i)*b(j,k);
end
end
end
Best Answer