Vectorizing/speeding up bsxfun multiplication-loop

조회 수: 1 (최근 30일)
PetterS
PetterS 2015년 4월 12일
댓글: PetterS 2015년 4월 12일
I have a situation that looks like this:
C=zeros(1440,181,8);
for i=1:8
C(:,:,i)=sum(bsxfun(@times,A(:,:,31:end),reshape(B(:,i),1,1,[])),3);
end
Where A is of size=1440x181x2251 and B size=2221x8.
What I want to do is simply perform an element wise multiplication between A(:,:,31:end) and all the rows of the i’th column in B and then store the summation of the third dimension of this in C depending on the address of i. This seemingly simple command is destroying the runtime of my script and I can’t really figure out how to speed it up by avoiding the for loop. I tried replacing the for loop by a parfor to do several loops at the same time but I immediately run out of memory when I try that so it doesn’t work.
Any suggestions?
Thanks

채택된 답변

Roger Stafford
Roger Stafford 2015년 4월 12일
편집: Roger Stafford 2015년 4월 12일
You can try these to see which, if either, is faster than your current method:
C = reshape(reshape(A(:,:,31:end),[],2221)*B,1440,181,8);
or
C = reshape(reshape(A(1440*181*30+1:end),[],2221)*B,1440,181,8);
They should both give the same result as your code. The idea here is to convert to two-dimensional matrix multiplication and then reshape the result back to a three dimensional array, with the hope that Mathworks' matrix multiplication is more efficient than the combined action of 'sum' and 'bsxfun'.
  댓글 수: 1
PetterS
PetterS 2015년 4월 12일
The first suggestion works like a dream! Thank you so much.
(the second one was also faster than my version but it caused a huge memory usage spike of about 10 Gb to run which I can’t afford)

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by