Computing a weighted sum of matrices

24 次查看(过去 30 天)
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!

采纳的回答

James Tursa
James Tursa 2018-5-10
编辑:James Tursa 2018-5-10
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);
  1 个评论
均儒
均儒 2024-3-4
In matlab 2023a, I've tried your method and tested the running time. I found it slower than use for loop to sum one by one, namely:
result = zeros(size(M,1),size(M,2));
for i = 1:size(M,3)
result = result + x(i) * M(:,:,i)
end
Is there any faster way than this for loop?

请先登录,再进行评论。

更多回答(1 个)

Steven Lord
Steven Lord 2018-5-10
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)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by