I need to get the indexes of all diagonals in a matrix. The matrix can be non square.
The diag
function gives the values, but I need the coords. So for instance with this: [1 2 3; 4 5 6; 7 8 9]
, I want [1 1; 2 2; 3;3]
PLUS [2 6]
and 3
because they are the upper diagonals of the matrix, and same for below i.e. [4 8]
and 7
. So the full list of indexes is: [1 1; 2 2; 3 3], [1 2; 2 3], [1 3], [2 1], [3 2], [3 1]
.
And I need this in the other diagonal direction too...
And it needs to work for matrices of any shape i.e. not just square ones, including vectors (i.e. 1xn and nx1) - but I guess I can test for these last 2 cases and treat separately.
EDIT: An example of a non square matrix is this 3x2 one:
1 2
3 4
5 6
In this case, the indexes I need are:
[1 1; 2 2]
[2 1; 3 2]
[1 2]
[3 1]
And then the same for diagonals running the other way...
I am aware of the diag
function and can write a bit of code to iterate over the matrices, but I can't then see how to easily turn those values into indexes.
As for why I need this: It's an online course I'm doing in MatLab. An introduction to programming, using MatLab. I'm a reasonably experienced programmer but I'm not familiar with MatLab and I want to learn it more.
The question asks us to find the biggest product of any n
numbers in any direction, i.e. rows, cols, and diagonals (both ways). And the thing is we don't return the product, we return the indexes of the elements making up this product.
I hope this provides more information.
EDIT 2: Sorry for not getting back to you guys, I've been very busy doing other things. When I first posted here, I assumed I was missing something and this would be something that took a few lines. But it's trickier than that, so the code you guys are posting will take me a little more time to go through and understand etc. But I hope to do this today and accept one as an answer. Thanks for all the replies.
alt_diag
gets also the position of the diagonal (-2,-1,0,1,2)? Can you provide an example (input and output) with a non-square matrix? – EBHdiag
to retrieve the values of any of the diagonals, even on non-square matrices. – beakerM(i,i)
and then use linear indexing to move them. Then either convert by hand (which is easy) to (i,j) indices or usesub2ind
. This should be simple if you use linear indexing. Moving the diagonal to the right is the same asidxArray = idxArray+size(M,1)
. Moving the diagonal down would only beidxArray=idxArray+1
. Just remember the diagonal may get shorter... – patrik