Matrix product using for/while loop

2 次查看(过去 30 天)
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

采纳的回答

James Tursa
James Tursa 2021-10-21
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by