I have an nxm matrix V, of which I compute the square S=V'*V. For my following computations I need only the diagonal of S, so I write s=diag(V'*V). However, this is a bit of a waste, because I'm computing also all the off-diagonal elements. Is there a fast way to compute only the diagonal elements of S? I could use a for loop, of course, but explicit looping isn't the fast way to do stuff in MATLAB.
Add a comment |
1 Answer
That's easy:
sum(conj(v).*v,1) or
sum(abs(v).^2,1) If the matrix is real, you can simplify to
sum(v.*v,1) or
sum(v.^2,1) 3 Comments
DeltaIV
:) thanks, man - I was sure this would be answered by you. You're my official
bsxfun guru! I like the third one because it's basically the definition of matrix product. I actually needed the diagonal as a column vector, so I modifed it to sum(v.*v,1)', but apart from that it was perfect!!kkuilla
@DeltaIV Would be interesting to see how much faster that is compared to your original solution.
Luis Mendo
@DeltaIV Thanks! No
bsxfun needed here, though :-)