Matlab to extract the n th diagonals in a Matrix

1 view (last 30 days)
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.

Accepted Answer

Thorsten
Thorsten on 5 Sep 2016
d = [2 4]; A(sub2ind(size(A), d, d))

More Answers (2)

michio
michio on 5 Sep 2016
Edited: michio on 5 Sep 2016
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 Comment
Xin
Xin on 5 Sep 2016
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.

Sign in to comment.


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

Community Treasure Hunt

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

Start Hunting!