简体   繁体   中英

ValueError: x and y must have the same first dimension

I am trying to implement a finite difference approximation to solve the Heat Equation, u_t = k * u_{xx} , in Python using NumPy.

Here is a copy of the code I am running:

    ## 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()

I think my code is working properly and it is producing an output. I want to plot the output of the solution u versus t (my time vector). If I can plot the graph then I am able to check if my numerical approximation agrees with the expected phenomena for the Heat Equation. However, I am getting the error that "x and y must have same first dimension". How can I correct this issue?

An additional question: Am I better off attempting to make an animation with matplotlib.animation instead of using matplotlib.plyplot ???

Thanks so much for any and all help! It is very greatly appreciated!

Okay so I had a "brain dump" and tried plotting u vs. t sort of forgetting that u , being the solution to the Heat Equation ( u_t = k * u_{xx} ), is defined as u(x,t) so it has values for time. I made the following correction to my code:

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

And now my programming is finally displaying an image. And here it is:

在此处输入图片说明 It is absolutely beautiful, isn't it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM