3

I am looking for a fast and flexible way to compute the following in Matlab without using a loop:

c = 1:5;
A = reshape(1:5^3,5,5,5);
res= c(1)*A(:,:,1)+...+c(5)*A(:,:,5) 

I think, working with

sum(A,3) 

could be a nice way as long as I am able to perform the multiplication along the third dimension. One solution (but with loops) would be:

val = zeros(length(c),length(c))
for i = 1:length(c)
    val = val+c(i)*A(:,:,i)
end

I am just wondering if this can be done in a simpler (and more elegant) way avoiding the loop.

Divakar
  • 218,885
  • 19
  • 262
  • 358
Stefan Voigt
  • 209
  • 2
  • 5
  • 18
  • Clarify a liitle bit better your question . you want to multiple what? – 16per9 Apr 20 '16 at 08:43
  • I want to obtain res at the end of the day.. So in other words, I would like to multiply the whole Matrix A(:,:,1) with the scalar c(1), the whole Matrix A(:,:,2) with the scalar c(2) and so on...at the end I want to sum up each of those five matrices, such that res is a matrix. – Stefan Voigt Apr 20 '16 at 08:45

2 Answers2

6

You can reshape A from 3D to 2D, use the very efficient matrix-multiplication, which will give you a 1D array and finally reshape back to 2D for the final output, like so -

res = reshape(reshape(A,[],size(A,3))*c(:),size(A,1),[])
Community
  • 1
  • 1
Divakar
  • 218,885
  • 19
  • 262
  • 358
4

Yes, this is a perfect job for bsxfun and permute:

res = sum(bsxfun(@times,A,permute(c,[3,1,2])),3)

You send c to the third dimension using permute(c,[3,1,2]). Then, by calling bsxfun, each of the matrices in A is multiplied by the corresponding (permuted) c. Finally, you can do a sum over the third dimension.

hbaderts
  • 14,136
  • 4
  • 41
  • 48