Get the diagonal without calculating the explicit matrix

2 vues (au cours des 30 derniers jours)
Long Hong
Long Hong le 26 Mar 2020
Modifié(e) : Matt J le 26 Mar 2020
Dear all:
I am trying to calculate a diagonal of a matrix (denoted A), which is formed by multiplying two large-dimensional matrices (denoted as B*C).
A naive way to do it is: first, calculating explicitly A = B*C, then get diagonal out from A. However, the first step takes forever to run due to the high-dimension of B and C. But the only thing I need is the diagonal of A.
Another straightforward way in my mind is: I could create a loop by calculating each element of the diagonal of A one by one. It will surely save a lot of time, but I am not sure if this is the most efficient way.
I am wondering if anyone knows a faster/smarter way to calculate it.
Thank you very much in advance!
Best,
Long
  1 commentaire
Matt J
Matt J le 26 Mar 2020
Modifié(e) : Matt J le 26 Mar 2020
The best approach will depend on the dimensions of the matrices, and whether they are of sparse-type or not.

Connectez-vous pour commenter.

Réponse acceptée

Matt J
Matt J le 26 Mar 2020
Modifié(e) : Matt J le 26 Mar 2020
Assuming B*C results in a square matrix,
diagonal=sum(B.' .* C, 1);
  8 commentaires
Long Hong
Long Hong le 26 Mar 2020
Thank you the cyclist! Do you have any insight in doing the transpose quicker? I am a bit confused here.
Matt J
Matt J le 26 Mar 2020
Modifié(e) : Matt J le 26 Mar 2020
the cyclist means you might avoid the transpose by loading data column-wise instead of row-wise when you first build B.

Connectez-vous pour commenter.

Plus de réponses (1)

the cyclist
the cyclist le 26 Mar 2020
Here is one way:
% Make up some inputs
N = 4;
B = rand(N);
C = rand(N);
% Calculate the diagonal
A_diag = 0;
for nr = 1:N
A_diag = A_diag + B(:,nr).*C(nr,:)';
end
  1 commentaire
Long Hong
Long Hong le 26 Mar 2020
Thanks the cyclist! This is a method I have applied currently.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Operating on Diagonal Matrices dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by