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

1 view (last 30 days)
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.

Accepted Answer

Bruno Luong
Bruno Luong on 26 Jan 2024
Edited: Bruno Luong on 26 Jan 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 Comments
Dyuman Joshi
Dyuman Joshi on 27 Jan 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 on 29 Jan 2024
Moved: Bruno Luong on 29 Jan 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')

Sign in to comment.

More Answers (0)

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!