Multiply matrix by each element of a vector without a for loop

2 views (last 30 days)
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)

Star Strider
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)
vr = 2×6
1 1 2 2 3 3 1 1 2 2 3 3
Ar = repmat(A,1,3)
Ar = 2×6
1 1 1 1 1 1 1 1 1 1 1 1
M = Ar.*vr
M = 2×6
1 1 2 2 3 3 1 1 2 2 3 3
Mc = mat2cell(M,2,ones(1,3)*2)
Mc = 1×3 cell array
{2×2 double} {2×2 double} {2×2 double}
Mc{1}
ans = 2×2
1 1 1 1
Mc{2}
ans = 2×2
2 2 2 2
Mc{3}
ans = 2×2
3 3 3 3
Generalising this to a different ‘A’:
A2 = [1 2; 3 4];
A2r = repmat(A2,1,3)
A2r = 2×6
1 2 1 2 1 2 3 4 3 4 3 4
M2 = A2r.*vr
M2 = 2×6
1 2 2 4 3 6 3 4 6 8 9 12
See the documentation for repmat, repelem, and mat2cell for details.
.

Stephen23
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{:}
ans = 2×2
1 1 1 1
ans = 2×2
2 2 2 2
ans = 2×2
3 3 3 3

Steven Lord
Steven Lord on 7 Jul 2021
A = [1,1;1,1];
v = [1,2,3];
R = pagemtimes(A, reshape(v, 1, 1, []))
R =
R(:,:,1) = 1 1 1 1 R(:,:,2) = 2 2 2 2 R(:,:,3) = 3 3 3 3

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!