Efficient matrix multiplication with weights
Show older comments
Let A and B be two matrices, say square NxN matrices. Ordinary matrix multiplication A*B implements (A*B)_{ij} = Sum_k A_{ik} B_{kj}. Is there an efficient way in Matlab to implement a weighted version of this product, where we have a matrix of weights W and we want to do :
Weighted(A*B)_{ij} = Sum_k A_{ik} B_{kj} W_{i-j,k}
(let's say here that A and B are triangular so that only i>=j need be considered).
How can I efficiently express Weighted(A*B), avoiding, if possible, for loops and the like ? I would like to keep everything vectorialized / use only matrix products and elements wise products etc.
3 Comments
Matt J
on 20 Jan 2022
I would like to keep everything vectorialized / use only matrix products and elements wise products etc.
Even if for-loops are faster?
Matt J
on 20 Jan 2022
Also, are A and B Toeplitz as well as triangular?
Pierre-Louis Giscard
on 20 Jan 2022
Accepted Answer
More Answers (1)
Using sepblockfun() from,
T=toeplitz(1:N);
WW=W.';
WW=reshape(WW(:,T), N^2,N);
BB=repmat(B,N^2,1);
AA=repmat( reshape(A.',[],1) ,1,N^2);
result=sepblockfun(AA.*WW.*BB, [N,1] , 'sum' ); %
1 Comment
Matt J
on 20 Jan 2022
For N=1000, you would need a lot of RAM for this to work. You might be able to mitigate RAM requiements by using single floats inputs. The result could still be obtained in doubles with,
result=sepblockfun(AA.*WW.*BB, [N,1] , @(x,d)sum(x,d,'double') ); %
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!