MATLAB: Efficiently calculating the trace of a matrix product

MATLABmatrix manipulationmatrix multiplicationtrace

I have two NxN square matrices, A and B, and I would like to calculate the trace of AB. Since the trace of AB only depends on its diagonal elements, it should hypothetically not be necessary to compute all of AB, thereby reducing the amount of operations from N^3 to N^2. My question is twofold:
  • Does calling tr(AB) in MATLAB automatically exploit this fact?
  • If not, is there an efficient way of doing this that doesn't involve calling for loops?
Thanks!

Best Answer

Bt=B.';
traceProduct = A(:).'*Bt(:);