필터 지우기
필터 지우기

get a diagonal line in matrix

조회 수: 4 (최근 30일)
dao
dao 2017년 8월 21일
댓글: dao 2017년 8월 22일
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일
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
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개)

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by