Multiply matrix by each element of a vector without a for loop
2 views (last 30 days)
Show older comments
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 Comments
Answers (3)
Star Strider
on 7 Jul 2021
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 Comments
Stephen23
on 7 Jul 2021
Edited: Stephen23
on 7 Jul 2021
Let MATLAB do the heavy lifiting for you! Note that RESHAPE operations are computationally cheap as they do not change the array data themselves, just some of the mxArray meta-data.
A = [1,1;1,1];
v = [1,2,3];
C = num2cell(A.*reshape(v,1,1,[]),1:2);
C{:}
0 Comments
Steven Lord
on 7 Jul 2021
A = [1,1;1,1];
v = [1,2,3];
R = pagemtimes(A, reshape(v, 1, 1, []))
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices 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!