calculating trace of matrix without calculating the matrix itself

2 views (last 30 days)
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 Comment
James Tursa
James Tursa on 7 Feb 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?

Sign in to comment.

Answers (1)

Roger Stafford
Roger Stafford on 7 Feb 2017
Edited: Roger Stafford on 7 Feb 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 Comment
Walter Roberson
Walter Roberson on 7 Feb 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.)

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!