MATLAB Array Manipulation Tips and Tricks
MATLAB Array Manipulation Tips and Tricks is a collection of very useful tips and tricks regarding array manipulation in Matlab. The main focus is on memory requirements and computing time, which is mostly achieved by vectorization of for-loops or other clever knacks. This can save you hours!
10.1.7 Keeping only diagonal elements of multiplication
Assume X and Y are two m-by-n matrices and that W is an n-by-n matrix. How does one vectorize the following for-loop
Z = zeros(m, 1); for i = 1:m Z(i) = X(i,:)*W*Y(i,:)'; end
Two solutions are
Z = diag(X*W*Y'); % (1) Z = sum(X*W.*conj(Y), 2); % (2)
Solution (1) does a lot of unnecessary work, since we only keep the n diagonal elements of the n^2 computed elements. Solution (2) only computes the elements of interest and is significantly faster if n is large.