Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast way to compute only the diagonal of the square of a matrix

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.

like image 551
DeltaIV Avatar asked Nov 26 '25 17:11

DeltaIV


1 Answers

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)
like image 94
Luis Mendo Avatar answered Nov 28 '25 07:11

Luis Mendo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!