3

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.

1 Answer 1

5

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) 
Sign up to request clarification or add additional context in comments.

3 Comments

:) 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!!
@DeltaIV Would be interesting to see how much faster that is compared to your original solution.
@DeltaIV Thanks! No bsxfun needed here, though :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.