how to plot 3d function using surface plot in matlab

To plot a 3D function using a surface plot in Matlab, follow these steps:

  1. Define the function that you want to plot (for example, z = sin(x) + cos(y)).
  2. Create a grid of x and y values using the meshgrid command.
  3. Evaluate the function at each grid point using element-wise array operations.
  4. Use the surf command to create a surface plot of the function.

Here is an example code:

main.m
% Define the function to plot
x = linspace(-pi, pi, 100);
y = linspace(-pi, pi, 100);
[X,Y] = meshgrid(x,y);
Z = sin(X) + cos(Y);

% Create the surface plot
surf(X,Y,Z)
xlabel('x')
ylabel('y')
zlabel('z')
title('Surface plot of sin(x) + cos(y)')
246 chars
13 lines

The meshgrid function creates a grid of x and y values that can be used to evaluate the function at each point. The surf command creates a surface plot of the function using the x, y, and z values. You can customize the plot labels and title using the xlabel, ylabel, zlabel, and title commands.

gistlibby LogSnag