lolibility
lolibility

Reputation: 2187

Matlab efficiently take diagonal values of a matrix product

I have two matrices, a is 2000 by 20000, b is also 2000 by 20000. I want to get the diagonal elements of a'*b. I used diag(a'*b) but it is very slow (about 20 seconds), since calculating non-diagonal elements takes time. I am wondering if there are faster ways to do this.

I noticed people do something like sum((T*H).*T',2), here is the link. But it is required that T is a square matrix. How about non-square matrix in my case?

Thanks

Upvotes: 1

Views: 295

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112679

The diagonal of a'*b is just

result = sum(a'.*b.',2);

Example (with non-square matrices):

>> a = rand(4,5);
>> b = rand(4,5);
>> result = sum(a'.*b.',2)
result =
    1.6102
    0.2805
    1.5354
    0.3966
    1.1896

>> diag(a'*b)
ans =
    1.6102
    0.2805
    1.5354
    0.3966
    1.1896

Upvotes: 1

Related Questions