Creating An Identity Matrix Containing Diagonally Determined Values
Essentially, I'm looking for an efficient piece of code to generate the following matrix: [[1 2 3 4 5] [2 3 4 5 6] [3 4 5 6 7] [4 5 6 7 8] [5 6 7 8 9]] I came up with the foll
Solution 1:
You're apparently describing a type of Hankel matrix.
>>>from scipy.linalg import hankel>>>hankel(c=range(1,6), r=range(5,10))
array([[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[3, 4, 5, 6, 7],
[4, 5, 6, 7, 8],
[5, 6, 7, 8, 9]])
The Hankel matrix has constant anti-diagonals. The arguments c
and r
specify the first column and the last row, respectively.
Solution 2:
You can achieve this in a simple one-liner with a list comprehension. I'm afraid that I don't know a numpy
-specific way of doing this, but you could always convert to an array afterwards.
matrix = [[x for x in range(y,y+5)] for y in range(1,6)]
Solution 3:
Here's an approach using NumPy strides
-
a = np.arange(1,10)
W = 5# Row length / Window sizenrows = a.size - W + 1n = a.strides[0]
out = np.lib.stride_tricks.as_strided(a,shape=(nrows,W),strides=(n,n))
Another way with broadcasting
-
np.arange(10-W)[:,None] + np.arange(1,W+1)
Solution 4:
Just throwing out another numpy-based option:
In [21]: np.arange(1,26).reshape(5,5) - np.arange(0, 20, 4)[np.newaxis].T
Out[21]:
array([[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[3, 4, 5, 6, 7],
[4, 5, 6, 7, 8],
[5, 6, 7, 8, 9]])
or generalized to an arbitrary size:
In [29]: N = 10
In [30]: np.arange(N**2).reshape(N,N) - np.arange(0, N*(N-1), N-1)[np.newaxis].T + 1
Out[30]:
array([[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
[ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
[ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
[ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
[ 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
[ 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
[ 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
[ 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]])
Solution 5:
How about this? using map
and np.vstack
N = 5
x = np.arange(1,2*N)
np.vstack(map(lambda i: np.roll(x, -i), range(N)))[:,0:N]
Post a Comment for "Creating An Identity Matrix Containing Diagonally Determined Values"