Computing a weighted sum of matrices
Show older comments
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!
Accepted Answer
More Answers (1)
Steven Lord
on 10 May 2018
If you're using a release that supports implicit expansion (release R2016b or later) reshape your vector to be a 3-dimensional array then use element-wise multiplication and the sum function.
R = rand(2, 3, 4) > 0.5
x = [1 2 4 8];
x3 = reshape(x, 1, 1, []);
S = sum(R.*x3, 3)
You can check that the S computed above is the same as the S2 generated by explicitly expanding out the summation:
S2 = 1*R(:, :, 1)+2*R(:, :, 2)+4*R(:, :, 3)+8*R(:, :, 4)
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!