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.

2
  • Clarify a liitle bit better your question . you want to multiple what? Commented Apr 20, 2016 at 8: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. Commented Apr 20, 2016 at 8:45

2 Answers 2

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),[])
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.