MATLAB: Computing a weighted sum of matrices

matrixmatrix manipulationsum

My initial idea was to store my 2D matrices (all of the same size) in a 3D array M. So the third index in M would indicate which 2D matrix I'm referring to. I want to sum these 2D matrices with weights given in vector x.
So, I want to calculate: x(1) * M(:,:,1) + x(2) * M(:,:,2) + … + x(n) * M(:,:,n). In case I would have n 2D matrices. What would be the best way to do this? (possibly avoiding loops, as the number of matrices and their sizes could be big).
note: the 2D matrices would only have 1 and 0 entries, in case that makes a difference
edit: If it would be more efficient to store the 2D matrices in a cell array (or another structure) that would still be of great help!

Best Answer

On later versions of MATLAB:
result = sum(M.*reshape(x,1,1,[]),3);
On earlier versions of MATLAB you need to use bsxfun:
result = sum(bsxfun(@times,M,reshape(x,1,1,[])),3);