multiplying matrix by a vector on an element by element basis using for loops

조회 수: 17 (최근 30일)
mohamed samhy
mohamed samhy 2022년 3월 30일
답변: Bruno Luong 2022년 3월 31일
Hi All,
i kindly need to multiply matrix A and the vector B on an element-by-element basis using for loop:
code:
A = [1 12 22 10 18; 20 8 13 2 25; 6 19 3 23 14; 4 24 17 15 7; 11 21 16 5 9];
B = [9 7 11 4 23];
[rowsA, colsA] = size(A);
[rowsB, colsB] = size(B);
theMatrixProduct = zeros(rowsA, colsB);
for row = 1 : rowsA
row % Print progress to command window.
for col = 1 : colsB
theSum = 0;
for k = 1 : colsA
theSum = theSum + A(row, k) * B(k, col);
end
theMatrixProduct(row, col) = theSum;
end
end
i get the following error : (Index exceeds matrix dimensions.)
kindly support me what is wrong in the code.
thanks in advance

답변 (2개)

Arif Hoq
Arif Hoq 2022년 3월 31일
try this:
A = [1 12 22 10 18; 20 8 13 2 25; 6 19 3 23 14; 4 24 17 15 7; 11 21 16 5 9];
B = [9 7 11 4 23];
for i = 1:size(A,1)
for j= 1:size(A,2)
C(i,j) = A(i,j)*B(j);
end
end
output=C;
% But if you want make it simple vectorized solution is the most efficient
output2=A.*B; % element wise multiplication
% checking loop output and vectorized output equal or not
isequal(output,output2)
ans = logical
1

Bruno Luong
Bruno Luong 2022년 3월 31일
To be able to compute A*B; You need B is column (vector): the number of rows of B much match the number of rows of A, 5 in this case, B must be initialized as
B = [9; 7; 11; 4; 23];

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by