calculating trace of matrix without calculating the matrix itself

조회 수: 1 (최근 30일)
Amir
Amir 2017년 2월 7일
편집: Roger Stafford 2017년 2월 7일
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
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
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
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 CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by