Lets say there's a numpy matrix with 3 rows and 3 columns. Finding the first diagonal is easy, its a method.
With the following matrix:
[[0,3,6]
[0,4,9]
[0,1,9]]
Using this code:
import numpy
matrix.diagonals()
[0, 4, 9]
How can I get the opposite diagonal? For example with the above matrix I would like it to return:
[6, 4, 0]
The fastest way to achieve this is using strides. Your array has a .strides attribute that tells you how many bytes do you have to skip ahead in memory to get to the next item in each dimension:
>>> a = np.array([[0, 3, 6], [0, 4, 9], [0, 1, 9]])
>>> a.strides
(24, 8)
For the normal forward diagonal you have to skip ahead a row plus a column, for the reverse diagonal, a row minus a column:
>>> a.strides[0] + a.strides[1]
32
>>> a.strides[0] - a.strides[1]
16
You can now construct an array from the same memory buffer as the original array, but with the new stride (and a non-zero offset to start at the last column of the first row in the reverse diagonal case):
>>> np.ndarray(shape=min(a.shape), dtype=a.dtype, buffer=a,
... offset=0, strides=a.strides[0]+a.strides[1])
array([0, 4, 9])
>>> np.ndarray(shape=min(a.shape), dtype=a.dtype, buffer=a,
... offset=a.strides[1] * (a.shape[1] - 1),
... strides=a.strides[0]+a.strides[1])
array([6, 4, 0])
These are actually views into the memory of the original array, i.e. if you modify their content, the original array will change as well, so there is virtually no memory allocation or copying going on, just the setup of the containing objects, so it will be about as fast as it gets.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With