Matrix product using for/while loop

1 view (last 30 days)
I got this task and I should find the error in this function hat should give us the product of 2 martices .
function [M_erg] = matrix_mult(M1,M2)
M_erg = zeros(size(M1,1),size(M2,2));
for i = 1:1:size(M1,1)
for j = 1:1:size(M2,2)
k=1;
while (k<=size(M1,1))
M_erg(i,j) = M_erg(i,k) + M1(i,k) * M2(k,j);
k=k+1;
end
end
end
end

Accepted Answer

James Tursa
James Tursa on 21 Oct 2021
The inner most loop needs to iterate over the 2nd index of M1, not the first index. E.g.,
while (k<=size(M1,2)) %<-- 2nd index
M_erg(i,j) = M_erg(i,j) + M1(i,k) * M2(k,j); %<-- also fixed typo for M_erg(i,j)
Note that the inner most loop could be written as a for-loop also.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!