chapter 5 advanced plotting and model building

119
Chapter 5 Advanced Plotting and Model Building

Upload: aolani

Post on 15-Jan-2016

62 views

Category:

Documents


0 download

DESCRIPTION

Chapter 5 Advanced Plotting and Model Building. Matlab, Maple & Mathematica – plots are part of the package !!! Type help graph2d or graph3d to get help. Anatomy of a typical xy (2D) plot. Figure 5.1–1. 5-2. Scale on axis – range and spacing of the numbers. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 5 Advanced Plotting and Model Building

Chapter 5Advanced Plottingand Model Building

Page 2: Chapter 5 Advanced Plotting and Model Building

Matlab, Maple & Mathematica – plots are part of the package!!!

Type help graph2d or graph3d to get help

Page 3: Chapter 5 Advanced Plotting and Model Building

Anatomy of a typical xy (2D) plot. Figure 5.1–1

5-25-2

More? See pages 260-261.

Scale on axis – range and spacing of the numbers.Here both axis are linear (later will see logarithmic…).

Page 4: Chapter 5 Advanced Plotting and Model Building

The following MATLAB session plots y 04 18x for 0 x 52, where y represents the height of a rocket after launch, in miles, and x is the horizontal (downrange) distance in miles.

>>x = [0:0.1:52]; % create vector of finely spaced pts

>>y = 0.4*sqrt(1.8*x); % to produce a smooth curve

>>plot(x,y)>>xlabel(’Distance (miles)’)>>ylabel(’Height (miles)’)>>title([‘Rocket Height as a Function of Downrange Distance’,num2str(dist)])

5-35-3

The resulting plot is shown on the next slide.

Page 5: Chapter 5 Advanced Plotting and Model Building

The autoscaling feature in MATLAB selects tick-mark spacing. Figure 5.1–2

5-45-4

Page 6: Chapter 5 Advanced Plotting and Model Building

The plot will appear in the Figure window. You can obtain a hard copy of the plot in several ways:

1. Use the menu system. Select Print on the File menu in the Figure window. Answer OK when you are prompted to continue the printing process.

2. Type print at the command line. This command sends the current plot directly to the printer.

3. Save the plot to a file to be printed later or imported into another application such as a word processor. You need to know something about graphics file formats to use this file properly. See the subsection Exporting Figures.

5-55-5

Page 7: Chapter 5 Advanced Plotting and Model Building

Requirements for a Correct Plot

The following list describes the essential features of any plot:

1. Each axis must be labeled with the name of the quantity being plotted and its units! If two or more quantities having different units are plotted (such as when plotting both speed and distance versus time), indicate the units in the axis label if there is room, or in the legend or labels for each curve.

2. Each axis should have regularly spaced tick marks at convenient intervals — not too sparse, but not too dense —with a spacing that is easy to interpret and interpolate.For example, use 0.1, 0.2, and so on, rather than 0.13, 0.26, and so on.

5-75-7 (continued …)

Page 8: Chapter 5 Advanced Plotting and Model Building

3. If you are plotting more than one curve or data set, label each on its plot or use a legend to distinguish them.

4. If you are preparing multiple plots of a similar type or if the axes’ labels cannot convey enough information, use a title.

5. If you are plotting measured data, plot each data point with a symbol such as a circle, square, or cross (use the same symbol for every point in the same data set). If there are many data points, plot them using the dot symbol.

5-85-8

Requirements for a Correct Plot (continued)

(continued …)

Page 9: Chapter 5 Advanced Plotting and Model Building

6. Sometimes data symbols are connected by lines to help the viewer visualize the data, especially if there are few data points. However, connecting the data points, especially with a solid line, might be interpreted to imply knowledge of what occurs between the data points. Thus you should be careful to prevent such misinterpretation.

7. If you are plotting points generated by evaluating a function (as opposed to measured data), do not use a symbol to plot the points. Instead, be sure to generate many points, and connect the points with solid lines.

5-95-9

Requirements for a Correct Plot (continued)

Page 10: Chapter 5 Advanced Plotting and Model Building

The grid and axis Commands

The grid command displays gridlines at the tick marks corresponding to the tick labels. Type grid on to add gridlines; type grid off to stop plotting gridlines.

You can use the axis command to override the MATLAB selections for the axis limits. The basic syntax is axis([xmin xmax ymin ymax]). This command sets the scaling for the x- and y-axes to the minimum and maximum values indicated. Note that, unlike an array, this command does not use commas to separate the values.

Axis commands: axis square, equal, auto

5-105-10 More? See pages 264-265.

Page 11: Chapter 5 Advanced Plotting and Model Building

The effects of the axis and grid commands. Figure 5.1–3

5-115-11

Page 12: Chapter 5 Advanced Plotting and Model Building

Plot of Complex numbersThe plot(y) function plots the values in y versus the indices. However, if y is complex plot(y) plots the imaginary parts vs real parts, i.e. plot( real(y) , imag(y) )In all other variants of the plot function, it ignores the imaginary parts.

5-125-12

Example:z = 0.3 + 0.7*in = [0:0.001:100];plot(z.^n)xlabel('Real')ylabel('Imaginary')axis equal

-0.4 -0.2 0 0.2 0.4 0.6 0.8 1-0.4

-0.2

0

0.2

0.4

0.6

Real

Imag

inar

y

Page 13: Chapter 5 Advanced Plotting and Model Building

The fplot – smart command for plotting functions - plots function specified as string. It automatically analyzes the function to pick proper spacing, so that plot will show all

the features of the function – adaptive plotting.Syntax is fplot(‘string’,[xmin xmax ymin ymax])

[x,y] = fplot(‘cos(tan(x)) – tan(sin(x))’,[1,2]) - automatically picked denser points in the more complicated region

5-135-13

Page 14: Chapter 5 Advanced Plotting and Model Building

Contrast the previous plot with:x = [1:0.01:2]; y = cos(tan(x)) – tan(sin(x)); plot(x,y) – much less detailed

Another form is [x,y]=fplot(‘string’,limits) – returns abscissa and ordinate values in the column vectors x and y, but no plot is produced.

The returned values can be used for plotting multiple curves etc…

5-145-14

Page 15: Chapter 5 Advanced Plotting and Model Building

Plotting Polynomials with the polyval Function.

To plot the polynomial 2x5–4x3 + 2x2 + 10 over the range –4 x 4 with a spacing of 0.01, you type

>>x = [-4:0.01:4]; % setting the spacing>>p = [2,0,-4,2,0,10]; % setting the coefficients>>plot(x,polyval(p,x))>>xlabel(’x’)>>ylabel(’p’)

5-155-15

More? See page 268.

-2 -1.5 -1 -0.5 0 0.5 1 1.5 2-20

-10

0

10

20

30

40

50

x

p

Page 16: Chapter 5 Advanced Plotting and Model Building

An example of a Figure window. Figure 5.1–7

5-165-16

Page 17: Chapter 5 Advanced Plotting and Model Building

Saving Figures ( less options in Octave )

To save a figure that can be opened in subsequent MATLAB sessions, save it in a figure file with the .fig file name extension.

To do this, select Save from the Figure window File menu or click the Save button (the disk icon) on the toolbar.

If this is the first time you are saving the file, the Save As dialog box appears. Make sure that the type is MATLAB Figure (*.fig). Specify the name you want assigned to the figure file. Click OK.

5-175-17

Page 18: Chapter 5 Advanced Plotting and Model Building

Exporting Figures (only Matlab)

To save the figure in a format that can be used by another application, such as the standard graphics file formats TIFF or EPS, perform these steps:

1. Select Export Setup from the File menu. This dialog lets you specify options for the output file, such as the figure size, fonts, line size and style, and output format.

2. Select Export from the Export Setup dialog. A standard Save As dialog appears.

3. Select the format from the list of formats in the Save As type menu. This selects the format of the exported file and adds the standard file name extension given to files of that type.

4. Enter the name you want to give the file, less the extension. Then click Save.

5-185-18 More? See pages 270-271.

Page 19: Chapter 5 Advanced Plotting and Model Building

On Windows systems, you can also copy a figure to the clipboard and then paste it into another application:

1. Select Copy Options from the Edit menu. The Copying Options page of the Preferences dialog box appears.

2. Complete the fields on the Copying Options page and click OK.

3. Select Copy Figure from the Edit menu.

5-195-19

Page 20: Chapter 5 Advanced Plotting and Model Building

SubplotsMatlab can create array of rectangular panes – subplots.

The syntax is subplot(m,n,p).

This command divides the Figure window into an array of rectangular panes with m rows and n columns.

The variable p tells MATLAB to place the output of the plot command following the subplot command into the pth pane.

For example, subplot(3,2,5) creates an array of six panes, three panes deep and two panes across, and directs the next plot to appear in the fifth pane (in the bottom-left corner).

5-205-20

Page 21: Chapter 5 Advanced Plotting and Model Building

The following script file created Figure 5.2–1, which shows the plots of the functions y e12x sin(10x 5) for 0 x 5 and y x3 100for 6 x 6.

x = [0:0.01:5];y = exp(-1.2*x).*sin(10*x+5);subplot(1,2,1)plot(x,y),axis([0 5 -1 1])

x = [-6:0.01:6];y = abs(x.^3-100);subplot(1,2,2)plot(x,y),axis([-6 6 0 350])

5-215-21

The figure is shown on the next slide.

Page 22: Chapter 5 Advanced Plotting and Model Building

Application of the subplot command. Figure 5.2–1

5-225-22

More on subplots? See page 271.

Page 23: Chapter 5 Advanced Plotting and Model Building

Overlay PlotsOverlay Plots

Simple Overlay:Simple Overlay:x = -1:0.01:2;

y1 = x.^2 - 1;

y2 = x.^3 - 2;

plot(x,y1,x,y2)

legend('y1','y2')

Matrix Overlays:Matrix Overlays:plot(A) plots the plot(A) plots the columns of Acolumns of A vs indices and generates n curves where A is matrix with m rows vs indices and generates n curves where A is matrix with m rows

and m columns.and m columns.

plot(x,A) plots the matrix A vs the vector x, where x is either a row vector or column vector and plot(x,A) plots the matrix A vs the vector x, where x is either a row vector or column vector and A is a matrix with m rows and n columns. A is a matrix with m rows and n columns.

If the length of x is If the length of x is mm, then each , then each columncolumn of A is plotted vs vector x of A is plotted vs vector x

If the length of x is If the length of x is nn , then each , then each rowrow of A is plotted vs vector x of A is plotted vs vector x

plot(A,x) plots the vector x vs the matrix Aplot(A,x) plots the vector x vs the matrix A

If the length of x is If the length of x is mm, then x is plotted vs each , then x is plotted vs each columncolumn of A of A

If the length of x is If the length of x is nn , then x is plotted vs each , then x is plotted vs each rowrow of A of A

plot(A,B) plots plot(A,B) plots columnscolumns of the matrix B vs of the matrix B vs columnscolumns of the matrix A of the matrix A

-1 -0.5 0 0.5 1 1.5 2-3

-2

-1

0

1

2

3

4

5

6

y1

y2

Page 24: Chapter 5 Advanced Plotting and Model Building

Data Markers and Line Types

To plot y versus x with a solid line and u versus v with a dashed line, type plot(x,y,u,v,’--’), where the symbols ’--’ represent a dashed line.

Table 5.2–1 gives the symbols for other line types.

To plot y versus x with asterisks (*) connected with a dotted line:plot(x,y,’*:’).

5-235-23

Page 25: Chapter 5 Advanced Plotting and Model Building

To plot y versus x with green asterisks () connected with a red dashed line, you must plot the data twice by typing plot(x,y,’g*’,x,y,’r--’).

5-245-24

Page 26: Chapter 5 Advanced Plotting and Model Building

Specifiers for data markers, line types, and colors.Table 5.2–1

Data markers†

Dot (.)Asterisk (*)Cross ()

Circle ()Plus sign ()Square ( )Diamond ( )Five-pointed star (w)

.*

sdp

Line types

Solid lineDashed lineDash-dotted lineDotted line

––– –– .….

Colors

BlackBlueCyanGreenMagentaRedWhiteYellow

kbcgmrwy

†Other data markers are available. Search for “markers” in MATLAB help.

5-265-26

Useful when you plot many different data types on the same plot

Page 27: Chapter 5 Advanced Plotting and Model Building

We can plot two different sets of data on the We can plot two different sets of data on the same plot with:same plot with:

-1 -0.5 0 0.5 1 1.5 2-3

-2

-1

0

1

2

3

y1

y2x1 = -1:0.1:2;x2 = 0:0.1:1.5;y1 = -x1.^2 + 1;y2 = x2.^3 - 1;plot(x1,y1,x2,y2,'*:')legend('y1','y2')

Page 28: Chapter 5 Advanced Plotting and Model Building

Use of data markers. Figure 5.2–2

5-275-27

More? See pages 273-274.

Page 29: Chapter 5 Advanced Plotting and Model Building

Labeling Curves and Data

The legend command automatically obtains from the plot the line type used for each data set and displays a sample of this line type in the legend box next to the string you selected.

The following script file produced the plot in Figure 5.2–4.

x = [0:0.01:2];y = sinh(x);z = tanh(x);plot(x,y,x,z,’--’),xlabel(’x’), ...ylabel(’Hyperbolic Sine and Tangent’), ...legend(’sinh(x)’,’tanh(x)’)

5-285-28

Page 30: Chapter 5 Advanced Plotting and Model Building

Application of the legend command. Figure 5.2–4

5-295-29

Page 31: Chapter 5 Advanced Plotting and Model Building

The gtext and text commands are also useful. Figure 5.2–5

5-305-30

Another way to distinguish graphs is to place text next to each one.

GTEXT('string') displays the graph window, puts up a cross-hair, and waits for a mouse button or keyboard key to be pressed. The cross-hair can be positioned with the mouse (or with the arrow keys on some computers). Pressing a mouse button or any key writes the text string onto the graph at the selected location. Examplegtext({‘first line','second line'}) gtext({'First line','Second line'},'FontName','Times','Fontsize',12)

There is also text(x,y,’string’), but here you have to specify x and y coordinates in advance.

Page 32: Chapter 5 Advanced Plotting and Model Building

Graphical solution of equations: To get a first guess on solution of two equations in two unknowns, you must always plot

the equations.Solution is at the intersection of two lines.If they do not intersect – no solutions, if multiple intersections – multiple solutions.

Example:Circuit representation of a power supply and a load. Example 5.2-1. Figure 5.2–6

5-315-31

Page 33: Chapter 5 Advanced Plotting and Model Building

Plot of the load line and the device curve for Example 5.2–1.Figure 5.2–7

5-325-32

Page 34: Chapter 5 Advanced Plotting and Model Building

Application of the hold command. Figure 5.2–8hold – holds the figure still allowing to add more plots later.

5-335-33

HOLD ON holds the current plot and all axis properties so that subsequent graphing commands add to the existing graph. HOLD OFF returns to the default mode whereby

PLOT commands erase the previous plots and reset all axis properties before drawing new plots.

It is not really needed in many cases because we can plot multiple graphs with plot(x,y,x,z,’--’), but useful here because plots are of different types and also useful for advanced toolboxes.

x = -1:0.01:1;y1 = 3 + exp(-x).*sin(6*x);y2 = 4 + exp(-x).*cos(6*x);z = 0.1 + 0.9*i ;n = 0:0.01:10;plot(z.^n) hold onplot(y1,y2)hold off

Page 35: Chapter 5 Advanced Plotting and Model Building

Hints for Improving Plots

The following actions, while not required, can nevertheless improve the appearance of your plots:

1. Start scales from zero whenever possible. This technique prevents a false impression of the

magnitudes of any variations shown on the plot.

2. Use sensible tick-mark spacing. If the quantities are months, choose a spacing of 12 because 110 of a year is not a convenient division. Space tick marks as close as is useful, but no closer. If the data is given monthly over a range of 24 months, 48 tick marks might be too dense, and also unnecessary.

5-345-34(continued …)

Page 36: Chapter 5 Advanced Plotting and Model Building

3. Minimize the number of zeros in the data being plotted. For example, use a scale in millions of dollars when appropriate, instead of a scale in dollars with six zeros after every number.

4. Determine the minimum and maximum data values for each axis before plotting the data. Then set the axis limits to cover the entire data range plus an additional amount to allow convenient tick-mark spacing to be selected.

For example, if the data on the x-axis ranges from 1.2 to 9.6, a good choice for axis limits is 0 to 10. This choice allows you to use a tick spacing of 1 or 2.

5-355-35

Hints for Improving Plots (continued)

(continued …)

Page 37: Chapter 5 Advanced Plotting and Model Building

5. Use a different line type for each curve when several are plotted on a single plot and they cross each other; for example, use a solid line, a dashed line, and combinations of lines and symbols. Beware of using colors to distinguish plots if you are going to make black-and-white printouts and photocopies.

6. Do not put many curves on one plot, particularly if they will be close to each other or cross one another at several points.

7. Use the same scale limits and tick spacing on each plot if you need to compare information on more than one plot.

Note:Matlab can create text, titles, and labels using Math symbols in TEXtitle(‘A e^{-t/\tau)sin(\omega t)’) backslash \ must precede each TEX

character sequence.

5-365-36

Hints for Improving Plots (continued)

Page 38: Chapter 5 Advanced Plotting and Model Building

Why use log scales? 1) To represent graphs that cover wide ranges.2) To identify certain trends in data, because some types of functional relationships

appear as straight lines when plotted using log scale.In the example below we have wide variation in both abscissa and ordinate, so loglog

plot is much more useful.

5-375-37

Page 39: Chapter 5 Advanced Plotting and Model Building

Logarithmic Plots

It is important to remember the following points when using log scales:

1) You cannot plot negative numbers on a log scale, because the logarithm of a negative number is not a real number.

2) You cannot plot the number 0 on a log scale, because log10 0 ln 0 . You must choose an appropriately small number as the lower limit on the plot.

(may just rescale your data to start with 1)

5-395-39(continued…)

Page 40: Chapter 5 Advanced Plotting and Model Building

3) The tick-mark labels on a log scale are the actual values being plotted;they are not the logarithms of the numbers. For example, the range of x values in the plot in Figure 5.3–2 is from 10-1 = 0.1 to 102 = 100.

4) Equal distances on a log scale correspond to multiplication by the same constant (as opposed to addition of the same constant on a rectilinear scale). log(a*b) = log(a) + log(b)

For example, all numbers that differ by a factor of 10 are separated by the same distance on a log scale.

That is, the distance between 0.3 and 3 is the same as the distance between 30 and 300. This separation is referred to as a decade or cycle.

Gridlines and tick marks within a decade are unevenly spaced. If 8 gridlines or tick marks occur within the decade, they correspond to values equal to 2, 3, 4, .

. . , 8, 9 times the value represented by the first gridline or tick mark of the decade.

5-405-40

Logarithmic Plots (continued)

(continued…)

Page 41: Chapter 5 Advanced Plotting and Model Building

The plot shown in Figure 5.3–2 covers three decades in x (from 0.1 to 100) and four decades in y and is thus called a four-by-three-cycle plot.

5-415-41

Logarithmic Plots (continued)

Page 42: Chapter 5 Advanced Plotting and Model Building

MATLAB has 3 commands for generating plots having log scales. The appropriate command depends on which axis must have a log scale.

1. Use the loglog(x,y) command to have both scales logarithmic.

2. Use the semilogx(x,y) command to have the x scale logarithmic and the y scale rectilinear.

3. Use the semilogy(x,y) command to have the y scale logarithmic and the x scale rectilinear.

5-425-42

Page 43: Chapter 5 Advanced Plotting and Model Building

Two data sets plotted on four types of plots. Figure 5.3–3

x1 = 1:0.2:3;y1 = 3*x1.^2;y2 = 3*exp(x1);y3 = 3*log(x1)subplot( 2, 2, 1)plot(x1,y1,'d-.',x1,y2,'*-',x1,y3,'o:')legend('power','exp','log')grid onsubplot( 2, 2, 2)semilogx(x1,y1,'d-.',x1,y2,'*-',x1,y3,'o:')grid on%legend('power','exp','log')subplot( 2, 2, 3)semilogy(x1,y1,'d-.',x1,y2,'*-',x1,y3,'o:')grid on%legend('power','exp','log')subplot( 2, 2, 4)loglog(x1,y1,'d-.',x1,y2,'*-',x1,y3,'o:')grid on%legend('power','exp','log')

1 1.5 2 2.5 30

10

20

30

40

50

60

70

100

0

10

20

30

40

50

60

70

1 1.5 2 2.5 310

-1

100

101

102

100

10-1

100

101

102

power

explog

y1 – power dependence is linear only on log log ploty2 - exp is linear only on semilogyy3 - log is linear only on semilogx

Page 44: Chapter 5 Advanced Plotting and Model Building

Application of logarithmic plots: An RC circuit. Figure 5.3–4

Frequency-response plot of a low-pass RC circuit. Figure 5.3–5

RC = 0.1;s = [ 1:100 ] * i;M = abs(1./(RC*s+1));loglog(imag(s),M)

At omega about 10 rad/sec the amplitudeof any signal with freq greater than thisone, will decrease by more than 30%=> low pass filter

Page 45: Chapter 5 Advanced Plotting and Model Building

An example of controlling the tick-mark labels with the set command. Figure 5.3–6

See pages 287-289.

Changes tick marksfrom numbers to text labels of months

set(gca,’XTicklabel’,[‘Jan’; ‘Feb’ ])set(gca,’XTick’,[1:6])

Page 46: Chapter 5 Advanced Plotting and Model Building

Command

bar(x,y)

plotyy(x1,y1,x2,y2)

polar(theta,r,’type’)

stairs(x,y)

stem(x,y)

Description

Creates a bar chart of y versus x.

Produces a plot with two y-axes, y1 on the left and y2 on the right.

Produces a polar plot from the polar coordinates theta and r, using the line type, data marker, and colors specified in the string type.

Produces a stairs plot of y versus x.

Produces a stem plot of y versus x.

Specialized plot commands. Table 5.3–1

5-435-43

Page 47: Chapter 5 Advanced Plotting and Model Building

A polar plot showing an orbit around Sun (at the origin) having an eccentricity of 0.5.

5-485-48

See pages 290-291.

Polar plot r = r(theta) – veryhard to do by hand!!!

theta = linspace(0, 2*pi,100);r = 2 ./ (1 – 0.5*cos(theta)/2);polar(theta,r)

Class: T5.3-1 and 3, p291

Page 48: Chapter 5 Advanced Plotting and Model Building

Interactive Plotting in MATLAB

This interface can be advantageous in situations where:

You need to create a large number of different types of plots,

You must construct plots involving many data sets,

You want to add annotations such as rectangles and ellipses, or

You want to change plot characteristics such as tick spacing, fonts, bolding, italics, and colors.

5-495-49More? See pages 292-298.

Page 49: Chapter 5 Advanced Plotting and Model Building

The interactive plotting environment in MATLAB is a set of tools for:

Creating different types of graphs,

Selecting variables to plot directly from the Workspace Browser,

Creating and editing subplots,

Adding annotations such as lines, arrows, text, rectangles, and ellipses, and

Editing properties of graphics objects, such as their color, line weight, and font.

5-505-50

Page 50: Chapter 5 Advanced Plotting and Model Building

The Figure window with the Figure toolbar displayed.Figure 5.4–1

5-515-51

Page 51: Chapter 5 Advanced Plotting and Model Building

The Figure window with the Figure and Plot Edit toolbars displayed. Figure 5.4–2

5-525-52

Page 52: Chapter 5 Advanced Plotting and Model Building

The Plot Tools interface includes the following three panels associated with a given figure.

The Figure Palette: Use this to create and arrange subplots, to view and plot workspace variables, and to add annotations.

The Plot Browser: Use this to select and control the visibility of the axes or graphics objects plotted in the figure, and to add data for plotting.

The Property Editor: Use this to set basic properties of the selected object and to obtain access to all properties through the Property Inspector.

5-535-53

Page 53: Chapter 5 Advanced Plotting and Model Building

The Figure window with the Plot Tools activated.Figure 5.4–3

5-545-54

Note that we can captureall the changes made to the plot by File-> Generate M-file

Page 54: Chapter 5 Advanced Plotting and Model Building

My example:

x = linspace(0.1,2,10);y1 = 1 + 0.5*x;y2 = 2*x.^2;y3 = 10.^(0.3*(1+x))subplot( 2, 2, 1)plot(x,y1,'d-.',x,y2,'*-',x,y3,'o:')legend('linear','power','10^x')grid onsubplot( 2, 2, 2)semilogx(x,y1,'d-.',x,y2,'*-',x,y3,'o:')grid onsubplot( 2, 2, 3)semilogy(x,y1,'d-.',x,y2,'*-',x,y3,'o:')grid onsubplot( 2, 2, 4)loglog(x,y1,'d-.',x,y2,'*-',x,y3,'o:')grid on

0 0.5 1 1.5 20

1

2

3

4

5

6

7

8

10-1

100

101

0

1

2

3

4

5

6

7

8

0 0.5 1 1.5 210

-2

10-1

100

101

10-1

100

101

10-2

10-1

100

101

linearpower

10x

Preview of Function Discovery (1st discuss the notes)

Page 55: Chapter 5 Advanced Plotting and Model Building

Using the Linear, Power, and Exponential Functions to Describe data.

Each function gives a straight line when plotted using a specific set of axes:

1. The linear function y mx b gives a straight line when plotted on rectilinear axes.

Its slope is m and its intercept is b.

2. The power function y bxm gives a straight line when plotted on log-log axes.

3. The exponential function y b(10)mx and its equivalent form y bemx give a straight line when plotted on a semilog plot whose y-axis is logarithmic.

5-565-56More? See pages 299-300.

Page 56: Chapter 5 Advanced Plotting and Model Building

Steps for Function DiscoverySummary of the procedures to find a function that describes a given set of data:Assume one of the function types - linear, exp, or power - can describe the data.

1. Examine the data near the origin. The exponential function y = b*10^(mx) can never pass through the origin

The linear function y = m*x + b can pass through the origin only if b = 0.

The power function y = b*x^m can pass through the origin but only if m > 0.

5-575-57

Page 57: Chapter 5 Advanced Plotting and Model Building

2. Plot the data using rectilinear scales.

If it forms a straight line, then it can be represented by the linear function and you are finished.

Otherwise, if you have data at x 0, thena. If y(0) 0, try the power function.b. If y(0) 0, try the exponential function.

If data is not given for x 0, proceed to step 3.

5-605-60

Steps for Function Discovery (continued)

Page 58: Chapter 5 Advanced Plotting and Model Building

3. If you suspect a power function, plot the data using log-log scales.

Only a power function will form a straight line on a log-log plot.

If you suspect an exponential function, plot the data using the semilog scales.

Only an exponential function will form a straight line on a semilog plot.

5-615-61

Steps for Function Discovery (continued)

(continued…)

Page 59: Chapter 5 Advanced Plotting and Model Building

4. In function discovery applications, we use the log-log and semilog plots only to identify the function type, but NOT to find the coefficients b and m.

The reason is that it is difficult to interpolate on log scales and we can do it much better on the linear scales.

In Matlab, b and m are found via polyfit function – finds polynomial of the specified degree n that best fits the data in the least squares sense

5-625-62

Steps for Function Discovery (continued)

Page 60: Chapter 5 Advanced Plotting and Model Building

Command

p = polyfit(x,y,n)

Description

Fits a polynomial of degree n to data described by the vectors x and y, where x is the independent variable.

Returns a row vector p of length n + 1 that contains the polynomial coefficients in order of descending powers.

The polyfit function. Table 5.5–1

5-635-63

Page 61: Chapter 5 Advanced Plotting and Model Building

Using the polyfit Function to Fit Equations to Data.

Syntax: p = polyfit(x,y,n)

where x and y contain the data, n is the order of the polynomial to be fitted, and p is the vector of polynomial coefficients.

The linear function: y = mx + b. In this case the variables w and z in the polynomial w = p1z+ p2 are the original data variables x and y, and we can find the linear function that fits the data by typing p = polyfit(x,y,1). The first element p1 of the vector p will be m, and the second element p2 will be b.

5-645-64

Page 62: Chapter 5 Advanced Plotting and Model Building

The power function: y bxm. In this case

log10 y m log10x log10b (5.5–5)

which has the form w p1z p2

where the polynomial variables w and z are related to the original data variables x and y by w log10 y and z log10x. Thus we can find the power function that fits the data by typing

p = polyfit(log10(x),log10(y),1)

The first element p1 of the vector p will be m, and the second element p2 will be log10b.

We can find b from b 10p2 .5-655-65

Page 63: Chapter 5 Advanced Plotting and Model Building

The exponential function: y b(10)mx. In this case

log10 y mx log10b (5.5–6)

which has the form w p1z p2

where the polynomial variables w and z are related to the original data variables x and y by w log10 y and z x. We can find the exponential function that fits the data by typing

p = polyfit(x, log10(y),1)

The first element p1 of the vector p will be m, and the second element p2 will be log10b.

We can find b from b 10p2 .5-665-66 More? See pages 302-303.

Page 64: Chapter 5 Advanced Plotting and Model Building

clear all; clf;disp('--------------------------------') x = [ 5, 10:10:100 ];y = [ 0 19 57 94 134 173 216 256 297 343 390 ]; p = polyfit(x,y,1)xv = linspace(min(x),max(x),1000);yv = polyval(p,xv); residuals = y - polyval(p,x);dmax = max(abs(residuals))D = sqrt( sum(residuals.^2) / length(x)) subplot(2,1,1)plot(x,y,'o',xv,yv)grid ontitle(['D = ',num2str(D),‘… dmax = ',num2str(dmax)]) subplot(2,1,2)plot(x,residuals,'*:')grid ontitle('Residuals')

%Fitting linep = 4.0693 *x -25.4071

%Fitting quadratic, just make it polyfit(x,y,2):p = 0.0049*x^2 + 3.5629*x -17.1145

0 10 20 30 40 50 60 70 80 90 100-200

0

200

400D = 4.1596 dmax = 8.4741

0 10 20 30 40 50 60 70 80 90 100-10

-5

0

5

10Residuals

My ExampleStretch of a spring data

Fitting line

0 10 20 30 40 50 60 70 80 90 1000

100

200

300

400D = 1.1087 dmax = 2.4567

0 10 20 30 40 50 60 70 80 90 100-4

-2

0

2Residuals

Page 65: Chapter 5 Advanced Plotting and Model Building

Fitting a linear equation: An experiment to measure force and deflection in a cantilever beam. Example 5.5-1. Figure 5.5–3

5-675-67

Page 66: Chapter 5 Advanced Plotting and Model Building

Plots for the cantilever beam example. Figure 5.5–4

5-685-68

Page 67: Chapter 5 Advanced Plotting and Model Building

clear all; clf;disp('--------------------------------') x = [ 0:100:800 ]; % x is applied forcey = [ 0 0.09 0.18 0.28 0.37 0.46 0.55 0.65 0.74];

% y is beam deflection p = polyfit(x,y,1)xv = linspace(min(x),max(x),1000);yv = polyval(p,xv);k = 1/p(1) residuals = y - polyval(p,x);dmax = max(abs(residuals))D = sqrt( sum(residuals.^2) / length(x)) subplot(2,1,1)plot(x,y,'o',xv,yv)grid ontitle(['D = ',num2str(D),' dmax = ',num2str(dmax)])xlabel('Force'); ylabel('Deflection'); subplot(2,1,2)plot(x,residuals,'*:')grid ontitle('Residuals')

p = 0.0009*x - 0.0018

k = 1/(p(1) = 1079.1 lb/inch ( f = k*x )

0 100 200 300 400 500 600 700 800-0.5

0

0.5

1D = 0.0026294 dmax = 0.0042222

Force

Def

lect

ion

0 100 200 300 400 500 600 700 800-5

0

5x 10

-3 Residuals

Note that the book actually plotsjust x = f/k, not the full polynomial.

cantilever beam example code

Page 68: Chapter 5 Advanced Plotting and Model Building

clear all; clf;disp('--------------------------------') x = [ 0 620 2262 3482 ]; % time in secsy = [ 145 130 103 90 ]; % temperaturey = y - 68; % subtract room temperature subplot(2,2,1)plot(x,y,'o-')xlabel('Time (sec)'); ylabel('Relative Temperature (F)'); subplot(2,2,2)semilogy(x,y,'o-')xlabel('Time (sec)'); ylabel('Relative Temperature (F)'); p = polyfit(x,log10(y),1)m = p(1)b = 10^p(2)xv = linspace(min(x),max(x),1000);yv = b*10.^(m*xv); t120 = (log10(120-68) - log10(b))/ m ; subplot(2,2,3)semilogy(xv,yv+68,x,y+68,'o',t120,120,'*')xlabel('Time (sec)'); ylabel('Relative Temperature (F)'); subplot(2,2,4)plot(xv,yv+68,x,y+68,'o',t120,120,'*')xlabel('Time (sec)'); ylabel('Relative Temperature (F)');

p = -0.0002 x + 1.8889m = -1.5563e-004b = 77.4361

The model is T – 68 = b*10^(m*t)

0 1000 2000 3000 400020

40

60

80

Time (sec)R

elat

ive

Tem

pera

ture

(F

)0 1000 2000 3000 4000

101.4

101.6

101.8

Time (sec)

Rel

ativ

e T

empe

ratu

re (

F)

0 1000 2000 3000 400010

1

102

103

Time (sec)

Rel

ativ

e T

empe

ratu

re (

F)

0 1000 2000 3000 400080

100

120

140

160

Time (sec)

Rel

ativ

e T

empe

ratu

re (

F)

Fitting an exponential function. Temperature of a cooling cup of coffee, plotted on various coordinates.

Page 69: Chapter 5 Advanced Plotting and Model Building

Fitting an exponential function. Temperature of a cooling cup of coffee, plotted on various coordinates. Example 5.5-2. Figure 5.5–5

5-695-69

Page 70: Chapter 5 Advanced Plotting and Model Building

Fitting a power function. An experiment to verify Torricelli’s principle. Example 5.5-3. Figure 5.5–6

5-705-70

Page 71: Chapter 5 Advanced Plotting and Model Building

x = [ 6:3:15 ]; % level of the cupstimes = [ 9 8 7 6];flow = 1./times;y = flow; p = polyfit(log10(x),log10(y),1)m = p(1)b = 10^p(2)xv = linspace(min(x),max(x),1000);yv = b*xv.^m; subplot(2,1,1)loglog(xv,yv,x,y,'o')xlabel('Volume (cups)'); ylabel('Flow Rate (cups/sec)');axis('tight') subplot(2,1,2)plot(xv,1./yv,x,1./y,'o')xlabel('Volume (cups)'); ylabel('Fill time (sec)');axis('tight') disp('Extrapolation:')V = 36f36 = b*V^mfilltime = 1/f36----------------------------------------------------p = 0.4331*x - 1.3019m = 0.4331b = 0.0499

Extrapolation:

V = 36f36 = 0.2356filltime = 4.2452

101

10-0.9

10-0.8

10-0.7

Volume (cups)F

low

Rat

e (c

ups/

sec)

10 15 20 25 30 35 40

5

6

7

8

9

Volume (cups)

Fill

tim

e (s

ec)

Page 72: Chapter 5 Advanced Plotting and Model Building

Flow rate and fill time for a coffee pot. Figure 5.5–7

5-715-71

Page 73: Chapter 5 Advanced Plotting and Model Building

The Least Squares Criterion: used to fit a function f (x). It minimizes the sum of the squares of the residuals, J.

J is defined as

We can use this criterion to compare the quality of the curve fit for two or more functions used to describe the same data.

The function that gives the smallest J value gives the best fit.

m

i1

J

[ f (xi ) – yi ]2 (5.6–1)

5-725-72

Page 74: Chapter 5 Advanced Plotting and Model Building

Illustration of the least squares criterion. Figure 5.6–1

5-735-73

Page 75: Chapter 5 Advanced Plotting and Model Building

The least squares fit for the example data. Figure 5.6–2

5-745-74

See pages 312-315.

Page 76: Chapter 5 Advanced Plotting and Model Building

My Example of Linear Fit:My Example of Linear Fit:clear all; clf;

x = [ 0 3 8]

y = [ 1 4 10]

p = polyfit(x,y,1)

pval = polyval(p,x)

J = sum( ( pval - y ).^2 )

xvec = linspace(min(x),max(x),100);

yvec = polyval(p,xvec);

plot(xvec,yvec,x,y,'o')

--------------------------------

p = 1.1327 0.8469

pval = 0.8469 4.2449 9.9082

J = 0.0918

0 1 2 3 4 5 6 7 80

1

2

3

4

5

6

7

8

9

10

Page 77: Chapter 5 Advanced Plotting and Model Building

p = polyfit(x,y,n)

Fits a polynomial of degree n to data described by the vectors x and y, where x is the independentvariable.

Returns a row vector p of length n+1 that contains the polynomial coefficients in order of descending powers.

5-755-75

The polyfit function is based on the least-squares method. Its syntax is

See page 315, Table 5.6-1.

Page 78: Chapter 5 Advanced Plotting and Model Building

Regression using polynomials of first through fourth degree.Figure 5.6–3

5-765-76

The program is on pages 315 to 316.

Page 79: Chapter 5 Advanced Plotting and Model Building

My Example from polyfitMy Example from polyfit

0 5 10

0

20

40

60

80

100

120

Polyn deg = 1 J = 2048.368

x

x

0 5 10

0

20

40

60

80

100

120

Polyn deg = 2 J = 179.9441

x

x0 5 10

0

20

40

60

80

100

120

Polyn deg = 3 J = 8.9246

x

x

0 5 10

0

20

40

60

80

100

120

Polyn deg = 4 J = 0.27338

xx

% Improving code on p 315 and changing dataclear all; clf;x = -2:10;y = -2+3*x + 5*exp(0.3*x);xp = linspace( min(x), max(x),1000);for k = 1:4 % power of polynomials coeff = polyfit(x,y,k); yp = polyval(coeff,xp); J = sum( (polyval(coeff,x) - y).^2 ); subplot(2,2,k) plot(xp,yp,x,y,'o'); axis ([ min(x)-0.2 max(x)+0.2 ... min(y)-0.2 max(y)+0.2 ]) xlabel('x'); ylabel('x'); title(['Polyn deg = ',num2str(k),... ' J = ',num2str(J)])end

Page 80: Chapter 5 Advanced Plotting and Model Building

Beware of using polynomials of high degree. An example of a fifth-degree polynomial that passes through all six data points but exhibits large excursions between points. Figure 5.6–4

5-775-77

Page 81: Chapter 5 Advanced Plotting and Model Building

My example, exact polynomial My example, exact polynomial fit of high degree.fit of high degree.

0 2 4 6-4

-2

0

2

4Polyn deg = 3 J = 11.7413

x

x

0 2 4 6-3

-2

-1

0

1

2

3Polyn deg = 4 J = 10.2753

x

x

0 2 4 6-4

-2

0

2

4Polyn deg = 5 J = 4.6253

x

x

0 2 4 6-6

-4

-2

0

2

4Polyn deg = 6 J = 9.784e-024

x

x

% p 317 exact polyn fit of high degreeclear all; clf;x = 0:6;y = -4+8*rand(size(x));xp = linspace( min(x), max(x),1000);for k = 3:6 % power of polynomials coeff = polyfit(x,y,k); yp = polyval(coeff,xp); J = sum( (polyval(coeff,x) - y).^2 ); subplot(2,2,k-2) plot(xp,yp,x,y,'o'); %axis ([ min(x)-0.2 max(x)+0.2 ... % min(y)-0.2 max(y)+0.2 ]) xlabel('x'); ylabel('x'); title(['Polyn deg = ',num2str(k),... ' J = ',num2str(J)])end

Page 82: Chapter 5 Advanced Plotting and Model Building

Assessing the Quality of a Curve Fit:

Denote the sum of the squares of the deviation of the y values from their mean y by S, which can be computed from

(yt – y )2 (5.6–2)mi1

S

5-785-78

Page 83: Chapter 5 Advanced Plotting and Model Building

This formula can be used to compute another measure of the quality of the curve fit, the coefficient of determination, also known as the r-squared value. It is defined as

(5.6–3)JS

r 2 1

5-795-79

The value of S indicates how much the data is spread around the mean, and the value of J indicates how much of the data spread is unaccounted for by the model.

Thus the ratio J / S indicates the fractional variation unaccounted for by the model.

Page 84: Chapter 5 Advanced Plotting and Model Building

For a perfect fit, J 0 and thus r 2 1. Thus the closer r 2 is to 1, the better the fit. The largest r 2 can be is 1.

It is possible for J to be larger than S, and thus it is possible for r 2 to be negative. Such cases, however, are indicative of a very poor model that should not be used.

As a rule of thumb, a good fit accounts for at least 99 percent of the data variation. This value corresponds to r 2 0.99.

5-805-80

More? See pages 319-320.

Page 85: Chapter 5 Advanced Plotting and Model Building

% p 319 Curve fitting exampleclear all; clf;x = -2:10;y = -2+3*x + 2*sin(x);ym = mean(y);xp = linspace( min(x), max(x),1000);for k = 1:4 % power of polynomials coeff = polyfit(x,y,k); yp = polyval(coeff,xp); J = sum( (polyval(coeff,x) - y).^2 ); S = sum( (y - ym).^2 ); r2 = 1 - J/S; subplot(2,2,k) plot(xp,yp,x,y,'o'); %axis ([ min(x)-0.2 max(x)+0.2 ... % min(y)-0.2 max(y)+0.2 ]) xlabel('x'); ylabel('x'); title(['Deg = ',num2str(k),... '; J = ',num2str(J)... '; S = ',num2str(S)... '; r^2 = ',num2str(r2)])end

Quality of Curve Fit (my example)

-5 0 5 10-10

0

10

20

30Deg = 1; J = 24.5642; S = 1764.7432; r2 = 0.98608

xx

-5 0 5 10-10

0

10

20

30Deg = 2; J = 23.0771; S = 1764.7432; r2 = 0.98692

x

x

-5 0 5 10-10

0

10

20

30Deg = 3; J = 22.0227; S = 1764.7432; r2 = 0.98752

x

x

-5 0 5 10-20

-10

0

10

20

30Deg = 4; J = 12.6007; S = 1764.7432; r2 = 0.99286

x

x

Page 86: Chapter 5 Advanced Plotting and Model Building

Effect of coefficient accuracy on a sixth-degree polynomial. Top graph: 14 decimal-place accuracy. Bottom graph: 8 decimal-place accuracy. Figure 5.6–5

5-825-82

More? See pages 320-321.

Page 87: Chapter 5 Advanced Plotting and Model Building

Avoiding high degree polynomials: Use of two cubics to fit data. Figure 5.6–6

5-835-83

See pages 321-322.

Page 88: Chapter 5 Advanced Plotting and Model Building

Scaling the Data

The effect of computational errors in computing the coefficients can be lessened by properly scaling the x values.

You can scale the data yourself before using polyfit.

Some common scaling methods are

1. Subtract the minimum x value or the mean x value from the x data, if the range of x is small, or

2. Divide the x values by the maximum value or the mean value, if the range is large.

5-81More? See pages 323-324.

Page 89: Chapter 5 Advanced Plotting and Model Building

x = [ 1990:1999 ];y= [ 2.1 3.4 4.5 5.3 6.2 6.6 6.8 7 7.4 7.8];

p = polyfit(x,y,3)

Warning: Polynomial is badly conditioned. Add points with distinct X values, reduce the degree of the polynomial, or try centering and scaling as described in HELP POLYFIT.

clear all; clf;disp('--------------------------------') x = [ 1990:1999 ] - 1990;y= [ 2.1 3.4 4.5 5.3 6.2 6.6 6.8 7 7.4 7.8];ym = mean(y)p = polyfit(x,y,3) xv = linspace(min(x),max(x),1000);yv = polyval(p,xv); subplot(2,1,1)plot(xv,yv,x,y,'o')xlabel('year'); ylabel('Cars (millions)');axis('tight') residuals = y - polyval(p,x);subplot(2,1,2)plot(x,residuals,'o:')xlabel('year'); ylabel('Cars (millions)');axis('tight')title('Residuals')

p = 0.0087(x -1990)^3 - 0.1851(x-1990)^2 + 1.5991(x – 1990) + 2.0362

0 1 2 3 4 5 6 7 8 9

3

4

5

6

7

yearC

ars

(mill

ions

)

0 1 2 3 4 5 6 7 8 9

-0.1

0

0.1

year

Car

s (m

illio

ns)

Residuals

Example 5.6.1Estimation of Traffic Flow

subtract off initial year

J = sum( (polyval(p,x) - y).^2 ); S = sum( (y - ym).^2 );r2 = 1 - J/S;

Get r2 = 0.9972 – very good!

Page 90: Chapter 5 Advanced Plotting and Model Building

clear all; clf;disp('--------------------------------') x = [ 1990:1999 ] ;y= [ 2.1 3.4 4.5 5.3 6.2 6.6 6.8 7 7.4 7.8]; [p,s,mu] = polyfit(x,y,3) xv = linspace(min(x),max(x),1000);yv = polyval(p,xv,s,mu); subplot(2,1,1)plot(xv,yv,x,y,'o')xlabel('year'); ylabel('Cars (millions)');axis('tight') residuals = y - polyval(p,x,s,mu);subplot(2,1,2)plot(x,residuals,'o:')xlabel('year'); ylabel('Cars (millions)');axis('tight')title('Residuals')

1990 1991 1992 1993 1994 1995 1996 1997 1998 1999

3

4

5

6

7

yearC

ars

(mill

ions

)

1990 1991 1992 1993 1994 1995 1996 1997 1998 1999

-0.1

0

0.1

year

Car

s (m

illio

ns)

Residuals

Using s and mu to center the polynomialaround average of x and its standard deviation mu = [ aver std ]

Traffic FlowAlternative approach using mu

Page 91: Chapter 5 Advanced Plotting and Model Building

Using Residuals: Residual plots of four models. Figure 5.6–7

5-845-84

See pages 325-326.

Page 92: Chapter 5 Advanced Plotting and Model Building

Linear-in-Parameters Regression: Comparison of first- and second-order model fits. Figure 5.6–8

5-855-85

See pages 329-331.

Page 93: Chapter 5 Advanced Plotting and Model Building

Basic Fitting Interface

MATLAB supports curve fitting through the Basic Fitting interface. Using this interface, you can quickly perform basic curve fitting tasks within the same easy-to-use environment. The interface is designed so that you can:

Fit data using a cubic spline or a polynomial up to degree 10.Plot multiple fits simultaneously for a given data set.Plot the residuals.Examine the numerical results of a fit.Interpolate or extrapolate a fit.Annotate the plot with the numerical fit results and the norm of residuals.Save the fit and evaluated results to the MATLAB workspace.5-865-86

Page 94: Chapter 5 Advanced Plotting and Model Building

The Basic Fitting interface. Figure 5.7–1

5-875-87

Page 95: Chapter 5 Advanced Plotting and Model Building

A figure produced by the Basic Fitting interface.Figure 5.7–2

5-885-88

More? See pages 331-334.

Page 96: Chapter 5 Advanced Plotting and Model Building

Applications of interpolation: A plot of temperature data versus time. Figure 7.4–1

7-327-32

Additional material on interpolation and splines from Ch 7

Page 97: Chapter 5 Advanced Plotting and Model Building

% P 446 my exampleclear all; clf;% temperature measured every % 2 hours, but need it every hourx = 0:2:24; y = 60 + 20*sin(2*pi*x/24);xv = linspace( min(x),max(x),1000);yv = 60 + 20*sin(2*pi*xv/24);xint = 0:24;yint = interp1(x,y,xint);plot(xv,yv,x,y,'o',xint,yint,'*')

0 5 10 15 20 2540

45

50

55

60

65

70

75

80

Page 98: Chapter 5 Advanced Plotting and Model Building

Temperature measurements at four locations. Figure 7.4–2

7-337-33

More? See pages 444-449.

Page 99: Chapter 5 Advanced Plotting and Model Building

Z_int = interp2(x,y,z,x_int,y_int)

Used to linearly interpolate a function of two variables: y f (x, y).

Returns a linearly interpolated vector z_int at the specified values x_int and y_int, using data stored in x, y, and z.

7-357-35

Table 7.4–1 Continued

x = [0 1]y = [0 2]z = [ 49 54 53 57]interp2(x,y,z,0.6,1.5)

54.55

Page 100: Chapter 5 Advanced Plotting and Model Building

Cubic-spline interpolation: The following session produces and plots a cubic-spline fit, using an increment of 0.01 in the x values.

>>x = [7,9,11,12];>>y = [49,57,71,75];>>x_int = [7:0.01:12];>>y_int = spline(x,y,x_int);>>plot(x,y,’o’,x,y,’--’,x_int,y_int),... xlabel(’Time (hr)’),ylabel(’Temperature (deg F)’,... title(’Temperature Measurements at a Single Location’),... axis([7 12 45 80])

This produces the next figure.7-367-36

Page 101: Chapter 5 Advanced Plotting and Model Building

Linear and cubic-spline interpolation of temperature data. Figure 7.4–3

7-377-37 More? See pages 449-452.

Page 102: Chapter 5 Advanced Plotting and Model Building

% P 451 my example splinesclear all; clf;disp('-----------------------')% Just a random set of temperature data x = 0:2:24; y = 60 + 20*rand(size(x));xint = linspace( min(x),max(x),1000);yint = interp1(x,y,xint,'spline');plot(x,y,'o',x,y,'-.',xint,yint)legend('Data','Linear','Cubic Spline')xtry = [ 12.5 1.5];ytry = interp1(x,y,xtry,'spline')

ytry = 66.9181 73.1265 -- to get spline approximation at specific points

0 5 10 15 20 2560

65

70

75

80

85

Data

Linear

Cubic Spline

Page 103: Chapter 5 Advanced Plotting and Model Building

Command

y_est = interp1(x,y,x_est,’spline’)

Description

Returns a column vector y_est that contains the estimated values of y that correspond to the x values specified in the vector x_est, using cubic-spline interpolation.

Polynomial interpolation functions. Table 7.4–2

7-387-38

Page 104: Chapter 5 Advanced Plotting and Model Building

Y_int = spline(x,y,x_int)

Computes a cubic-spline interpolation where x and y are vectors containing the data and x_int is a vector containing the values of the independent variable x at which we wish to estimate the dependent variable y.

The result Y_int is a vector the same size as x_int containing the interpolated values of y that correspond to x_int.

7-397-39

Table 7.4–2 Continued

Page 105: Chapter 5 Advanced Plotting and Model Building

[breaks, coeffs, m, n] = unmkpp(spline(x,y))

Computes the coefficients of the cubic-spline polynomials for the data in x and y.

The vector breaks contains the x values, and the matrix coeffs is an m n matrix containing the polynomial coefficients.

The scalars m and n give the dimensions of the matrix coeffs; m is the number of polynomials, and n is the number of coefficients for each polynomial.

7-407-40

Table 7.4–2 Continued

Page 106: Chapter 5 Advanced Plotting and Model Building

clear all; clf;x = [7:7:42]';y = [8 41 133 250 280 297];xx = linspace(min(x),max(x),1000); yy = spline(x,y,xx);[breaks, coeffs, m, n] = unmkpp(spline(x,y))plot(x,y,'o',xx,yy)title('Spline fit')

breaks = 7 14 21 28 35 42coeffs = -0.0004 0.6102 0.4619 8.0000 -0.0004 0.6020 8.9476 41.0000 -0.0972 0.5939 17.3190 133.0000 0.0626 -1.4469 11.3476 250.0000 0.0626 -0.1327 0.2905 280.0000m = 5n = 4

5 10 15 20 25 30 35 40 450

50

100

150

200

250

300Spline fit

My Example for spline coefficients

Page 107: Chapter 5 Advanced Plotting and Model Building

3-D plots3-D plots

We look at three basic types:We look at three basic types:

line, surface and contour plots.line, surface and contour plots.

Page 108: Chapter 5 Advanced Plotting and Model Building

Three-Dimensional Line Plots:

>>t = [0:pi/50:10*pi];>>plot3(exp(-0.05*t).*sin(t),exp(-0.05*t).*cos(t),t),... xlabel(’x’),ylabel(’y’),zlabel(’z’),grid

5-895-89

t goes from 0 to 10*pisin/cos go through 5 cyclesx^2 + y^2 = exp(-0.1t) decreases.x and y decrease!

Page 109: Chapter 5 Advanced Plotting and Model Building

Surface Plots: z = f(x,y) – represents a surface in 3D.mesh, surf etc… generate surface plots.

First, need to generate a grid (mesh) of points in x-y plane and evaluate f on it.x = xmin: dx : xmax; y = ymin: dy : ymax; [X,Y] = meshgrid(x,y) generates such a grid with corners (xmin,ymin) and (xmax,ymax)Matrices X and Y contain coordinate pairs of every point on the grid

If x and y are the same, can use [X,Y] = meshgrid(x)

The following session shows how to generate the surface plot of the function z = xe-[(x-y2)2+y2], for -2 <= x <= 2 and -2 <= y <= 2, with a spacing of 0.1.

This plot appears in Figure 5.8–2.

>>[X,Y] = meshgrid(-2:0.1:2);>>Z = X.*exp(-((X-Y.^2).^2+Y.^2));>>mesh(X,Y,Z),xlabel(’x’),ylabel(’y’),zlabel(’z’)

5-915-91

Page 110: Chapter 5 Advanced Plotting and Model Building

A plot of the surface z xe[(xy2)2y2] created with the mesh function. Figure 5.8–2

5-925-92More? See pages 335-336.

Page 111: Chapter 5 Advanced Plotting and Model Building

My example with My example with surf surf command:command:

-2-1

01

2

-2

-1

0

1

20

0.1

0.2

0.3

0.4

0.5

xy

z

[X,Y] = meshgrid(-2:0.1:2);Z = sqrt(X.^2+Y.^2).*exp(-2*((X-Y).^2+Y.^2));surf(X,Y,Z),xlabel('x'),ylabel('y'),zlabel('z')

Page 112: Chapter 5 Advanced Plotting and Model Building

Contour PlotsTopographic plots show the contours of the land by means of constant elevation lines – contour lines.

The following session generates the contour plot of the function whose surface plot is shown in Figure 5.8–2; namely, z xe[(xy2)2y2], for 2 x 2 and 2 y 2, with a spacing of 0.1.

>>[X,Y] = meshgrid(-2:0.1:2);>>Z = X.*exp(-((X- Y.^2).^2+Y.^2));>>contour(X,Y,Z),xlabel(’x’),ylabel(’y’)

5-935-93

Page 113: Chapter 5 Advanced Plotting and Model Building

A contour plot of the surface z xe[(xy2)2y2] created with the contour function. Figure 5.8–3

5-945-94

More? See page 337.

Page 114: Chapter 5 Advanced Plotting and Model Building

Functioncontour(x,y,z)

mesh(x,y,z)

meshc(x,y,z)

meshz(x,y,z)

surf(x,y,z)

surfc(x,y,z)

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

[X,Y] = meshgrid(x)

waterfall(x,y,z)

DescriptionCreates a contour plot.

Creates a 3D mesh surface plot.

Same as mesh but draws contours under the surface.

Same as mesh but draws vertical reference lines under the surface.

Creates a shaded 3D mesh surface plot.

Same as surf but draws contours under the surface.

Creates the matrices X and Y from the vectors x and y to define a rectangular grid.

Same as [X,Y]= meshgrid(x,x).

Same as mesh but draws mesh lines in one direction only.

Three-dimensional plotting functions. Table 5.8–1

5-955-95

Page 115: Chapter 5 Advanced Plotting and Model Building

Plots of the surface z xe(x2y2) created with the mesh function and its variant forms: meshc, meshz, and waterfall. a) mesh, b) meshc, c) meshz, d) waterfall.Figure 5.8–4

5-965-96

Page 116: Chapter 5 Advanced Plotting and Model Building

The following slides contain figures from the chapter’s homework problems.

5-97

Page 117: Chapter 5 Advanced Plotting and Model Building

Figure P27

5-985-98

Page 118: Chapter 5 Advanced Plotting and Model Building

Figure P28

5-995-99

Page 119: Chapter 5 Advanced Plotting and Model Building

Figure P56

5-1005-100