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
source to share
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,[])
source to share