Computing a weighted sum of matrices

6 ビュー (過去 30 日間)
Berlibur
Berlibur 2018 年 5 月 10 日
コメント済み: 均儒 2024 年 3 月 4 日
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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by