How can i vectorize a matrix multiplication of higher dimension arrays?

조회 수: 2 (최근 30일)
Anthony Barone
Anthony Barone 2016년 4월 1일
답변: Steven Lord 2020년 9월 17일
I want to multiply a 6x6 matrix A and a 6x1 vector B at every grid point in a 3D earth model. Currently I am doing this:
for ix=1:length(x)
for iy=1:length(y)
for iz=1:length(z)
C(:,ix,iy,iz)=squeeze(A(:,:,ix,iy,iz))*squeeze(B(:,ix,iy,iz));
end
end
end
Is there a way to vectorize this? Currently this segment of nested loops is by far the slowest part of my code (almost 90% of the time taken every iteration is spent in this nested loop). Thanks!
  댓글 수: 1
Anthony Barone
Anthony Barone 2016년 4월 1일
I have found an answer, but I still wanted to post it incase anyone else has a similiar situation. I did this:
for n=1:6
C(n,:,:,:)=sum(squeeze(A(n,:,:,:,:)).*B);
end
For me, this method proved to be ~30x faster than my initial method.

댓글을 달려면 로그인하십시오.

답변 (2개)

Steven Lord
Steven Lord 2020년 9월 17일
If you're using release R2020b or later, take a look at the pagemtimes function introduced in that release.

Matt J
Matt J 2016년 4월 1일
Using mtimesx ( Download )
C=mtimesx( reshape(A,6,6,[]) , reshape(B,6,1,[]) );
C=reshape(C,size(B));

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by