1
©2009 by L. Lagerstrom
Plotting in 3D
• Plotting a function z = f(x,y)
• Experimenting with the interval size
• How meshgrid creates the grid
• Common error
• Surface plots
• Changing the shading and coloring
• Adding lighting effects
• Contour plots
• Combining 3D and contour plots
©2009 by L. Lagerstrom
Note re. Code and Display
•
In the code examples that follow, we will often have the results
displayed simply by leaving off the semi-colon at the end of
assignment statements. (The results will be displayed in a
simulated Command window.)
•
In addition, we will assume that the display format has been set
to “format bank” (i.e., results displayed to 2 decimal places),
simply to save space.
•
Finally, the display of the results will have blank lines in it for
readability, but the code that would create those blank lines
(e.g.,
disp(‘ ’)
) will not be shown in the code examples
(again, for readability’s sake).
©2009 by L. Lagerstrom
Plotting a Function z = f(x,y)
•
When we learned to plot a function y = f(x), there were three basic
steps:
1. Define a row vector of x values.
2. Calculate the corresponding y values.
3. Plot the (x,y) values using the plot function.
•
When we are plotting a function of two variables, z = f(x,y), the
process is similar, but with one key extra step (#2):
1. Define row vectors of x and y values.
2. Create an (x,y) grid of points using the x and y values in
step 1. (To do so, we use the "meshgrid" function.)
3. Calculate the corresponding z value for each (x,y) grid point.
4. Plot the (x,y,z) results using one of several possible 3D
plotting functions (e.g., mesh, surf, meshc).
Matlab code
Command window display
©2009 by L. Lagerstrom
Plotting a Function z = f(x,y)
%As an example, consider the function
%z = y*exp(-(x^2 + y^2)) plotted for
%x = -2 to 2 and y = -1 to 2.
%Define some x and y values at
%intervals of 0.1:
x = -2:0.1:2;
y = -1:0.1:2;
%Use meshgrid function to create
%the (x,y) grid of points:
[X Y] = meshgrid(x,y);
%Calculate Z values using X,Y grid of
%points (note use of dot operators):
Z = Y.*exp(-(X.^2 + Y.^2));
%Use mesh function with the X,Y,Z
%values to create a mesh plot:
figure(1), clf
mesh(X,Y,Z)
title('z = y*exp(-(x^2 + y^2))')
xlabel('x'), ylabel('y'), zlabel('z')
[Plot shown on next slide.
..]