フィルターのクリア

Matlab to extract the n th diagonals in a Matrix

1 回表示 (過去 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;
  1 件のコメント
Xin
Xin 2016 年 9 月 5 日
Thanks. That works.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by