How can I refer to the diagonals of a matrix?
15 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
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.
0 个评论
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!