Filter löschen
Filter löschen

Matlab to extract the n th diagonals in a Matrix

1 Ansicht (letzte 30 Tage)
Xin
Xin am 5 Sep. 2016
Kommentiert: Xin am 5 Sep. 2016
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.

Akzeptierte Antwort

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

Weitere Antworten (2)

michio
michio am 5 Sep. 2016
Bearbeitet: michio am 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 Kommentar
Xin
Xin am 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.

Melden Sie sich an, um zu kommentieren.


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

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by