我正在使用正向差分格式来数值求解一维的扩散函数。我的解决方案的最终图应该是一个曲面,其中解决方案u(x,t)绘制在由x和t值组成的网格上。我已经解决了这个问题,但是我不能使用网格表示来绘制数据。
我可以想到两种方法来解决这个问题:
1.)我的x和t数组应该是一维的,但是我的u数组应该是二维数组。最终,我想要一个方阵,但我很难编码。目前我对u有一个一维数组。这是填充u的代码。
u = zeros(Nx+1) # unknown u at new time level
u_1 = zeros(Nx+1) # u at the previous time level
# Set initial condition u(x,0) = I(x)
for i in range(0, Nx+1):
#set initial u's to I(xi)
u_1[i] = 25-x[i]**2
for n in range(0, Nt):
# Compute u at inner mesh points
for i in range(1, Nx):
u[i] = u_1[i] + F*(u_1[i-1] - 2*u_1[i] + u_1[i+1])2.)上面的代码为u返回一个一维数组,有没有一种方法可以绘制一个三维曲面,其中包含x,y,z的3个1维数组?
发布于 2016-05-06 04:10:57
嗯……,有很多信息你还没提供。例如,你说你想要一个x,y,z图,但没有说在你的图的上下文中x,y和z应该是什么。另外,z通常是z(x,y)。
下面的配方假设t和x,以及u(t,x)作为要放入曲面的变量。我认为这不完全是你的想法,但它应该适应你的锻炼:
EDIT:您的代码(在本食谱中的函数computeU中)有一个Nt循环,该循环似乎没有做任何事情。出于本例的目的,我删除了它。
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
def computeU(Nx,x,F,Nt):
u = np.zeros(Nx+1) # unknown u at new time level
u_1 = np.zeros(Nx+1) # u at the previous time level
# Set initial condition u(x,0) = I(x)
for i in range(0, Nx+1):
#set initial u's to I(xi)
u_1[i] = 25-x[i]**2
#for n in range(0, Nt): # I'm not sure what this is doing. It has no effect.
# Compute u at inner mesh points
for i in range(1, Nx):
u[i] = u_1[i] + F*(u_1[i-1] - 2*u_1[i] + u_1[i+1])
return np.hstack((u[:,np.newaxis],u_1[:,np.newaxis]))
Nx = 10
F = 3
Nt = 5
x = np.arange(11)
t = np.arange(2)
X,Y = np.meshgrid(t,x)
Z = computeU(Nx,x,F,Nt)
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,linewidth=0, antialiased=False)
plt.show()注意我是如何使用meshgrid构建新的t,x (从1D数组)映射到您的U数组堆栈(它们将具有相同的形状X,Y -新的t,x)。结果是这样的:

https://stackoverflow.com/questions/37057327
复制相似问题