Matrix product using for/while loop

조회 수: 1 (최근 30일)
Sedki Ben Salem
Sedki Ben Salem 2021년 10월 21일
댓글: Sedki Ben Salem 2021년 10월 22일
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에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by