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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by