I am looking for an efficient way (preferably a vectorized fast built-in function) to flatten a numpy array in diagonal order. For example:
A=np.array([[1,2,3],
[4,5,6],
[7,8,9]])
b=flatten_diagonally(A)
b
should be [7,4,8,1,5,9,2,6,3]
.
A
will be a very large matrix so I don't want to iterate over the elements individually. For the same reason I also do not want to prepare in advance a list of all the indices in the correct order. Since A
is large and the result will be equally large, I would like to avoid solutions that use a lot of memory in addition.
It would be even better if I could specify which subset of diagonals I would like to flatten, e.g. flattening only 1st and 2nd diagonals will give [1,5,9,2,6]
.