필터 지우기
필터 지우기

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