Matrix product using for/while loop
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Sedki Ben Salem
el 21 de Oct. de 2021
Comentada: Sedki Ben Salem
el 22 de Oct. de 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 comentarios
Respuesta aceptada
James Tursa
el 21 de Oct. de 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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!