23
1 Computer Lab #1: Plotting in 3D 1.1 Using “ez” plotting For a quick plot of a curve or surface, you can use the the “ez” plotting proce- dures. For example, suppose you want to plot the surface z = x 2 - 2xy +3y +2 over the rectangle -4 x 4 and -3 y 3. At the Matlab prompt type: ezsurf(’x^2-2*x*y+3*y+2’, [-4 4 -3 3]); (note the single quotes around the function, and the brackets and spacing for the domain). The plot will appear in a separate window. Here are some points about ez-plotting. You can plot curves in 3D as well. For example, the command: ezplot3(’cos(t)’,’sin(t)’,’t’,[-2*pi 2*pi]); will plot a helix in 3-space. You can make contour plots; for example: ezcontour(’x^2-2*x*y+3*y+2’, [-4 4 -3 3]); ezcontourf(’x^2-2*x*y+3*y+2’, [-4 4 -3 3]); (the second one produces a more colorful plot). While the plot is on the screen, you can rotate it. Simple drag it (slowly!) vertically or horizontally with the mouse. Ez plotting is fine if you have a simple function and want a simple and quick plot. However, to work with complicated functions or to superimpose several plots, you will need to use m-files; here’s how to do this. 1.2 Setting up a plot grid and function As an example we will use the same function as above: z = x 2 - 2xy +3y + 2. The first step is to set up vectors that represent the range of x and y values. As before we will plot over the region -4 x 4 and -3 y 3. Plotting on a grid of about 50 x 50 should be quite adequate, so we set up these vectors as follows: x=-4:.1:4; y=-3:.1:3; We have to make a grid of points over which we want the heights of the surface. MatLab provides a command for this: [X,Y] = meshgrid(x,y); 1

1 Computer Lab #1: Plotting in 3D - Northeastern Universitymathserver.neu.edu/~braverman/Teaching/Fall2002/Lab...The simplest way of getting a surface plot is the MatLab command surf(X,Y,Z)

Embed Size (px)

Citation preview

Page 1: 1 Computer Lab #1: Plotting in 3D - Northeastern Universitymathserver.neu.edu/~braverman/Teaching/Fall2002/Lab...The simplest way of getting a surface plot is the MatLab command surf(X,Y,Z)

1 Computer Lab #1: Plotting in 3D

1.1 Using “ez” plotting

For a quick plot of a curve or surface, you can use the the “ez” plotting proce-dures. For example, suppose you want to plot the surface z = x2− 2xy +3y +2over the rectangle −4 ≤ x ≤ 4 and −3 ≤ y ≤ 3. At the Matlab prompt � type:

ezsurf(’x^2-2*x*y+3*y+2’, [-4 4 -3 3]);

(note the single quotes around the function, and the brackets and spacing forthe domain). The plot will appear in a separate window. Here are some pointsabout ez-plotting.

• You can plot curves in 3D as well. For example, the command:

ezplot3(’cos(t)’,’sin(t)’,’t’,[-2*pi 2*pi]);

will plot a helix in 3-space.

• You can make contour plots; for example:

ezcontour(’x^2-2*x*y+3*y+2’, [-4 4 -3 3]);

ezcontourf(’x^2-2*x*y+3*y+2’, [-4 4 -3 3]);

(the second one produces a more colorful plot).

• While the plot is on the screen, you can rotate it. Simple drag it (slowly!)vertically or horizontally with the mouse.

Ez plotting is fine if you have a simple function and want a simple and quickplot. However, to work with complicated functions or to superimpose severalplots, you will need to use m-files; here’s how to do this.

1.2 Setting up a plot grid and function

As an example we will use the same function as above: z = x2 − 2xy + 3y + 2.The first step is to set up vectors that represent the range of x and y values.As before we will plot over the region −4 ≤ x ≤ 4 and −3 ≤ y ≤ 3. Plotting ona grid of about 50 x 50 should be quite adequate, so we set up these vectors asfollows:

x=-4:.1:4; y=-3:.1:3;

We have to make a grid of points over which we want the heights of thesurface. MatLab provides a command for this:

[X,Y] = meshgrid(x,y);

1

Page 2: 1 Computer Lab #1: Plotting in 3D - Northeastern Universitymathserver.neu.edu/~braverman/Teaching/Fall2002/Lab...The simplest way of getting a surface plot is the MatLab command surf(X,Y,Z)

(X and Y will hold the rows and columns of this grid; we could have used anyletters for these variables.) Note that we have placed a semicolon (;) after eachcommand:1 this suppresses the long list of components which MatLab generatesas it creates these vectors.

We create Z from the variables X and Y as follows:

Z = X.^2 - 2*(X.*Y) + 3*Y + 2;

(Note the dot . when multiplying vectors or raising them to powers.)Now we are ready to plot. The simplest way of getting a surface plot is the

MatLab command surf(X,Y,Z). This gives a “standard” view with standardcolors. There are other palettes of colors available; they are chosen using thecolormap command. A good all-purpose choice is colormap(jet), which isalso good for contour plots. Other color schemes are: hsv, hot, cool, pink,gray, bone, copper, prism, and flag. It is also possible to rotate the plotin 3D to get different views. In order to do this, issue the command rotate3don before doing any plotting. Now, once you plot the surface, you can rotateit by dragging with the mouse: try it.

Once you issue a drawing command such as surf(X,Y,Z), a window con-taining the plot will be created. To get back to the MatLab command line toadjust the plot (without deleting it), either collapse the window without clos-ing it (click on the “-” in Windows) or click on whatever part of the MatLabworksheet is visible outside the window. It also helps to add semi-colons to eachplotting command, so that the window is not reopened each time you add tothe plot.

Here, then, is the sequence of commands we might use:

� x=-4:.1:4; y=-3:.1:3;� [X,Y]=meshgrid(x,y);� Z=X.^2-2*(X.*Y)+3*Y+2;� colormap(jet);� rotate3d on� surf(X,Y,Z);

1.3 Surfaces and Contours

There are several variations on surface plotting which you may want to exper-iment with. Instead of surf(X,Y,Z), try surfl(X,Y,Z), shading interp ormesh(X,Y,Z) or meshc(X,Y,Z) (adding a “c” combines the surface plot with aplot of the contours in the xy-plane).

You can plot contour curves for the function z = x2 − 2xy + 3y + 2 createdin the previous section. Instead of the surf command, use MatLab’s contour

2

Page 3: 1 Computer Lab #1: Plotting in 3D - Northeastern Universitymathserver.neu.edu/~braverman/Teaching/Fall2002/Lab...The simplest way of getting a surface plot is the MatLab command surf(X,Y,Z)

drawing command; for example: contour(X,Y,Z,30). This will draw a contourplot on the screen, with 30 different contour levels. They will be color coded,using the same colors as the surface plot. You can also make a 3D contour plotusing contour3(X,Y,Z).

It is sometimes very effective to draw both a surface and a contour plot atthe same time. To accomplish this, we have to tell MatLab that we want bothplots in the same window. This is accomplished using the hold on command.Until the hold off command is issued (or the graphing window closed), allplots drawn will be superimposed, one on the other. We also have to “raise”the surface plot a bit so that it doesn’t get in the way of the contour plot, whichis always drawn in the x, y-plane (z = 0). We do this by simply adding someconvenient number to Z when plotting. The sequence which does the trick isthe following:

� surf(X,Y,Z+5)� hold on;� contour(X,Y,Z+5,30);

1.4 Using M-files

As you can see, there are lots of parameters that one may want to set in plottingsurfaces. Also, the equations themselves take a while to type in. The secret tosaving time and being able to make adjustments easily is to use m-files, bothfor defining the function and for scripting the commands. Here is a file definingthe function we have been using.

func1.mfunction z =func1(x,y;f=’x^2 - 2*(x*y) + 3*y + 2’;z=eval(vectorize(f));

Since we have called the function func1, we have to name this file func1.mso that MatLab can find it when we use it. It is also worth taking some time tosee how this definition works. We first define f to be a certain series of symbols,enclosed in single quotes: ’ ’. This is the only part you have to change ifyou want to change how this function is computed. The command vectorizesimply adds the correct dots to make this a legal vector definition; for example,vectorize changes the x*y to x.*y. The eval command orders MatLab totreat this as a function to be computed, rather than an array of symbols.

Now we can write a script which creates the plot. Here is a sample whichdraws the surface and the contour plot. (You create this m-file by clicking onthe File menu at the top of the Matlab window, and clicking the “m-file” choice.This opens up an editing window in which you can type in the code below. Save

3

Page 4: 1 Computer Lab #1: Plotting in 3D - Northeastern Universitymathserver.neu.edu/~braverman/Teaching/Fall2002/Lab...The simplest way of getting a surface plot is the MatLab command surf(X,Y,Z)

the m-file but leave the window open so that you can edit it if you made amistake. Run it by typing example1 at the Matlab command prompt

. Note that the “%” indicates a comment which is to be ignored by Matlab.)

example1.mcolormap(jet); % Set colorsx=-4:.1:4; y=-3:.1:3; % Set up x and y as vectors[X,Y]=meshgrid(x,y); % Form the grid for plottingZ=func1(X,Y); % Create the heightsrotate3d on; % Activate interactive mouse rotationsurf(X,Y,Z+20), shading interp; % Draw surfacehold on; % Allow for more without erasingcolorbar; % Add key to contour colorsxlabel(’x’); ylabel(’y’); % Label axescontour3(X,Y,Z+20,30); % 3D contour plot over surfacecontour(X,Y,Z+20,30); % 2D contour plot in xy-plane

• If you don’t want to use a separate m-file for the function, replace theZ=func1(X,Y)command by the line: Z=X.^2-2*(X.*Y)+3*Y + 2.

• Adding 20 to the Z-values to show more of the contours was discoveredby experiment – another reason for using m-files.

• The colorbar command adds a strip to the right of the plot that showswhich contour colors correspond to which function values.

• Since the contour3 and the surf command use the same colors in the sameplaces, you can’t see 3D contours; however, they will appear in a blackand white printout.

IMPORTANT: When multiplying “scalar” variables or raising them topowers, MatLab requires that you use a “dot” before each multiplication (*) orpower (ˆ) sign. For example, the function Z=X.^2-2*(X.*Y)+3*Y + 2 above, orthe term x3y2 cos(z), which would be typed in as: (X.^3).*(Y.^2).*cos(Z).

As a final example, this file produces a plot showing that the curve x =− sin(t) sin(2t), y = sin(t) cos(2t), z = cos(t), appears to lie on the unit sphere.It illustrates parametric plotting of curves and surfaces.

4

Page 5: 1 Computer Lab #1: Plotting in 3D - Northeastern Universitymathserver.neu.edu/~braverman/Teaching/Fall2002/Lab...The simplest way of getting a surface plot is the MatLab command surf(X,Y,Z)

figure8.ms=0:.1:pi; t=0:.1:2*pi;[S,T]=meshgrid(s,t);mesh(sin(S).*cos(T), sin(S).*sin(T), cos(S));hold on;h=plot3(-sin(T).*sin(2*T), sin(T).*cos(2*T), cos(T));set(h, ’linewidth’,4);rotate3d on;

Compare the mesh drawing with the surf drawing: the first draws a grid ornet, while the second fills in the surface. Plot3 graphs curves in space by givingtheir x, y and z coordinates in terms of a parameter – in this case, t. Setting h= plot3( ) enables MatLab to change the properties of this particular plot usingthe set command.

1.5 Building Peaks and Pits

The family of curves y = e−kx2looks like a series of “bumps” of height 1, all

centered at x = 0. Use your calculator or MatLab to plot a few, for k = 1, 2, 3, 4and −2 ≤ x ≤ 2, on the same set of axes. The curves in the family are similar,but the bigger k, the steeper the curve. We can center the bumps around thepoint x = a and make them of height c by using y = ce−k(x−a)2 instead. Hereis an m-file called mt.m which creates three dimensional hills in the same way:

mt.m% mt creates a peak or pit centered at (a,b)% The max/min height is c (negative for pit, = min)% It uses a function of type exp(-kr$\wedge$2); large% values of k make slimmer peaks% z = mt(x,y) is the height over the point (x,y)

function z = mt(a,b,c,k,x,y);f=’c*exp(-k*((x-a)^2+(y-b)^2))’;z=eval(vectorize(f));

If we create vectors X and Y as before, then we can create a single peakat (1, 1) of height 3 with steepness 4, by writing Z1=mt(1,1,3,4,X,Y) andplotting . We can create a “pit” (opposite of a peak) at (0,−1) of depth3 by writing Z2=mt(0,-1,-3,4,X,Y). We can plot both with the commandsurf(X,Y,Z1+Z2).

5

Page 6: 1 Computer Lab #1: Plotting in 3D - Northeastern Universitymathserver.neu.edu/~braverman/Teaching/Fall2002/Lab...The simplest way of getting a surface plot is the MatLab command surf(X,Y,Z)

1.6 Exercises to Hand In

1. Create and print out a surface plot and a contour plot for the functionz = (x2 + 2y2)e1−x2−y2

over the rectangle −2 ≤ x, y ≤ 2. (Be careful touse dots.) You may have to rotate the surface plot a bit to get a goodview. The contour plot should be separate, but you may want to plotcontours on the same axes as the surface plot as well. Credit will be basedon the quality of the plots. Find out how to label them, or label them byhand.

2. Using the mt(a,b,c,k,X,Y) function described above, you can piece to-gether surfaces from peaks and pits. Unfortunately, these mountains andvalleys interfere with each other, so that when we add several together,their heights and centers aren’t exactly where you expect them to be. Thiseffect can be reduced by making k large, so that the height or depth of apeak or pit approaches 0 very quickly as you move away from its center(a, b).

• Demonstrate this interference and its improvement by creating somecontour plots, each containing two nearby peaks/pits and each witha different value of k (e.g. k = 0.5, k = 2, k = 7).

• Create a single surface which has a peak of height 2 near (1, 1), apeak of height 3 near (1, 1/2), and a pit of depth −3.5 near (−1, 1).Print out a good view and a contour diagram (or both in one plot ifyou want).

3. The surfaces z = x2 − y2 and z = xy are called “saddles” (centered at(0, 0)). Draw a saddle and, separately, its contour plot.

4. Plot z = 4500 − 105x2 − 105y2 + 3y2x + 3x2y + 0.8x4 + 0.8y4 over thesquare −10 ≤ x, y ≤ 10 (use y=x=-10:.1:10; y=x and be careful of yourdots.). How many peaks and pits do you see? What about saddle-shapedpieces? Print out a contour plot and label peaks, pits, saddles. Zoom inon a saddle (by changing the axes or resizing x and y) and see if you geta contour diagram resembling the one in the previous exercise.

5. (Optional) Plot an interesting surface of your choosing. Here’s one of ourfavorites:

z = cos(x + y) cos(3x− y) + cos(x− y) sin(x + 3y) + 5e−(x2+y2)/8

(cos(X+Y).*cos(3*X-Y)+cos(X-Y).sin(x+3*Y)+5*exp(-(X.^2+Y.^2)/8))

6

Page 7: 1 Computer Lab #1: Plotting in 3D - Northeastern Universitymathserver.neu.edu/~braverman/Teaching/Fall2002/Lab...The simplest way of getting a surface plot is the MatLab command surf(X,Y,Z)

6. An outdoor decorative light consists of a thin neon-filled tube shaped likea conical spiral; think of it as a curve spiraling on a cone. The base of thecone has a radius of half a meter and the height is 2 meters. Starting onthe base, the tube winds around 12 times before reaching the tip of thecone. Find parametric equations for this curve and plot it in Matlab.

7

Page 8: 1 Computer Lab #1: Plotting in 3D - Northeastern Universitymathserver.neu.edu/~braverman/Teaching/Fall2002/Lab...The simplest way of getting a surface plot is the MatLab command surf(X,Y,Z)

2 Computer Lab #2: Quadric Surfaces in Maple

2.1 Maple and Implicit Plots

Maple is very powerful mathematics manipulation and plotting software. It cando symbolic algebra and calculus, compute derivatives and indefinite integrals,and perform complicated numerical calculations. We will not use its full powerhere, but simply draw upon certain of its plotting abilities not available inMatlab.

As we have seen above, if we are given a function f(x, y) of two variables,we can write z = f(x, y) and plot the graph of f , i.e. the set of points(x, y, f(x, y)). This is called an explicit plot since the variable z is given ex-plicitly as a function of the variables x and y. A more general example of anexplicit plot is a parametric plot in which each of the variables x, y, and z isgiven explicitly as a function of one or more other variables called parameters.For example, the helix curve given by x = 3 cos(t), y = 3 sin(t), z = 2t or thesphere given by x = sin(s) cos(t), y = sin(x) sin(t), z = cos(s) are explicit plots.

The general equation for a quadric surface, however, is:

Ax2 + By2 + Cz2 + D xy + E yz + F zx + G x + H y + I z + J = 0.

No variable here is given explicitly in terms of the others. Although it ispossible to solve for z, for example, in terms of the other variables, it involves thequadratic formula and usually requires two separate expressions correspondingto the two roots; in other words, it is pretty messy and awkward to work with.The surface which consists of all points (x, y, z) satisfying this equation is saidto be defined implicitly (i.e. there is an implied solution of one variable in termsof the others, but it is not given explicitly).

Unlike Matlab, Maple provides a plotting procedure which allows you todraw surfaces defined implicitly.

2.2 A Maple Implicit Plot Example

Call up the Maple program using NUNET Programs from the Start menu(go to Computational and Statistical packages, then choose Maple). TheMaple prompt looks like this: > . Here is a sample Maple “session”, followedby an explanation. You should try typing this in for practice. Be very care-ful in entering the commands. Maple is “case-sensitive” which means that itdistinguishes between capital and lower-case letters (for example, “Pi” denotesthe numerical constant 3.14159..., while “pi” is just the greek letter π; and, ofcourse, correct spelling is important.

This plot produces a hyperboloid of 1-sheet, a vertical cylinder, and a plane(with x missing), all on the same set of axes.

8

Page 9: 1 Computer Lab #1: Plotting in 3D - Northeastern Universitymathserver.neu.edu/~braverman/Teaching/Fall2002/Lab...The simplest way of getting a surface plot is the MatLab command surf(X,Y,Z)

> with(plots):> f:= x^2+y^2-z^2=9;> g:= x^2+y^2=4;> h:= z=y;> implicitplot3d({f,g,h},x=-5..5 y=-5..5,z=-7..7,axes=boxed,

grid=[12,12,12], style=patchcontour);

Here are some additional points about Maple in general and the specificsession above.

• Every command in Maple, in order to be executed, must end with a colon(:) or semicolon (;). In general, the semicolon stops Maple from printingany response to the command; thus, the first line above has the com-mand “with(plots):”. This loads Maple’s graphing package. Had therebeen a semicolor, Maple would have printed out the names of the manysubroutines in these packages — obviously something not very useful.

• Each time you start Maple, and want to draw a plot, you have to executethe “with(plots):” command; however, you only have to execute it oncefor each Maple session.

• If you have created the plot above, and want to change one of the functions,use the mouse to position the cursor appropriately on the function, andchange it. In order for this change to register with Maple, you must pressEnter with the cursor on this function line. This is true in general formaking changes in Maple commands.

• To insert a new command line before an already typed Maple line, use theInsert Menu at the top.

• You can change various attributes of the plot (e.g. type of axes, colors,etc.). Click anywhere in the plot; this selects the plot with a box, and addsnew menu icons at the top of the screen. For example, from these icons,choose Style then Patch w/o grid (instead of the patchcontour typedin above); choose Color then Z(Grayscale) (best for printing) or Z(Hue)(good for viewing). Play around with these (e.g. some of the Projectionchoices — this plot uses the default far).

• Once the plot is on the screen, you can rotate it in 3-space by dragging itwith the mouse: experiment with this — use small changes.

• Observe carefully how the equations f, g, h were entered in the samplelines above. Note that they are put in braces: {f,g,h} in the implicitplotcommand.

• You can use the Help menu at the top to learn more about Maple; also,ask the mentor(s) in the Math Dept. Computer Lab (in 553 Lake).

9

Page 10: 1 Computer Lab #1: Plotting in 3D - Northeastern Universitymathserver.neu.edu/~braverman/Teaching/Fall2002/Lab...The simplest way of getting a surface plot is the MatLab command surf(X,Y,Z)

2.3 Quadric Surfaces Exercises to Hand In

Any of the quadric surfaces (Hyperboloids, Paraboloids, Ellipsoids, Cones andCylinders based on parabolas, ellipses or hyperbolas) can be rotated in such away that its equation does not have any xy, yz, or zx terms. Equivalently, wecan let the coefficients of these terms (D, E, F ) in the general equation abovebe equal to 0, and still get any kind of quadric surface. However, sometimesyou encounter a second-degree equation having these terms, and you have toidentify it. The simplest way is to plot it.

Use Maple and implicitplot3d to identify the surfaces given by the equa-tions below. In each case attach a printout of the plot, and give the nameof the surface (for example, “Hyperboloid of 1 sheet”). At least for starters,include the following commands x=-3..3, y=-3..3, z=-3..3, axes=boxed,grid=[12,12,12]. Once you get a plot, you may want to change some or all ofthese. Remember that you can also rotate the plot to get a better viewpoint:click on it once so that a frame forms around it (this will also give variousplotting options on the menu bar at the top of the screen); now dragging theplot in various directions will cause it to rotate. Do this slowly and carefully;it takes a while to get used to how it works. Remember that certain surfaces,from certain viewpoints, may look the same. For example, the bottom half ofan ellipsoid can look like the top part of a hyperboloid of two sheets or like aparaboloid. Try to rotate your plot so that you can be pretty sure which surfaceyou’re dealing with.

a) 2xy − z2 + yz − x = 1

b) 2x2 + x− z − xy + 2yz = 1

c) xz + 3yz = 1

d) 2x2 + 3y2 + 4z2 − 3xy + yz = 8

e) 2x2 + 3y2 + 4z − xy + yz − 4y = 1

f) xy − 3yz + x = 1

Finally, you can probably fit at least two of these plots on a page: this willsave time and paper!

10

Page 11: 1 Computer Lab #1: Plotting in 3D - Northeastern Universitymathserver.neu.edu/~braverman/Teaching/Fall2002/Lab...The simplest way of getting a surface plot is the MatLab command surf(X,Y,Z)

3 Computer Lab #3: Linearization and TangentPlanes

3.1 The Best “Linear” Approximation to a Function

A linear function of the variables x and y is simply a function of “degree 1” inx and y; that is, L(x, y) is linear if we can write L(x, y) = A · x + B · y + C. Aswe shall see, it is usually most convenient to put this in the following form:

L(x, y) = A · (x− a) + B · (y − b) + K

where A, a, B, b, and C are constants. (Strictly speaking this is an affinefunction; a linear function is one of the form: A ·x+B ·y. We will not make thisdistinction here but use the terminology found in many calculus books, eventhough it is not technically correct.)

Now suppose that f(x, y) is any function of x and y, not necessarily linear.We don’t expect that f is even close to a linear function everywhere, but itturns out that if we choose some values of x and y, say (x, y) = (a, b), we canusually approximate f by a certain linear function for (x, y) near (a, b). Wecan’t go into the theory here (check with your text for this), but here’s how itworks.

First we need the constants A and B. They turn out to be the partials:

A = fx (a, b) =∂f

∂x

∣∣∣∣(a,b)

B = fy (a, b) =∂f

∂y

∣∣∣∣(a,b)

Also, we want L and f to agree at (a, b), that is f(a, b) = L(a, b) = A · (a−a) + B · (b− b) + K, so

K = f(a, b)

The linear function L(x, y) defined in this way turns out to be the linearfunction whose values L(x, y) are closest to the values f(x, y) when x is neara and y is near b (we will make the technical assumption that both partialderivatives are continuous near (a, b)).

Definition The linear function L(x, y) = fx(a, b) · (x− a) + fy(a, b) · (y − b) +f(a, b) is called the best linear approximation to f near the point (a,b). Itis also called the linearization of f near (a,b) or the local linearization off.

11

Page 12: 1 Computer Lab #1: Plotting in 3D - Northeastern Universitymathserver.neu.edu/~braverman/Teaching/Fall2002/Lab...The simplest way of getting a surface plot is the MatLab command surf(X,Y,Z)

Now there is a geometric interpretation of this, which we get by looking atgraphs. The graph of the function f is the surface whose equation is z = f(x, y).In general it will be a wavy surface. However, the graph of z = L(x, y) willalways be a plane, which is flat. How are these graphs related?

Theorem When L(x, y) is the best linear approximation to f(x, y) near (a, b),then the graph of L(x, y) is the tangent plane to the surface z = f(x, y)at the point 〈a, b, f (a, b)〉.

(The tangent plane to a surface S at a point P on S is sometimes defined as theset of all tangent vectors at P to all curves that lie on S and that pass throughP . Therefore there really is something to prove in this theorem! One usuallyassume, also, that both partial derivatives fx and fy are continuous at(a, b).)

Using a computer to plot functions and their tangent planes, we can get adirect experience of this geometric relationship.

3.2 Example

Consider this function:

f(x, y) = −x2 +12x4 +

32y2 with (a, b) = (.8, .2).

If we calculate the linearization of f at (a, b), we find that the equation of thetangent plane is given by

z = −.0344− .576x + .6y.

Let us pick a rectangle R containing (.8, .2), say −.2 ≤ x ≤ 1.8 and −.8 ≤y ≤ 1.2 which puts (.8, .2) in the center of a 2x2 square. Let us plot f and itstangent plane. For practice, create the the m-files:

f.mfunction z=f(x,y)z=x.^2+0.5*x.^4+1.5*y.^2;

tp.mfunction z=tp(x,y)z=-.0344-0.576*x+0.6*y;

linear.mx=-.2:.05:1.8;y=-.8:.05:1.2;[X,Y]=meshgrid(x,y);Z1=f(X,Y);surf(X,Y,Z1);hold on;Z2=tp(X,Y);surf(X,Y,Z2);

12

Page 13: 1 Computer Lab #1: Plotting in 3D - Northeastern Universitymathserver.neu.edu/~braverman/Teaching/Fall2002/Lab...The simplest way of getting a surface plot is the MatLab command surf(X,Y,Z)

(Notice that the choice of .05 increments in the x, y data points was somewhatarbitrary; but if the increments are too large, the plot will be inaccurate and ifthe increments are too small, Matlab may take a long time. Also notice that thecommand hold on tells MATLAB to superimpose all plots; it will continue todo so until the command hold off is entered.)

At the Matlab � prompt, type in linear to see the plot.You can zoom in on the point (.8, .2) by selecting a smaller rectangle cen-

tered around it, say .7 ≤ x ≤ .9 and .1 ≤ y ≤ .3. Make these changes inthe linear.m file: x=.7:0.01:.9 y=.1:0.01:.3 (note the change of incrementfrom 0.05 to 0.01), save it, then call up linear again to see the new plot.Notice that the surface has “flattened out” so that it remains much closer tothe tangent plane; in other words the “best linear approximation” to f is muchclose to f on this smaller rectangle.

Finally, for practice, replace the surf(X,Y,Z1) command in linear.m withcontour(X,Y,Z1,20) (same with the one with Z2). This will draw contours (20of them) for the function and its linear approximation.

3.3 Exercises to Hand in

1. Examine the function f(x, y) = 5+xy−x2−y2 and its best linear approx-imation at (a, b) = (0, 1). Create m-files as in the example above. Startwith a 2 x 2 box around (0, 1) and draw the surfaces and contour plots.Then zoom in until the tangent plane and the surface are close. Examinethe contour plots after zooming as well.

• If you were to take a smooth surface, such as the graph of f , andmagnify it many times near a point P such as (0, 1), what would iteventually look like?

• What does the contour plot of a non-horizontal plane look like?(What about horizontal planes?) What does the contour plot ofa smooth surface look like if you magnify (zoom) many times?

(Hand in your plots, answers to the questions, and any other observationsyou care to make.)

2. Now consider the function g(x, y) = (x2 + y2)1/2.

• Plot the function g(x, y) on the rectangle −1 ≤ x ≤ 1, −1 ≤ y ≤ 1(centered at (0, 0)).

• Plot g(x, y) on the rectangle −.1 ≤ x ≤ .1, ,−1 ≤ y ≤ .1 (also cen-tered at (0, 0)). Has the graph of the function become more “plane-like”?

13

Page 14: 1 Computer Lab #1: Plotting in 3D - Northeastern Universitymathserver.neu.edu/~braverman/Teaching/Fall2002/Lab...The simplest way of getting a surface plot is the MatLab command surf(X,Y,Z)

• What’s going on here? What is the best linear approximation? Whatabout the tangent plane? What does the contour plot of g look likenear (0, 0)?

14

Page 15: 1 Computer Lab #1: Plotting in 3D - Northeastern Universitymathserver.neu.edu/~braverman/Teaching/Fall2002/Lab...The simplest way of getting a surface plot is the MatLab command surf(X,Y,Z)

4 Computer Lab #4: Newton’s Method, 2 Vari-ables

Solving the system of equations f(x, y) = 0, g(x, y) = 0 can be quite com-plicated when the the functions f and g depend on x and y in a nonlinear way.On the other hand, as we have seen, (differentiable) nonlinear functions may belocally approximated by linear ones, and these are quite elementary to solve;Newton’s method takes advantage of these facts.

Let’s recall how this works for functions of a single variable. We want tosolve f(x) = 0; i.e., find a root of f . We make an initial guess; let’s call it a. Wehope that f(a) = 0, but that would be pretty lucky. Maybe, however, it’s close.We know that for x near a, f(x) is close to L(x), its best linear approximation.So a root of L should be a good approximation to a root of f . So we solveL(x) = 0 and take that to be our next guess. Now we know that

L(x) = f(a) + f ′(a) · (x− a)

so solving L(x) = 0 gives x = a− f(a)f ′(a)

so this is our new guess. Thus, we get Newton’s formula:

NewGuess = OldGuess− f (OldGuess)f ′(OldGuess)

.

So now we return to the 2-variable case. We want to solve the systemf(x, y) = 0 and g(x, y). Following the 1-variable case, we make a guess: (x, y) =(a, b) = OldGuess, and our new guess will be a solution to Lf (x, y) = 0 andLg(x, y) = 0 where Lf and Lg are the linearizations of f at OldGuess. Thus:

NewGuess = Solution to the system:{

Lf (x, y) = 0Lg(x, y) = 0

= Solution to the system:{

fx(a, b) · (x− a) + fy(a, b) · (y − b) + f(a, b) = 0gx(a, b) · (x− a) + gy(a, b) · (y − b) + g(a, b) = 0

Matlab is especially suited for vector and matrix operations, so we rewritethese equations in matrix form. To simplify things, let ∆x = x − a and ∆y =y − b. Then the equations become:(

fx(a, b) fy(a, b)gx(a, b) gy(a, b)

)·(

∆x∆y

)=(−f(a, b)−g(a, b)

).

The matrix of partial derivatives is called the Jacobian matrix and is some-times denoted J(f, g, a, b). So here is how Newton’s Method plays out in 2variables.

15

Page 16: 1 Computer Lab #1: Plotting in 3D - Northeastern Universitymathserver.neu.edu/~braverman/Teaching/Fall2002/Lab...The simplest way of getting a surface plot is the MatLab command surf(X,Y,Z)

• Suppose(

ab

)is the OldGuess; compute the Jacobian matrix J(f, g, a, b).

• Solve the matrix equation: J(f, g, a, b) ·(

∆x∆y

)=(−f(a, b)−g(a, b)

)for ∆x

and ∆y: (∆x∆y

)= (J(f, g, a, b))−1 ·

(−f(a, b)−g(a, b)

)

NewGuess =(

xy

)=(

a + ∆xb + ∆y

)= OldGuess +

(∆x∆y

)= OldGuess− (J(f, g, a, b))−1 ·

(f(a, b)g(a, b)

)

Example Suppose we have the system x2 = 2y, x2 + y = 3 that we want tosolve simultaneously. Write this as f(x, y) = x2 − 2y = 0 and g(x, y) =x2 + y − 3 = 0.

Let us take (a, b) = (1, 1) as our initial guess.Below is the m-file Newton.m which performs Newton’s Method on an arbi-

trary function F with Jacobian matrix JF. It takes three parameters: F is thename of an m-file with the pair of functions f and g, JF is the name of an m-filefor the Jacobian matrix for these functions, Guess is a vector for the initialguess, and interation is the number of guesses to calculate.

Newton.mfunction[P,deltaG,error]=Newton(F,JF,Guess,iteration);Y=feval(F,Guess); %Findf(Guess)for k=1:iteration %Perform loop interation timesJ=feval(JF,Guess); %Jacobian(Guess)K=inv(J); %Invert matrix JQ=Guess-K*Y; %Q is NewGuessY=feval(F,Q); %Find f(NewGuess)deltaG=norm(Q-Guess); %See how close guesses areGuess=Q; %Reset:Guess=NewGuessend %End loopP=Guess; %Newton’s estimate of rootdeltaG; %Are guesses converging?error=Y; %Is f(Guess) close to 0?

Here are m-files for the functions and the Jacobian, and an example of usingthe function Newton:

16

Page 17: 1 Computer Lab #1: Plotting in 3D - Northeastern Universitymathserver.neu.edu/~braverman/Teaching/Fall2002/Lab...The simplest way of getting a surface plot is the MatLab command surf(X,Y,Z)

Newtfunc.mfunction Z=Newtfunc(X)x=X(1); y=X(2);Z=[x^2-2*y;x^2+y-3];

NewtJ.mfunction W=NewtJ(X)x=X(1); y=X(2);W=[2*x, -2; 2*x, 1];

Thus, to apply Newton’s method in this example, with 4 iterations, youwould type:

� Newton(’Newtfunc’,’NewtJ’,[1;1],4)

Here are some further points.

• You’ll find that the above command will display only 4-place accuracy. Asimple solution is to precede the call to Newton with the command: �format long. All further computations will display 16 places.

• Note that Newton should output three numbers: the last guess, the dif-ference between the last two guesses, and the values of f and g appliedto the last guess, while the simple command above produces only the lastguess (called “ans”). To get all three outputs, type: � [A,B,C] =Newton(’Newtfunc’,’NewtJ’,[1;1],4).

• Finally, note that when names of functions are passed to functions, theyhave to be put in single quotes; e.g. ’Newtfunc’, ’NewtJ’.

4.1 Exercises to Hand In

1. Use Newton’s Method to solve the simultaneous equations x2 − y2 =−1, y2 − x = 3 with initial guess x = y = −1. What is the actual (i.e.exact) solution? How many interations of Newton’s method does it taketo get the correct answer to 16 places?

2. Find a local minimum for the function f (x, y) = x3 + y3 − 3x − 3y + 5.(First, look at some surface and contour plots to find an estimate forwhere the minimum occurs — don’t forget that x3 is entered as x.^3 insetting up the plot — next, use Newton’s method to find the critical pointaccurately.)

3. (Challenging) Find one maximum and one minimum (to 16 places) for thefunction

z = .02 sin(x) sin(y)−.03 sin(2x) sin(y)+.04 sin(x) sin(2y)+.08 sin(2x) sin(2y)

(This represents a Fourier approximation to a certain vibrating mem-brane.) You should draw some plots to find good starting approximations

17

Page 18: 1 Computer Lab #1: Plotting in 3D - Northeastern Universitymathserver.neu.edu/~braverman/Teaching/Fall2002/Lab...The simplest way of getting a surface plot is the MatLab command surf(X,Y,Z)

for using Newton’s Method to find the critical points — contour plots areprobably easiest to use for this. Here is an m-file for use in plotting thisfunction — note the use of a broken string (with a +) to make the functionmore readable:

membrane.mfunction z = membrane(x,y);f=[’0.02*sin(x)*sin(y)-0.03*sin(2*x)*sin(y)’,...’+0.04*sin(x)*sin(2*y)+0.08*sin(2*x)*sin(2*y)’];z=eval(vectorize(f));

18

Page 19: 1 Computer Lab #1: Plotting in 3D - Northeastern Universitymathserver.neu.edu/~braverman/Teaching/Fall2002/Lab...The simplest way of getting a surface plot is the MatLab command surf(X,Y,Z)

5 Computer Lab #5: Gradient Fields

5.1 Introduction

The aim of this lab is to visualize some of the properties of the gradient, and touse them to interpret the behavior of a function of two variables.

5.2 Review of the Gradient

1. Suppose f (x, y) is a scalar-valued function of two variables, so f : R2 −→R. The gradient of f is the vector of functions: grad(f) = ∇f =(fx, fy) =

⟨∂f∂x , ∂f

∂y

⟩=(

∂f∂x

)i +(

∂f∂y

)j.

2. The gradient of f at the point P = (a, b) is the vector:

∇f (a, b) = 〈fx(a, b), fy(a, b)〉 =

(∂f

∂x

∣∣∣∣(a,b)

)i +

(∂f

∂y

∣∣∣∣(a,b)

)j

3. ∇f (a, b) points in the direction, from (a, b), in which the function f in-creases most rapidly.

4. ∇f (a, b) is perpendicular to the contour or level curve for f through (a, b).

5.3 Vector Fields and Gradient Fields

1. A vector field V is simply a way of assigning, to points (x, y) in the plane,vectors V(x, y). For example, the vector field V(x, y) = (4xy−1)i+(2x2+2y)j assigns the vector V(2, 3) = 23i + 14j to the point (2, 3).

2. Given a function f(x, y), its gradient ∇f =(

∂f∂x

)i +

(∂f∂y

)j is a vector

field. For example, suppose f(x, y) = 2x2y + y2 − x + 2. Then ∇f =(4xy− 1)i+(2x2 + 2y)j (see immediately above), so ∇f assigns the vector23i + 14j to the point (2, 3).

3. We can picture vector fields by selecting a grid of points in the planeand drawing the vector V(P ) at the point P . Matlab does this withthe command quiver (a “quiver”, you may recall, is a carrying case forarrows). Here is an m-file which draws the gradient field for the functionabove, as well as a contour plot for the same function

19

Page 20: 1 Computer Lab #1: Plotting in 3D - Northeastern Universitymathserver.neu.edu/~braverman/Teaching/Fall2002/Lab...The simplest way of getting a surface plot is the MatLab command surf(X,Y,Z)

grad1.mv = -10:1.0:10; vv=-10:0.2:10;[x,y]=meshgrid(v); [xx,yy]=meshgrid(vv);z = 2*x.^2.*y + y.^2-x+2; zz = 2*xx.^2.*yy + yy.^2-xx+2;[px,py] = gradient(z);hold on, quiver(x,y,px,py), contour(xx,yy,zz), hold off

Here are some comments about this m-file.

• Note first that there are two grids, one for the gradient field andthe other for the contours. This is because you want a fine grid(every 0.2) for drawing smooth contours, but such a fine grid woulddraw so many arrows for the vector field that the screen would betoo cluttered. Therefore we use the gap 1.0 instead of 0.2 for thegradient.

• The arrays have to match up: [px,py] goes with x and y, zz goeswith xx and yy; otherwise you’ll get an error message.

• You can get a more colorful plot by replacing the contour commandwith contourf. However, if you do this, you’ll want to draw thearrows in black, so use quiver(x,y,px,py,’k’).

• Matlab scales the arrows so that they fit nicely in the screen anddon’t touch each other. They can also be scaled manually — look itup by typing: help quiver at the Matlab prompt.

4. Combined gradient and contour plots can be helpful in classifying criticalpoint (places where the gradient is zero). These are of three types:

• Maxima: nearby gradient vectors all point toward the critical point(function increasing)

• Minima: nearby gradient vectors all point away from critical point• Saddles: some nearby gradients point toward, others away.

5.4 Exercises to Hand In

1. Draw a gradient/contour plot for the function z = xe−x2−y2in the rect-

angle −2 ≤ x ≤ 2, −2 ≤ y ≤ 2 (usually written as simply −2 ≤ x, y ≤ 2).Use this to locate, approximately, the critical points. Classify them: max,min or saddle; explain how you know.

2. Do the same as exercise 1, except use the rectangle −10 ≤ x, y ≤ 10 andthe function:

z = 4500− 105x2 − 105y2 + 3y2x + 3x2y + 0.8x4 + 0.8y4.

20

Page 21: 1 Computer Lab #1: Plotting in 3D - Northeastern Universitymathserver.neu.edu/~braverman/Teaching/Fall2002/Lab...The simplest way of getting a surface plot is the MatLab command surf(X,Y,Z)

3. Do the same as exercise 1, except use the rectangle 0 ≤ x, y ≤ π andthe function: z = .02 sin(x) sin(y)− .03 sin(2x) sin(y)+ .04 sin(x) sin(2y)+.08 sin(2x) sin(2y) .

(see exercise 3 of the previous set for a sample m-file).

4. Do the same as exercise 1, except use the rectangle −π ≤ x, y ≤ π andthe function:

z = cos(x + y) cos(3x− y) + cos(x− y) sin(x + 3y) + 5e−(x2+y2)/8

(see exercise 3 of the previous set for a sample m-file).

21

Page 22: 1 Computer Lab #1: Plotting in 3D - Northeastern Universitymathserver.neu.edu/~braverman/Teaching/Fall2002/Lab...The simplest way of getting a surface plot is the MatLab command surf(X,Y,Z)

6 Ray Tracing Project

When a ray of light bounces off a shiny surface at a point P , it is reflected insuch a way that the angle that it makes with the normal at P is equal to theangle that the reflected ray makes with the normal. Both rays and the normallie in the same plane. In the technique of ray tracing, a computer calculates, formany points on a surface, how the rays of light from each source of illuminationare reflected. Those reflections that hit a specified “viewplane” at a point Xdetermine a color and intensity number for X, depending on the nature of theparticular source(s) of the reflections. These numbers are then used to light uppixels or dots on a computer screen. In this way, a highly realistic rendering ofthe original surface is obtained.

This project deals with just one aspect of ray-tracing: determining where onthe viewplane a particular ray will end up, after it is reflected from a point onthe surface. Suppose the surface S is the graph of z = 8x+6y−2x2−y2−1. (Inactual computer-simulated scenes, a complex surface is often approximated bymany small patches, each one given by a relatively simple mathematical formulasuch as this one.) Suppose that the source of light is at P = (2, 3, 25), and theviewplane is the plane x = 100.

1. Let Q = (3, 4, 13). Verify that Q actually lies on the surface S.

2. Light travels from P to Q. Find the vector ∆ =−−→PQ.

3. Find the normal N to S at Q.

4. Write ∆ = Proj ~N∆ + Perp ~N∆ and calculate the two vectors on the rightside.

5. Draw a diagram to show that the reflected vector ∆r is actually Perp ~N∆−Proj ~N∆, and calculate ∆r. (Check that ∆ and ∆r make equal angles withN!)

6. Using the vector ∆r as direction, parametrize the line along which thereflected ray travels, and find out where the line intersects the viewplane.

7. Use Matlab or Maple to draw the surface, a bit of the tangent plane, andthe ray and its reflection.

22

Page 23: 1 Computer Lab #1: Plotting in 3D - Northeastern Universitymathserver.neu.edu/~braverman/Teaching/Fall2002/Lab...The simplest way of getting a surface plot is the MatLab command surf(X,Y,Z)

7 Facts About Vectors

In the following formulas let V = (vx, vy, vz) and W = (wx, wy, wz). As usual,i = (1, 0, 0), j = (0, 1, 0) and k = (0, 0, 1).

1. Displacement, velocity, acceleration, momentum, force and torque are allexamples of vector quantities. (Distance and speed are scalars, however.)

• V ·W = vxwx + vywy + vzwz = |V||W| cos(θ)

• |V| =√

v2x + v2

y + v2z =

√V ·V

• If V = Displacement and W = Force, then Work = V ·W.

2. We can write V = projWV + perpWV where projWV is parallel to Wand perpWV is perpendicular to W; these vectors are given by:

• projWV =(

V·WW·W

)W

• perpWV = V − projWV.

3. The cross product V ×W has the properties:

• V ×W is perpendicular to both V and W

• |V×W| = |V||W| sin(θ) = Area of the parallelogram determined byV and W.

• V ×W = det

i j kvx vy vz

wx wy wz

• |V×W|/|W| is the perpendicular distance from the head of V to the

line determined by W (since it’s the altitude of the parallelogram).

• Torque = (Leverarmvector)× (Forcevector).

• V is perpendicular to W ⇐⇒ V ·W = 0.

• V is parallel to W ⇐⇒ V ×W = 0 ⇐⇒ There is a scalar λ 6= 0with V = λW.

4. If U = (ux, uy, uz) then

• U·(V×W) = det

ux uy uz

vx vy vz

wx wy wz

= volume of the parallelopiped

determined by U, V and W.

• U, V and W are coplanar ⇐⇒ U · (V ×W) = 0.

23