Vectorization of weighted sum of matrices in MATLAB

I am trying to vector animation of the next operation in MATLAB, but this puzzled me. I've learned from experience that there is usually a way, so I'm not giving up yet. Any help would be appreciated.

I have a set m

of vector strings of each size n

arranged in an mxn matrix; name it X

.

I also have a vector of dimensions m, w.

I want to compute the weighted sum of matrices formed by the eigenproducts of vectors in X

.

Here is an MWE using a loop for

:

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

      

+3


source to share


3 answers


This is probably the fastest way:

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

      

You can also do



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

      

(or remove complex conjugate, if not needed).

+3


source


You can use two approaches here, one call and multiple and . The refactoring trick basically allows us to be efficient and thus avoid any additional call that might otherwise be required. bsxfun

permutes

reshapes

matrix multiplication

bsxfun

Approach # 1

[m1,n1] = size(X);
XXmult = bsxfun(@times,X,permute(X,[1 3 2])); %// For X(i, :)' * X(i, :) step
S = reshape(reshape(permute(XXmult,[2 3 1]),[],m1)*w(:),n1,[]) %// multiply weights w

      



Approach # 2

[m1,n1] = size(X);
XXmult = bsxfun(@times,permute(X,[2 3 1]),permute(X,[3 2 1]));
S = reshape(reshape(XXmult,[],m1)*w(:),n1,[])

      

+3


source


The shortest answer and probably the fastest:

S = X '* diag (W) * X

Uses it for filter without Kalman filter, works great.

0


source







All Articles