I need to get the diagonal "stripe" of a matrix. Say I have a matrix of size KxN (K>N):
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
From it I need to extract a diagonal stripe, in this case, a matrix MxV size that is created by truncating the original one:
[[ 0 x x]
[ 3 4 x]
[ x 7 8]
[ x x 11]]
So the result matrix is:
[[ 0 4 8]
[ 3 7 11]]
I could define a bolean mask like so:
import numpy as np
X=np.arange(12).reshape(4,3)
mask=np.asarray([
[ True, False, False],
[ True, True, False],
[ False, True, True],
[ False, False, True]
])
>>> X
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
>>> X.T[mask.T].reshape(3,2).T
array([[ 0, 4, 8],
[ 3, 7, 11]])
But I don't see how such a mask could be automatically generated to an arbitrary KxN matrix (e.g. 39x9, 360x96)
Is there a function that does this automatically either in numpy
, scipy
or pytorch
?
Additional question: is it possible to get a "reverse stripe" instead? i.e.
[[ x x 2]
[ x 4 5]
[ 6 7 x]
[ 9 x x]]