Computing a weighted sum of matrices

조회 수: 7 (최근 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 CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by