How can i index a matrix to do implicit multiplication to each value in a row with a vector?
9 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
David Hill
2019-9-21
A(:,1:3).*s
1 个评论
Stephen23
2019-9-21
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)
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!