Hi,
The error you're encountering arises because "np.meshgrid" in Python and "mesh" in MATLAB have some differences in how they handle dimensions and inputs. In your case, "Z" should indeed be a 2-dimensional array for the "plot_surface" function in Matplotlib.
Here's a corrected version of your Python code that should work:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
T = np.zeros((n, m, tmax))
h[j] = (y[j] + y[j-1])/2 if j > 0 else y[j]/2
z[i] = (x[i] + x[i-1])/2 if i > 0 else x[i]/2
T[j, i, 0] = 0 # Note: Use 0 instead of 1 for the first time step
# Extract the first time slice of T
fig = plt.figure(figsize=(14, 8))
ax = fig.add_subplot(projection='3d')
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)
fig.colorbar(surf, shrink=0.5, aspect=5)
Explanation of Differences:
MATLAB "mesh":
- In MATLAB, mesh(X, Y, Z) assumes X, Y, and Z are 2D matrices that define the grid and the surface height.
To know more about "mesh" function, check out:
Python "np.meshgrid":
- "np.meshgrid" in Python creates coordinate matrices from coordinate vectors. The resulting X and Y are 2D arrays suitable for surface plotting.
To know more about "meshgrid" function, check out:
Hope it helps