Effacer les filtres
Effacer les filtres

Matlab to extract the n th diagonals in a Matrix

1 vue (au cours des 30 derniers jours)
Xin
Xin le 5 Sep 2016
Commenté : Xin le 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.

Réponse acceptée

Thorsten
Thorsten le 5 Sep 2016
d = [2 4]; A(sub2ind(size(A), d, d))
  1 commentaire
Xin
Xin le 5 Sep 2016
Thank you Thorsten. That does solve the problem. :)

Connectez-vous pour commenter.

Plus de réponses (2)

michio
michio le 5 Sep 2016
Modifié(e) : michio le 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 commentaire
Xin
Xin le 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.

Connectez-vous pour commenter.


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

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by