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!