필터 지우기
필터 지우기

How can I refer to the diagonals of a matrix?

조회 수: 16 (최근 30일)
Alex
Alex 2014년 2월 18일
답변: Alex 2014년 2월 18일
I'm trying to write a code to refer to the diagonals of a matrix, but I'm having some difficulty doing so. For example, if you have a 5x5 matrix, the diagonals will be made up of the following elements, where the elements are listed in (row,column) fashion:
diagonal 1: (1,1)
diagonal 2: (1,2), (2,1)
diagonal 3: (1,3), (2,2), (3,1)
diagonal 4: (1,4), (2,3), (3,2), (4,1)
diagonal 5: (1,5), (2,4), (3,3), (4,2), (5,1)
diagonal 6: (2,5), (3,4), (4,3), (5,2)
diagonal 7: (3,5), (4,4), (5,3)
diagonal 8: (4,5), (5,4)
diagonal 9: (5,5)
I basically need to store the location of these combinations, (for example, I need to know that the 5th diagonal consists of the elements (1,5), (2,4), etc). A lookup table would not be feasible, because while I'm using a 5x5 matrix for demonstration, I need to use this for a 128x128 matrix (so 255 diagonals).
I'm trying to store the locations then in a cell using for loops, but I'm not sure how to do that. First, I'm trying to write the pattern of the diagonals in the for loops. The diagonals seem to follow two patterns. The first pattern happens for the 1st through Nth diagonals, where N is the size of the matrix (N=5 here, so for the 1st through 5th diagonals). The second pattern happens for the remaining diagonals (so 6 through 9 here).
Here is what I have so far:
%find row/col combinations of x-diags
for k=1:1:5 %counter for counting which diagonal you are on
for i=1:1:i==k %row counter
for j=k-1:-1:j==1 %column counter
end
end
end
for k=6:-1:9 %counter for counting which diagonal you are on
for i=2:1:5 %row counter
for j=5:-1:2 %column counter
end
end
end
That sort of models the trend, but not exactly. The i/row and j/column counters kind of need to update together. Can you & them together? Also, I'm not sure what to actually put inside the for loops to store these locations.

채택된 답변

Paul
Paul 2014년 2월 18일
In case you want to use the diagonal values without saving the locations of the values, you can use diag.
diag(A,0)
is the main diagonal values. diag(A,1) is the diagonal above the main etc.

추가 답변 (1개)

Alex
Alex 2014년 2월 18일
Oh, my. That makes things much easier. Thanks!

카테고리

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