Further vectorizing a loop over bsxfun

9 visualizaciones (últimos 30 días)
Niko
Niko el 5 de Nov. de 2011
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 comentarios
Daniel Shub
Daniel Shub el 5 de Nov. de 2011
I am assuming your code is really i=1:size(B, 2), otherwise I get an error.
Niko
Niko el 5 de Nov. de 2011
Indeed, I made a mistake when reducing to a minimal working example. Thank you.

Iniciar sesión para comentar.

Respuesta aceptada

Andrei Bobrov
Andrei Bobrov el 5 de Nov. de 2011
bsxfun(@times,A,reshape(B,size(B,1),1,[]))
or
bsxfun(@times,A,permute(B,[1 3 2]))
  1 comentario
Niko
Niko el 5 de Nov. de 2011
Thank you, exactly what I was looking for.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre MATLAB en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by