plot a surface plot given two 2-d functions in matlab

To plot a surface plot given two 2-D functions in MATLAB, we can follow these steps:

  1. Define the two 2-D functions using meshgrid and z variable to represent the function values.
main.m
[x,y] = meshgrid(-3:0.1:3);    
z1 = sin(x+y);
z2 = x.*exp(-x.^2-y.^2);
72 chars
4 lines
  1. Create a new figure and a new axes for the surface plot.
main.m
figure();
axes_new = axes();
29 chars
3 lines
  1. Use the surf function to plot the surface. Set the Parent property of this function to be the newly created axes object.
main.m
surf(axes_new, x, y, z1);   % For the first function
surf(axes_new, x, y, z2);   % For the second function
107 chars
3 lines
  1. Customize the plot as needed using standard MATLAB functions like colorbar, title, and xlabel/ylabel/zlabel.
main.m
colorbar();                     
title('Surface Plot of Two Functions');
xlabel('X-Axis');
ylabel('Y-Axis');
zlabel('Z-Axis');
127 chars
6 lines

Here is the complete code:

main.m
[x,y] = meshgrid(-3:0.1:3);

z1 = sin(x+y);
z2 = x.*exp(-x.^2-y.^2);

figure();
axes_new = axes();

surf(axes_new, x, y, z1);
surf(axes_new, x, y, z2);

colorbar();
title('Surface Plot of Two Functions');
xlabel('X-Axis');
ylabel('Y-Axis');
zlabel('Z-Axis');
259 chars
17 lines

This code generates a surface plot of the two functions defined by z1 and z2.

Note that the range of x and y used in meshgrid determines the domain of the functions, and the resolution of the plot is determined by the spacing used in meshgrid.

related categories

gistlibby LogSnag