A quick way to calculate only the diagonal of a square of a matrix

I have a matrix nxm

V

from which I am calculating the square S=V'*V

. For my next calculations, I only need the diagonal S

, so I am writing s=diag(V'*V)

. However, this is a bit of a waste because I am calculating all off-diagonal elements. Is there a quick way to calculate only diagonal elements S

? Of course I could use a loop for

, but an explicit loop is not a fast way to do things in MATLAB.

Thank!!!

+3


source to share


1 answer


It's easy:

sum(conj(v).*v,1)

      

or

sum(abs(v).^2,1)

      



If the matrix is ​​valid you can simplify

sum(v.*v,1)

      

or

sum(v.^2,1)

      

+5


source







All Articles