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

4 views (last 30 days)
mohamed samhy
mohamed samhy on 30 Mar 2022
Answered: Bruno Luong on 31 Mar 2022
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

Answers (2)

Arif Hoq
Arif Hoq on 31 Mar 2022
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 on 31 Mar 2022
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];

Community Treasure Hunt

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

Start Hunting!