如何使用python制作具有不同列表的矩阵?

时间:2017-10-28 17:45:59

标签: python numpy

我正在尝试制作一个矩阵:

s = [[s11 s12 s13 s14]
     [s21 s22 s23 s24]
     [s31 s32 s33 s34]
     [s41 s42 s43 s44]]

我可以通过以下方式获得矩阵的每个数组:

 sii = a(i)  ;  for s11, s22, ... and s44

 sij = b(j)**2 + 10    ;  for s12=s21, s23=s32,s13=s31, ...

这里,a和b是数据列表:

 a = [0.1, 0.25, 0.12, 0.45, 0.98]
 b = [0.1, 0.25, 0.12, 0.45, 0.98, 1]

所以当我使用以下内容时:

 import numpy as np


 a = np.array([0.1, 0.25, 0.12, 0.45, 0.98])
 b = np.array([0.1, 0.25, 0.12, 0.45, 0.98, 1])

 i = 4   # matrix order 
 s = np.ones([i,i])

 def matrix(s):

    for i in range(len(a)):
       s[i,i] = a[i]  
    for j in range(len(b)):        
       rc = (j + 1) % (len(b) - 1)
       val = b[i] 
       s[rc+1, rc] = val           
       s[rc, rc + 1] = val        
    return s

 print(matrix(s)) 

它给了我一个错误。我怎么解决这个问题?感谢。

3 个答案:

答案 0 :(得分:1)

你最好使用库函数。对于非对角元素分配,请使用triutril,如下所示;您也可以使用np.diag

设置对角线
import numpy as np

size=5
off_diag=np.array(range(int(size*(size-1)/2)))
diag=np.array(range(size))*10

s=np.diag(diag)
s[np.triu_indices(size, 1)]=off_diag
s[np.tril_indices(size, -1)]=s.T[np.tril_indices(size, -1)]

print(s)



[[ 0  0  1  2  3]
 [ 0 10  4  5  6]
 [ 1  4 20  7  8]
 [ 2  5  7 30  9]
 [ 3  6  8  9 40]]

答案 1 :(得分:1)

您定义问题的方式仍存在一些问题,但如果您尝试创建矩阵

array([[  1,  12,  13,  14],
       [ 12,   2,  23,  24],
       [ 13,  23,   3,  34],
       [ 14,  24,  34,   4]])

来自数组

a = [1,2,3,4]
b = [12, 13, 14, 23, 24, 34]

然后你可以在没有Python循环的“纯NumPy”中做到这一点:

M = np.zeros((4,4))
M[np.triu_indices(4, 1)] = b
M += M.T
np.fill_diagonal(M, a)

即,从b构建上对角线,通过添加转置使其对称,然后使用a元素填充对角线。

答案 2 :(得分:0)

代码中的数组a包含5个元素,矩阵顺序i设置为4.矩阵s将有shape=(4, 4),您尝试解决第5个元素

for i in range(len(a)):
   s[i,i] = a[i]

尝试

a = np.array([0.1, 0.25, 0.12, 0.45, 0.98]) 
b = np.array([1, 2, 3, 4, 5])

i = 5   # matrix order should correspond to a length
s = np.ones([i,i])