Python 如何按对角线填充矩阵?
我很难用一个m大小的列表填充一个nxn的方阵 我想要实现的是这样的目标:Python 如何按对角线填充矩阵?,python,numpy,Python,Numpy,我很难用一个m大小的列表填充一个nxn的方阵 我想要实现的是这样的目标: arr = np.array([ [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], dtype=float) myList= [1, 2, 3, 4, 5, 6, 7] 下面是一个列表: arr = np.array([ [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]
arr = np.array([
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]], dtype=float)
myList= [1, 2, 3, 4, 5, 6, 7]
下面是一个列表:
arr = np.array([
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]], dtype=float)
myList= [1, 2, 3, 4, 5, 6, 7]
输出应为:
arr = np.array([
[4, 5, 6, 7],
[3, 4, 5, 6],
[2, 3, 4, 5],
[1, 2, 3, 4]], dtype=float)
我的功能正常,但我认为这不是最优雅的方式
def fill_array(img, myList):
arr = np.ones(np.shape(img))
diag_size = (np.shape(img)[0] * 2) - 1
diag_idx = np.median(np.linspace(1, diag_size, diag_size))
# First iterate through the lower half, main diagonal and then upper half
i = 1
while i <= diag_size:
factor = myList[i - 1]
if i < diag_idx:
position = int(diag_idx - i)
np.fill_diagonal(arr[position:, :], factor)
elif i == diag_idx:
np.fill_diagonal(arr[0:, :], factor)
elif i > diag_idx:
position = int(i - diag_idx)
np.fill_diagonal(arr[:, position:], factor)
i += 1
return arr
有更好的解决办法吗?
提前谢谢 让我们大步前进:
输出:
array([[4., 5., 6., 7.],
[3., 4., 5., 6.],
[2., 3., 4., 5.],
[1., 2., 3., 4.]])
让我们大步前进:
输出:
array([[4., 5., 6., 7.],
[3., 4., 5., 6.],
[2., 3., 4., 5.],
[1., 2., 3., 4.]])
首先创建一个函数,返回给定对角线的索引:
def kthDiagIndices(a, offs):
rows, cols = np.diag_indices_from(a)
if offs < 0:
return rows[-offs:], cols[:offs]
elif offs > 0:
return rows[:-offs], cols[offs:]
else:
return rows, cols
请注意,此函数不允许传递太长时间
myList的长度大于可用对角线的数量
另一个需要更改的细节是删除dtype=int,但正如我看到的,您
在整数值上测试函数
为了测试此函数,我创建了:
img = np.ones((4, 4), dtype=int)
myList = [11, 12, 13, 14, 15, 16, 17, 18]
然后我跑:
fill_array(img, myList)
获取:
array([[14, 15, 16, 17],
[13, 14, 15, 16],
[12, 13, 14, 15],
[11, 12, 13, 14]])
使用较短的MyList进行实验。首先创建一个函数,返回给定对角线的索引:
def kthDiagIndices(a, offs):
rows, cols = np.diag_indices_from(a)
if offs < 0:
return rows[-offs:], cols[:offs]
elif offs > 0:
return rows[:-offs], cols[offs:]
else:
return rows, cols
请注意,此函数不允许传递太长时间
myList的长度大于可用对角线的数量
另一个需要更改的细节是删除dtype=int,但正如我看到的,您
在整数值上测试函数
为了测试此函数,我创建了:
img = np.ones((4, 4), dtype=int)
myList = [11, 12, 13, 14, 15, 16, 17, 18]
然后我跑:
fill_array(img, myList)
获取:
array([[14, 15, 16, 17],
[13, 14, 15, 16],
[12, 13, 14, 15],
[11, 12, 13, 14]])
用较短的MyList进行实验。我看到了根据内存管理的注释。你能解释一下为什么我应该使用这个代码,即使文档提到,如果可能的话,我应该避免使用它吗?我看到了内存管理的注释。你能解释一下为什么我应该使用这个代码,即使文档提到,如果可能的话,我应该避免使用它吗?