# 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