Computing a weighted sum of matrices

9 vues (au cours des 30 derniers jours)
Berlibur
Berlibur le 10 Mai 2018
Commenté : 均儒 le 4 Mar 2024
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!

Réponse acceptée

James Tursa
James Tursa le 10 Mai 2018
Modifié(e) : James Tursa le 10 Mai 2018
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 commentaire
均儒
均儒 le 4 Mar 2024
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?

Connectez-vous pour commenter.

Plus de réponses (1)

Steven Lord
Steven Lord le 10 Mai 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)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by