Explicitly Multiplication of Matrices using For Loops
55 views (last 30 days)
Show older comments
I understand the concept of this, but only for when the matrices are the same size.
I now have Matrix A which is a 3x5 matrix and Matrix B which is a 5x4 matrix. I want to multiply the two explicitly using For loops. Can anyone help ?
Thanks in advance !
2 Comments
Answers (2)
Andrei Bobrov
on 1 Oct 2016
Edited: Andrei Bobrov
on 1 Oct 2016
s1 = size(A);
s2 = size(B,2);
out=zeros(s1(1),s2);
for ii = 1:s1(1)
for jj = 1:s2
p=0;
for k = 1:s1(2)
p = p + A(ii,k)*B(k,jj);
end
out(ii,jj)=p;
end
end
John D'Errico
on 1 Oct 2016
Edited: John D'Errico
on 1 Oct 2016
Well, you do show some code. Lets see how we can write it to help you out. First, understand that a matrix multiply is just a set of dot products. So we can define the (ii,jj) element of the result as just
C(ii,jj) = dot(A(ii,:),B(:,jj))
Or, I could write it as:
C(ii,jj) = A(ii,:)*B(:,jj);
That too is a dot product, between the corresponding vectors.
Unfortunately, we can't just leave it like that, as MATLAB won't understand what we are writing. We need to put loops around it, defining ii and jj using for loops.
[ra,ca] = size(A);
[rb,cb] = size(B);
C = zeros(ra,cb);
for ii= 1:ra
for jj = 1:cb
C(ii,jj) = dot(A(ii,:),B(:,jj));
end
end
Note that I preallocated C. That was important.
Anyway, written as loops around a dot product, the above code will work. But really, this requires a triple set of loops, because the dot product itself can/should/might be expanded.
[ra,ca] = size(A);
[rb,cb] = size(B);
C = zeros(ra,cb);
for ii= 1:ra
for jj = 1:cb
% expanded: C(ii,jj) = dot(A(ii,:),B(:,jj));
for k = 1:ca
C(ii,jj) = C(ii,jj) + A(ii,kk)*B(kk,jj);
end
end
end
Note that ca and rb MUST be the same for the matrices in a matrix multiply to conform for multiplication.
The preallocation of C allows us to simply accumulate the results directly in place.
This final form is what the code would look like, if you saw it written in (very) old school fortran, etc.
See Also
Categories
Find more on Loops and Conditional Statements 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!