How to do a layered matrix--vector multiplication without a for loop?

3 visualizaciones (últimos 30 días)
I would like to multiply a 3-D matrix of NNN transformations by a 2-D matrix of NNN vectors without the for loop below:
% RR is an (NNN x 3) array of vectors.
% TT is a 3-D array of NNN (3 x 3) matrices.
for iii = 1:1:NNN
TRR(iii,:) = TT(:,:,iii) * RR(iii, 3);
end
The array of transformed vectors is an (NNN x 3) matrix.
I have tried pagemtimes() with no luck. Any help would be much appreciated.

Respuesta aceptada

Bruno Luong
Bruno Luong el 26 de En. de 2024
Editada: Bruno Luong el 26 de En. de 2024
NNN = 10;
RR = rand(NNN, 3);
TT = rand(3,3,NNN);
for iii = 1:1:NNN
TRR(iii,:) = TT(:,:,iii) * RR(iii, :).'; % Bug fix
end
TRR1 = permute(pagemtimes(TT, reshape(RR.', 3, 1, [])), [3 1 2]);
norm(TRR-TRR1, 'inf')
ans = 0
% EDIT:
TRR
TRR = 10×3
0.5562 0.5086 1.2347 1.1149 0.9370 0.9763 0.6643 0.4458 0.6342 0.3462 0.4368 0.3715 0.3473 0.4736 0.2898 1.6595 0.6729 1.2345 0.9500 1.4171 1.9221 0.9745 1.1071 0.8333 0.4928 1.1708 1.0786 1.0319 0.6400 1.3485
TRR1
TRR1 = 10×3
0.5562 0.5086 1.2347 1.1149 0.9370 0.9763 0.6643 0.4458 0.6342 0.3462 0.4368 0.3715 0.3473 0.4736 0.2898 1.6595 0.6729 1.2345 0.9500 1.4171 1.9221 0.9745 1.1071 0.8333 0.4928 1.1708 1.0786 1.0319 0.6400 1.3485
  4 comentarios
Dyuman Joshi
Dyuman Joshi el 27 de En. de 2024
@Anne Davenport, the elements do match, see the edit above.
You can directly check like this as well -
NNN = 10;
RR = rand(NNN, 3);
TT = rand(3,3,NNN);
for iii = 1:1:NNN
TRR(iii,:) = TT(:,:,iii) * RR(iii, :).'; % Bug fix
end
TRR1 = permute(pagemtimes(TT, reshape(RR.', 3, 1, [])), [3 1 2]);
all(TRR-TRR1==0, 'all')
ans = logical
1
Anne Davenport
Anne Davenport el 29 de En. de 2024
Movida: Bruno Luong el 29 de En. de 2024
Thank-you again for your quick response. It worked for me this time.
I don't know how many times I can stare at a typo in my code and not see it, but my pride prevents me from saying just what dastardly typo I fat-fingered into your solution. This bit of code from above works just fine and answers my question.
TRR1 = permute(pagetimes(TT, reshape(RR.', 3, 1,[])),[3 1 2])
norm(TRR-TRR1, 'inf')

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2023b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by