Matlab to extract the n th diagonals in a Matrix

조회 수: 2 (최근 30일)
Xin
Xin 2016년 9월 5일
댓글: Xin 2016년 9월 5일
I have a matrix, for example A=[ 1 0 0 0 ; 0 2 0 0 ; 0 0 3 0 ; 0 0 0 4]; I want to reference to the n th diagonal, for example the 2nd and 4th ones, that means [2,4]. Is there a elegant way to do this without using a loop. I tried using A([2,4],[2,4]) but it gave a 2*2 matrix. Anybody knows how to do this? Thanks.

채택된 답변

Thorsten
Thorsten 2016년 9월 5일
d = [2 4]; A(sub2ind(size(A), d, d))
  댓글 수: 1
Xin
Xin 2016년 9월 5일
Thank you Thorsten. That does solve the problem. :)

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

michio
michio 2016년 9월 5일
편집: michio 2016년 9월 5일
Have you considered using diag function?
A=[ 1 0 0 0 ; 0 2 0 0 ; 0 0 3 0 ; 0 0 0 4];
dA = diag(A);
dA([2,4])
ans =
2
4
  댓글 수: 1
Xin
Xin 2016년 9월 5일
Thanks a lot for your answer Michio. I actually wanted to index the 2nd and 4th components. This will give me the number but I actually need to change the value of the 2nd and 4th components.

댓글을 달려면 로그인하십시오.


Andrei Bobrov
Andrei Bobrov 2016년 9월 5일
A = randi(9,5);
n = [2,4];
A(sub2ind(size(A),n,n)) = 100*n;

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by