How can i index a matrix to do implicit multiplication to each value in a row with a vector?
8 views (last 30 days)
Show older comments
I have a matrix, A of size (a x b) and a vector s of size (1 x b) and I want to multiply each row of A with s.
I am trying to use a for loop to index each of the 'a' rows of matrix A and then index along the 'b' columns and multiply each value with the corresponding index of vecor s. This should then return a new matrix B that is the same size as matrix A, however I cannot get this to work. This is my code;
A = rand(8,3);
s = rand(1,3);
for i = 1:size(A,1)
c = A(i,:);
for ii = 1:size(A,2)
x(ii) = c(ii)*s(ii);
end
end
Please note: I do not want to simply multiply the two together, I am aware that i can transpose and get a resulting a x 1 size vector - this is not the solution I want to achieve.
0 Comments
Accepted Answer
David Hill
on 21 Sep 2019
A(:,1:3).*s
1 Comment
Stephen23
on 21 Sep 2019
Given that "A of size (a x b) and a vector s of size (1 x b)", then the indexing is not required:
A.*s
(Of course this assumes R2016b or later)
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!