Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vectorizing a weighted sum of matrices in MATLAB

I'm trying to vectorize the following operation in MATLAB, but it's got me stumped. I've learned from experience that there usually is a way, so I'm not giving up just yet. Any help would be appreciated.

I have a collection of m row-vectors each of size n, arranged in an m x n matrix; call it X.

I also have an m-sized vector of weights, w.

I want to compute a weighted sum of the matrices formed by the self outer products of the vectors in X.

Here is a MWE using a for loop:

m = 100;
n = 5;

X = rand(m, n);
w = rand(1, m);

S = zeros(n, n);
for i = 1 : m
    S = S + (w(i) * X(i, :)' * X(i, :));
end

S
like image 905
MGA Avatar asked Mar 17 '23 12:03

MGA


1 Answers

This is probably the fastest approach:

S = X' * bsxfun(@times, X, w(:));

You could also do

S = squeeze(sum(bsxfun(@times, ...
    bsxfun(@times, conj(X), permute(X, [1 3 2])), w(:)), 1));

(or remove the complex conjugate if not needed).

like image 68
Luis Mendo Avatar answered Mar 20 '23 00:03

Luis Mendo