get a diagonal line in matrix

Hi, please help me get a diagonal line in matlab. Example, I have a matrix: a = [1 2 3; 4 5 6; 7 8 9] I want to get vector b =[3 5 7] which is a diagonal line of matrix a. This is my code but it doesn't work
a=[1 2 3; 4 5 6; 7 8 9];
b = zeros(1,3);
for i=1:3
for i=1:3
b = a(i,j);
end
end

 採用された回答

Jan
Jan 2017 年 8 月 21 日
編集済み: Jan 2017 年 8 月 21 日

0 投票

Or:
a = [1 2 3; 4 5 6; 7 8 9];
s = size(a);
index = (numel(a) - s(1) + 1):(1 - s(1)):s(2);
b = a(index)
[EDITED, works with non square matrices now]

3 件のコメント

dao
dao 2017 年 8 月 22 日
Thank you so much Jan Simon and Star Strider for the answer.
But how could I use the two for loop to this work ? I am a newbie and I want to get used to with the loop in matlab. Thank you.
Jan
Jan 2017 年 8 月 22 日
If you really want a loop:
b = zeros(1,3);
for i = 1:3
b(i) = a(i, 4 - i);
end
dao
dao 2017 年 8 月 22 日
Thank you for your answer, it is neat. in my case, the column and row are equal. How about they are different. Example, I have a matrix 3x4 ? Do I need to use two loop ?

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

その他の回答 (1 件)

カテゴリ

ヘルプ センター および File ExchangeOperating on Diagonal Matrices についてさらに検索

質問済み:

dao
2017 年 8 月 21 日

コメント済み:

dao
2017 年 8 月 22 日

Community Treasure Hunt

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

Start Hunting!

Translated by