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

2 次查看(过去 30 天)
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.

采纳的回答

Bruno Luong
Bruno Luong 2024-1-26
编辑:Bruno Luong 2024-1-26
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 个评论
Dyuman Joshi
Dyuman Joshi 2024-1-27
@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 2024-1-29
移动:Bruno Luong 2024-1-29
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')

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by