Does MATLAB optimize diag(A*B)?

前端 未结 4 998
予麋鹿
予麋鹿 2021-01-05 10:00

Say I have two very big matrices A (M-by-N) and B (N-by-M). I need the diagonal of A*B. Computing the full A*B requires M

4条回答
  •  轮回少年
    2021-01-05 10:33

    Actually, you can do this faster than a for loop using the wonders of bsxfun:

    diag4 = sum(bsxfun(@times,A,B.'),2)
    

    This about twice as fast as the explicit for loop on my machine for large matrices (2,000-by-2,000 and bigger) and is faster for matrices larger than about 500-by-500.

    Note that all of these methods will produce numerically different results because of the different orders of summation and multiplication.

提交回复
热议问题