Multiply matrix by each element of a vector without a for loop
2 次查看(过去 30 天)
显示 更早的评论
If I have a matrix A and a vector v filled with scalars, how to I multiply A by each element of v, storing each result in an array as I go without using a for loop.
For example, if I have
A = [1,1;1,1]
v = [1,2,3]
I want to get an array M that is
M = {[A.*v(1)],[A.*v(2)],[A.*v(3)]} = {[1,1;1,1],[2,2;2,2],[3,3;3,3]}
Is there any way to do this without a for loop?
0 个评论
回答(3 个)
Star Strider
2021-7-7
This may be considered ‘cheating’, however it does meet the requirements:
A = [1,1;1,1];
v = [1,2,3];
vr = repelem(v,2,2)
Ar = repmat(A,1,3)
M = Ar.*vr
Mc = mat2cell(M,2,ones(1,3)*2)
Mc{1}
Mc{2}
Mc{3}
Generalising this to a different ‘A’:
A2 = [1 2; 3 4];
A2r = repmat(A2,1,3)
M2 = A2r.*vr
.
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!