特殊的對角矩陣,我試圖做一個numpy的陣列看起來像這樣:請在numpy的
[a b c ]
[ a b c ]
[ a b c ]
[ a b c ]
因此,這涉及到更新的主對角線和兩條對角線上方。
這樣做的有效方法是什麼?
特殊的對角矩陣,我試圖做一個numpy的陣列看起來像這樣:請在numpy的
[a b c ]
[ a b c ]
[ a b c ]
[ a b c ]
因此,這涉及到更新的主對角線和兩條對角線上方。
這樣做的有效方法是什麼?
您可以使用np.indices
來獲取數組的索引,然後在需要的位置分配值。
a = np.zeros((5,10))
i,j = np.indices(a.shape)
i,j
分別是行和列索引。
a[i==j] = 1.
a[i==j-1] = 2.
a[i==j-2] = 3.
將導致:
array([[ 1., 2., 3., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 1., 2., 3., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 1., 2., 3., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 1., 2., 3., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 1., 2., 3., 0., 0., 0.]])
import numpy as np
def using_tile_and_stride():
arr = np.tile(np.array([10,20,30,0,0,0], dtype='float'), (4,1))
row_stride, col_stride = arr.strides
arr.strides = row_stride-col_stride, col_stride
return arr
In [108]: using_tile_and_stride()
Out[108]:
array([[ 10., 20., 30., 0., 0., 0.],
[ 0., 10., 20., 30., 0., 0.],
[ 0., 0., 10., 20., 30., 0.],
[ 0., 0., 0., 10., 20., 30.]])
其他,較慢的替代方案包括:
import numpy as np
import numpy.lib.stride_tricks as stride
def using_put():
arr = np.zeros((4,6), dtype='float')
a, b, c = 10, 20, 30
nrows, ncols = arr.shape
ind = (np.arange(3) + np.arange(0,(ncols+1)*nrows,ncols+1)[:,np.newaxis]).ravel()
arr.put(ind, [a, b, c])
return arr
def using_strides():
return np.flipud(stride.as_strided(
np.array([0, 0, 0, 10, 20, 30, 0, 0, 0], dtype='float'),
shape=(4, 6), strides = (8, 8)))
如果使用using_tile_and_stride
,注意數組是僅適用於只讀目的。否則,如果你嘗試修改數組,則可能會在多個陣列位置的同時改變感到驚訝:
In [32]: arr = using_tile_and_stride()
In [33]: arr[0, -1] = 100
In [34]: arr
Out[34]:
array([[ 10., 20., 30., 0., 100.],
[ 100., 10., 20., 30., 0.],
[ 0., 0., 10., 20., 30.],
[ 30., 0., 0., 10., 20.]])
您可以解決此通過返回np.ascontiguousarray(arr)
,而不是僅僅arr
,但隨後using_tile_and_stride
會慢using_put
。所以如果你打算修改陣列,using_put
將是更好的選擇。
使用我對這個問題的回答:changing the values of the diagonal of a matrix in numpy,你可以做一些棘手的切片來獲得每個對角線的視圖,然後做任務。 在這種情況下,它也只是:
import numpy as np
A = np.zeros((4,6))
# main diagonal
A.flat[:A.shape[1]**2:A.shape[1]+1] = a
# first superdiagonal
A.flat[1:max(0,A.shape[1]-1)*A.shape[1]:A.shape[1]+1] = b
# second superdiagonal
A.flat[2:max(0,A.shape[1]-2)*A.shape[1]:A.shape[1]+1] = c
這是一個Toeplitz matrix的一個例子 - 你可以使用scipy.linalg.toeplitz
構造它:
import numpy as np
from scipy.linalg import toeplitz
first_row = np.array([1, 2, 3, 0, 0, 0])
first_col = np.array([1, 0, 0, 0])
print(toeplitz(first_col, first_row))
# [[1 2 3 0 0 0]
# [0 1 2 3 0 0]
# [0 0 1 2 3 0]
# [0 0 0 1 2 3]]
這是一個很好的解決方案。在提出的所有解決方案中,它在簡單性和性能之間具有良好的平衡。我希望numpy的diag函數可以讓我指定要更新哪個超級/子對角線,然後返回對角線的視圖。這將是最直觀,最快速的。 –