Multiply matrix by each element of a vector without a for loop
Ältere Kommentare anzeigen
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?
Antworten (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, []))
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!