代码之家  ›  专栏  ›  技术社区  ›  Panos Kalatzantonakis

从两个列表快速创建对角矩阵

  •  2
  • Panos Kalatzantonakis  · 技术社区  · 6 年前

    Diagonal matrix
    一张单子就可以填得满满的 diagonal-constant 另一个将填充矩阵。

    例如:

    fast_matrix([1,2], [6,7,8])

    应输出2个矩阵:

    [2] # unused
    [1, 6, 7, 8]
    [6, 1, 7, 8]
    [6, 7, 1, 8]
    [6, 7, 8, 1]
    

    [1] # unused
    [2, 6, 7, 8]
    [6, 2, 7, 8]
    [6, 7, 2, 8]
    [6, 7, 8, 2]
    

    code makes 10000 transformations

    from pprint import pprint
    import timeit
    
    def not_so_fast_matrix(A, B):
        rt_obj = []
        for i,_ in enumerate(A):
            for z in range(len(B) + 1):
                new_from = A.copy()
                new_from.remove(A[i])
                new_list = B.copy()
                new_list.insert(z, A[i])
                rt_obj.append({'remain': new_from, 'to_list': new_list})
        return rt_obj
    
    # pprint(not_so_fast_matrix([1,2], [6,7,8]))
    
    A = ([1,2,3,4,5,6,7,8,9,10])
    B = ([60,70,80,90,100,200,300])
    t = timeit.Timer(lambda: not_so_fast_toeplitz(A, B))
    print("not_so_fast_matrix took: {:.3f}secs for 10000 iterations".format(t.timeit(number=10000)))
    

    我想知道用另一种方法是否能更快。


    Circulant scipy.linalg 看起来像我要找的但没有滚动:
    from scipy.linalg import circulant
    
    print(circulant([1, 8,7,6])) # <- Should be inverted
    outputs:
    [[1 6 7 8]
     [8 1 6 7]
     [7 8 1 6]
     [6 7 8 1]]
    

    元素被向右移动(推动)。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Ante    6 年前

    转置和展平矩阵有一个重复B元素的结构。该方法使用该属性创建对角线上具有错误值的矩阵蓝图,然后使用正确值填充对角线。

    import numpy
    
    def create_matrices(A, B):
        # Create blueprint of result matrix
        n = len(B) + 1
        b = numpy.empty((n * n,), dtype=numpy.int32)
        b[:-1] = numpy.repeat(B, n + 1)
        b = b.reshape((n, n)).T  # <- added transposition
        # Change diagonal elements
        for a in A:
            m = b.copy()
            numpy.fill_diagonal(m, a)
            print(m)
    
    create_matrices([1, 2], [6, 7, 8])