我想使用一个列表创建一个矩阵,其元素将是矩阵对角线下的元素。
import numpy as np
x1 = np.array([0.9375, 0.75, 0.4375, 0.0, 0.9375, 0.75, 0.4375, 0.9375, 0.75, 0.9375])
x1
我想要的矩阵是
array([[ 1. , 0.9375, 0.75 , 0.4375, 0. ],
[ 0.9375, 1. , 0.9375, 0.75 , 0.4375],
[ 0.75 , 0.9375, 1. , 0.9375, 0.75 ],
[ 0.4375, 0.75 , 0.9375, 1. , 0.9375],
[ 0. , 0.4375, 0.75 , 0.9375, 1. ]])
我以为你可以用np.tril来做到这一点,但它给出了我不期望的结果。
mat = np.tril(x1, k = -1 )
print(mat)
我错过了什么?
如果这是一个微不足道的问题,我提前道歉,但我不知道如何在不循环的情况下解决它。
最佳答案
你可以这样做:
x = np.ones((5, 5), dtype=float)
x[np.triu_indices(5, 1)] = x1 # sets the upper triangle
x[np.triu_indices(5, 1)[::-1]] = x1 # sets the lower triangle
在最后一行中,自 x1
以来索引已反转是为上三角形排序的。您还可以使用x[np.tril_indices(5, -1)] = x1[::-1]
如果这感觉更直观。
关于python - 从 numpy 中对角线下的元素数组创建一个矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30058133/