1

Suppose I have two 5000 x 1000 matrices, A and B. Will octave compute trace(A*B') efficiently, i.e. in a way that only requires 5000 inner products as opposed to 5000*5000 inner products most of which will not be used?

And, what if the argument to trace is more complicated, i.e.: trace(A*B' + C*D')? Does that change anything?

ErikR
  • 51,541
  • 9
  • 73
  • 124

2 Answers2

2

trace(A*B') will compute the complete matrix product before using trace().

A more efficient approach would be sum(sum(A.*conj(B),2)). The inner sum computes the diagonal of the resulting matrix.

A probably even more efficient approach would be doing both sums in one step via `sum((A.*conj(B))(:)).

trace(A*B' + C*D') would be computed efficiently by sum((A.*conj(B) + C.*conj(D))(:)).

Community
  • 1
  • 1
Twonky
  • 445
  • 9
  • 12
1

No, the product will be evaluated before the call to trace(). One efficient implementation would be to manually compute only the diagonal terms of that matrix multiply and then sum them sum(sum(diag(A) .* diag(B))); for your second example sum(sum(diag(A) .* diag(B) + diag(C) .* diag(D)))

Note that you can shorten both expressions slightly and possibly gain a bit of speed at the loss of readability and Matlab compatibility like so: sum((diag(A) .* diag(B))(:));

thirdhaf
  • 138
  • 7