Matrix product using for/while loop
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Sedki Ben Salem
am 21 Okt. 2021
Kommentiert: Sedki Ben Salem
am 22 Okt. 2021
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
0 Kommentare
Akzeptierte Antwort
James Tursa
am 21 Okt. 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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!