我一直试图弄清楚如何使用此功能,但似乎无法获得x
输入来执行任何操作。每当我输入x
的数字值时,它就会告诉我由于“大小”问题而无法使用。
我该怎么办?
import numpy as np
from scipy.sparse import diags, kron, identity
from scipy.sparse.linalg import inv
import matplotlib.pyplot as plt
def laplacian_1D(x):
"""Construct the 1D Laplacian matrix on the domain defined by x. Note that
we assume a constant spacing.
Parameters
----------
x : array-like, shape (nx, )
One dimensional mesh.
Returns
-------
A : scipy sparse matrix, shape (nx, nx)
Laplacian matrix.
"""
# -->
n = x.size
# -->
dx = x[1]-x[0]
# -->
d2 = [np.ones(n-1), -2*np.ones(n), np.ones(n-1)]
# -->
A = diags(d2, [-1, 0, 1]) / dx**2
return A
print(laplacian_1D(10))
读取错误
Traceback (most recent call last):
File "C:/Users/Andrew/PycharmProjects/ENSAM/Math/Exercise_1.py", line 52, in <module>
print(laplacian_1D(10))
File "C:/Users/Andrew/PycharmProjects/ENSAM/Math/Exercise_1.py", line 23, in laplacian_1D
n = x.size
AttributeError: 'int' object has no attribute 'size'
答案 0 :(得分:1)
如参数说明中所述,该函数希望获得一个numpy数组或一个列表作为参数。例如,调用laplacian_1D(x = np.arange(10))
将返回形状为(10,10)的拉普拉斯矩阵。注意,在函数中使用x的唯一方法是确定输出矩阵的大小和dx值。后者告诉您x应该是其元素值递增的列表。