亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從兩個列表快速創建對角矩陣

從兩個列表快速創建對角矩陣

冉冉說 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 關注
  • 189 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號