Multiply matrix by each element of a vector without a for loop
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?
Answers (3)
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
.
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{:}
A = [1,1;1,1];
v = [1,2,3];
R = pagemtimes(A, reshape(v, 1, 1, []))
Categories
Find more on Loops and Conditional Statements 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!