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

2 ビュー (過去 30 日間)
Anne Davenport
Anne Davenport 2024 年 1 月 26 日
移動済み: Bruno Luong 2024 年 1 月 29 日
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 Center および File ExchangeLogical についてさらに検索

製品


リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by