为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

冉冉说 2021-08-24 18:00:14
给定 2 个列表,我想创建一个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]我的代码在 2.5 秒内在我的电脑上进行了 10000 次转换。from pprint import pprintimport timeitdef 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)))我想知道使用另一种方法是否可以更快。Circulantfromscipy.linalg看起来像我想要的但没有滚动:from scipy.linalg import circulantprint(circulant([1, 8,7,6])) # <- Should be invertedoutputs:[[1 6 7 8] [8 1 6 7] [7 8 1 6] [6 7 8 1]]元素被向右移动(推)。
查看完整描述

1 回答

?
精慕HU

TA贡献1845条经验 获得超8个赞

转置和展平矩阵具有重复来自 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])


查看完整回答
反对 回复 2021-08-24
  • 1 回答
  • 0 关注
  • 173 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号