how to plot a 3d surface in matlab

To plot a 3D surface in MATLAB, you can use the surf function. Here's an example on how to do it:

main.m
% Define the x and y coordinates for the surface
x = linspace(-5, 5, 100);
y = linspace(-5, 5, 100);
[X,Y] = meshgrid(x,y);

% Define the function for the surface
Z = sin(sqrt(X.^2 + Y.^2))./(sqrt(X.^2 + Y.^2));

% Plot the 3D surface
figure;
surf(X, Y, Z);

% Customize the plot
title('3D Surface');
xlabel('X');
ylabel('Y');
zlabel('Z');

% Add a colorbar
colorbar;

% Adjust the view angle
view(45, 30);
407 chars
24 lines

In this example, we first define the x and y coordinates for the surface using the linspace function. Then, we use the meshgrid function to create a grid of these coordinates. Taking the surface equation as sine of the distance from the origin, we calculate the corresponding z values. The surf function is then used to plot the surface. Finally, we can customize the plot by adding a title, axis labels, a colorbar, and adjusting the view angle.

Note that you may need to adjust the range of the x and y coordinates, as well as the function used to calculate the z values, according to your specific case.

related categories

gistlibby LogSnag