python生成三对角矩阵_使用Python的三对角矩阵

我看了过去关于三对角的问题,但似乎没有人遇到我遇到的问题。我试图用,非均匀泊松方程的三对角刚度矩阵scipy.sparse.spdiags但似乎并没有因此收到矩阵。在def Poisson_Stiffness(x0):

N = len(x0) - 1 #THE AMOUNT OF ELEMENTS (NOT THE AMOUNT OF POINTS) x0, x1, ... , x_N

h = np.zeros(N)

a = np.zeros(N+1)

b = np.zeros(N)

for i in range(N):

h[i] = x0[i+1] - x0[i] #Length of each nonuniform element

a[0] = 1/h[0]

for i in range(1,N):

a[i] = 1/h[i] + 1/h[i-1] #Main Diagonal of stiffness matrix

a[N] = 1/h[N-1]

for i in range(N):

b[i] = -1/h[i] #Upper and lower diagonal of stiffness matrix.

Tridiagonal_Data = np.array([[a],[b],[b]])

Positions = [0, 1, -1]

Stiffness_Matrix = scipy.sparse.spdiags(Tridiagonal_Data,Positions,N+1,N+1)

print Stiffness_Matrix

因此,当x0=[0,0.3,0.4,0.7,1]时,得到的刚度矩阵如下:

^{pr2}$

我的问题是为什么它是这样的,而不是矩阵形式?在

我尝试过更改数据类型以查看是否存在问题,但我会收到诸如(for.toarray())之类的错误:Jamess-MBP:Poisson jamesmalone$ python Poisson1d.py

Traceback (most recent call last):

File "Poisson1d.py", line 33, in

Poisson_Stiffness([0,0.3,0.4,0.7,1])

File "Poisson1d.py", line 29, in Poisson_Stiffness

Stiffness_Matrix = scipy.sparse.spdiags(Tridiagonal_Data,Positions,N+1,N+1).toarray()

File "/Users/jamesmalone/anaconda/lib/python2.7/site-packages/scipy/sparse/base.py", line 637, in toarray

return self.tocoo().toarray(order=order, out=out)

File "/Users/jamesmalone/anaconda/lib/python2.7/site-packages/scipy/sparse/coo.py", line 275, in toarray

B.ravel('A'), fortran)

RuntimeError: internal error: failed to resolve data types

提前谢谢。在

你可能感兴趣的:(python生成三对角矩阵)