calculating trace of matrix without calculating the matrix itself

2 vues (au cours des 30 derniers jours)
Amir
Amir le 7 Fév 2017
Let's say I have this matrix
tmp = magic(10);
and then I have
vecx= [1,2]
vecy=[3,4]
If I write tmp(vecx,vecy) it generates the matrix of
A= [tmp(1,3), tmp(1,4); tmp(2,3), tmp(2,4)]
but what I want to get is
B=[tmp(1,3), tmp(2,4)].
I understand B= trace(A), but the problem is in my actually code, I can't calculate A, because it is too large and I go out of memory.
How can I calculate B without explicitly calculating A?
Thanks,
  1 commentaire
James Tursa
James Tursa le 7 Fév 2017
We can't answer unless we know what A is and how it is currently calculated. Until we know that, how can we possibly tell you how to calculate only the trace elements of it?

Connectez-vous pour commenter.

Réponses (1)

Roger Stafford
Roger Stafford le 7 Fév 2017
Modifié(e) : Roger Stafford le 7 Fév 2017
Let tmp be an n by n matrix.
B = tmp(vecx+n*(vecy-1)).';
(Note: The ‘trace’ is the sum of the diagonal elements of A, not their vector.)
  1 commentaire
Walter Roberson
Walter Roberson le 7 Fév 2017
The above is pretty much the internal formula used by sub2ind, but calling sub2ind() specifically can be easier to read and understand (but direct calculation can sometimes be much faster.)

Connectez-vous pour commenter.

Catégories

En savoir plus sur Logical 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