multiplying matrix by a vector on an element by element basis using for loops
11 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(2 个)
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)
0 个评论
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];
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!