Multiply a "stack" of matrices with a "stack" of vectors
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Michael
am 4 Mär. 2014
Kommentiert: James Tursa
am 7 Mär. 2014
I have a matrix 2 x 2 x n and a vector 2 x n. So basically, I have n layers of 2 x 2 matrices and n layers of vectors with 2 entries. I d like to do a matrix-vector multiplication on each layer.
I could easily do this using a for loop, but is there a way which directly supports such an operation?
0 Kommentare
Akzeptierte Antwort
Jos (10584)
am 4 Mär. 2014
Bearbeitet: Jos (10584)
am 7 Mär. 2014
One option:
n = 6
% M is your 2x2xn array of "matrices
M = rand(2,2,n)
% V is your 2xn array of "vectors"
V = rand(2,n)
fh = @(k) M(:,:,k) * V(:,k)
C = arrayfun(fh,1:n,'un',0)
C2 = cat(3,C{:})
Corrected.
3 Kommentare
Jos (10584)
am 7 Mär. 2014
You did ask for " a way which directly supports such an operation ", not for a faster way! ;-)
To be honest, I think a straight forward for-loop is as good as the accumarray approach in this case.
James Tursa
am 7 Mär. 2014
If you want speed, I would suggest looking at one of the solutions I have posted.
Weitere Antworten (1)
James Tursa
am 4 Mär. 2014
Bearbeitet: James Tursa
am 7 Mär. 2014
Some options in the FEX:
C-mex code:
C-mex code:
m-code:
You may need to reshape the 2 x n to a 2 x 1 x n for some of these methods to work.
Also this explicit m-code:
result = sum(bsxfun(@times,M,reshape(v,1,2,n)),2);
0 Kommentare
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!