Matlab to extract the n th diagonals in a Matrix

1 次查看(过去 30 天)
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))

更多回答(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