Further vectorizing a loop over bsxfun

조회 수: 9 (최근 30일)
Niko
Niko 2011년 11월 5일
I have a vectorization problem that I cannot quite wrap my head around. I have a calculation that requires several parameter sweeps.
Basically, I need to element-wise multiply a matrix A of size m*n and B matrix of size m*p to obtain a matrix Y of size m*n*p. My solution so far is
for i=1:length(B)
Y(:,:,i)=bsxfun(@times,A,B(:,i));
end
This strikes me as unnecessary, surely there must be a way to generalize this to higher dimensions without using loops? Another solution I have cooked up uses repmat, but seems even less elegant.
I hope someone can point into the right direction :)
  댓글 수: 3
Daniel Shub
Daniel Shub 2011년 11월 5일
I am assuming your code is really i=1:size(B, 2), otherwise I get an error.
Niko
Niko 2011년 11월 5일
Indeed, I made a mistake when reducing to a minimal working example. Thank you.

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

채택된 답변

Andrei Bobrov
Andrei Bobrov 2011년 11월 5일
bsxfun(@times,A,reshape(B,size(B,1),1,[]))
or
bsxfun(@times,A,permute(B,[1 3 2]))
  댓글 수: 1
Niko
Niko 2011년 11월 5일
Thank you, exactly what I was looking for.

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

추가 답변 (0개)

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by