python - ValueError : x and y must have the same first dimension

标签 python numpy matplotlib compiler-errors

我正在尝试使用NumPy在Python中实现有限差分逼近来求解热方程u_t = k * u_{xx}

这是我正在运行的代码的副本:

    ## This program is to implement a Finite Difference method approximation
## to solve the Heat Equation, u_t = k * u_xx,
## in 1D w/out sources & on a finite interval 0 < x < L. The PDE
## is subject to B.C: u(0,t) = u(L,t) = 0,
## and the I.C: u(x,0) = f(x).
import numpy as np
import matplotlib.pyplot as plt

# parameters    
L = 1 # legnth of the rod
T = 10 # terminal time
N = 10 
M = 100
s = 0.25

# uniform mesh
x_init = 0
x_end = L
dx = float(x_end - x_init) / N

x = np.arange(x_init, x_end, dx)
x[0] = x_init

# time discretization
t_init = 0
t_end = T
dt = float(t_end - t_init) / M

t = np.arange(t_init, t_end, dt)
t[0] = t_init

# Boundary Conditions
for m in xrange(0, M):
    t[m] = m * dt

# Initial Conditions
for j in xrange(0, N):
    x[j] = j * dx

# definition of solution u(x,t) to u_t = k * u_xx
u = np.zeros((N, M+1)) # array to store values of the solution

# Finite Difference Scheme:
u[:,0] = x**2 #initial condition

for m in xrange(0, M):
    for j in xrange(1, N-1):
        if j == 1:
            u[j-1,m] = 0 # Boundary condition
        elif j == N-1:
            u[j+1,m] = 0
        else:
            u[j,m+1] = u[j,m] + s * ( u[j+1,m] - 
            2 * u[j,m] + u[j-1,m] )

print u, #t, x
plt.plot(u, t)
#plt.show()

我认为我的代码工作正常,并且正在产生输出。我想绘制解决方案ut(我的时间 vector )的输出。如果可以绘制该图,则可以检查我的数值近似值是否符合热方程的预期现象。但是,我得到一个错误,即“x和y必须具有相同的第一维”。我该如何解决这个问题?

另一个问题:我是否最好尝试使用matplotlib.animation制作动画,而不是使用matplotlib.plyplot

非常感谢您提供的所有帮助!非常感谢!

最佳答案

好的,所以我有了一个“大脑转储”,尝试绘制ut的关系,却忘记了作为热方程式(u)的解决方案u_t = k * u_{xx}被定义为u(x,t),因此它具有时间值。我对代码进行了以下更正:

print u #t, x
plt.plot(u)
plt.show()

现在,我的编程终于可以显示图像。这里是:

enter image description here
绝对漂亮,不是吗?

关于python - ValueError : x and y must have the same first dimension,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38257616/

相关文章:

Python '&' 字符丢失

python - numpy dtype 中的 > < 符号是什么意思?

python - 如何分享 matplotlib 风格?

python - 如何导入行列不规则的文本数据文件?

python - 如何填充 pandas 中缺失的 GPS 数据?

python - 将圆盘形掩码应用于 NumPy 数组中的多个位置

python - 为什么 numpy 不会计算一个 5 元素列表而不是另一个的标准偏差?

python - 中心 Seaborn 颜色条标签

python - Jupyter 笔记本不再在外部窗口中打开 matplotlib 图?

python - 名称错误 : name 'index' is not defined