如何以对角线方向填充矩阵?

时间:2020-09-18 15:38:31

标签: python numpy

我无法用大小为n x n的列表填充m的方阵。

我想要实现的是这样的:

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

是否有更好的解决方案? 预先感谢!

2 个答案:

答案 0 :(得分:3)

让我们尝试as_strided

from numpy.lib.stride_tricks import as_strided

out = as_strided(np.array(myList, dtype=arr.dtype), 
                 shape=arr.shape, 
                 strides=arr.strides[1:]*2)[::-1]

输出:

array([[4., 5., 6., 7.],
       [3., 4., 5., 6.],
       [2., 3., 4., 5.],
       [1., 2., 3., 4.]])

答案 1 :(得分:0)

首先创建一个返回给定对角线索引的函数:

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

然后将生成数组的函数定义为:

def fill_array(img, myList):
    arr = np.ones_like(img, dtype=int)
    # How many diagonals can be filled
    diagNo = min(len(myList), img.shape[0] * 2 - 1)
    # Shift from the index in myList to the diagonal offset
    diagShift = diagNo // 2
    # Fill each diagonal in arr
    for i, v in enumerate(myList):
        arr[kthDiagIndices(arr, i - diagShift)] = v
    return arr

请注意,此功能“抵抗”传递时间过长 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 较短的实验。

相关问题