calculating trace of matrix without calculating the matrix itself
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
James Tursa
2017-2-7
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?
回答(1 个)
Roger Stafford
2017-2-7
编辑:Roger Stafford
2017-2-7
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 个评论
Walter Roberson
2017-2-7
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.)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!