36
1 Cureve Fitting Introduction to Matlab 10 Omed Ghareb Abdullah Sulaimani University Sulaimani University College of Sciences College of Sciences Physics Department Physics Department 1 Data points (x i , y i ) can be approximated by a function Data Approximation with a Function a function y = f(x) such that the function passes “close” to the data points but does not necessarily pass through them. Data fitting is necessary to model data with fluctuations such as experimental measurements measurements. The most common form of data fitting is the least squares method. 2

10 Matlab Fitting

Embed Size (px)

DESCRIPTION

Lecture (10): Matlab Fitting - Sulaimani University - College of Science - Physics Department

Citation preview

Page 1: 10 Matlab Fitting

1

Cureve Fitting

Introduction to Matlab 10

Omed Ghareb AbdullahSulaimani UniversitySulaimani UniversityCollege of SciencesCollege of SciencesPhysics DepartmentPhysics Department

1

Data points (xi, yi) can be approximated by a function

Data Approximation with a Function

a function y = f(x) such that the function passes “close” to the data points but does not necessarily pass through them.Data fitting is necessary to model data with fluctuations such as experimental measurementsmeasurements.The most common form of data fitting is theleast squares method.

2

Page 2: 10 Matlab Fitting

2

Fitting Polynomials to DataFitting analytical curves to experimental data is a common task in engineering.  The simplest is linear interpolation (straight lines between data points).  P l i l     f   d   d fi     d  h     l Polynomials are often used to define curves, and there are several options:

Fit curve through all data points (polynomial—spline interpolation),Fit curve through some data points,Fit curve as close to points as possible (polynomial regression, also called “least square fitting”)

polynomial

interpolation

polynomial

regression

3

y

Multi‐Valued Data Points

x

Some points are multi-valued, i.e. different measurements of the same x yielded different results. By definition, you cannot use an interpolation function.

4

Page 3: 10 Matlab Fitting

3

Fitting Data with a Linear Function

y

x

y = ax+b,

Determine a and b.

Using the least squares algorithm, ensure that all the data points fall close to the straight line/function.

5

Linear interpolation with a polynomial of degree oneInput: two nodes

Fitting Data with a Linear Function

pOutput: Linear polynomial

),( 11 yx

),( 22 yx=+=+

2221

1211

ypxpypxp

21)( pxpxy += ⎟⎟⎠

⎞⎜⎜⎝

⎛=⎟⎟

⎞⎜⎜⎝

⎛⎟⎟⎠

⎞⎜⎜⎝

2

1

2

1

2

1

11

yy

pp

xx

6

Page 4: 10 Matlab Fitting

4

Quadratic interpolation with a polynomial of degree two

Fitting Data with a quadratic Function

=++

=++

=++

3332231

2322221

1312211

ypxpxp

ypxpxp

ypxpxp

),( 11 yx

),( 22 yx

),( 33 yx

322

1)( pxpxpxy ++=⎟⎟⎟

⎜⎜⎜

⎛=

⎟⎟⎟

⎜⎜⎜

⎟⎟⎟

⎜⎜⎜

3

2

1

3

2

1

323

222

121

111

yyy

ppp

xxxxxx

7

Polynomial interpolation of degree n

Fitting Data with a polynomial Function

⎟⎟⎟⎟

⎜⎜⎜⎜⎜

=⎟⎟⎟⎟

⎜⎜⎜⎜⎜

⎟⎟⎟⎟

⎜⎜⎜⎜⎜

n

n

n

yy

pp

xxxx

MMMMOM

L

L

2

1

2

1

22

11

1

11

),( 11 yx

),( 22 yx

),( nn yx

11)( ++++= nnn pxpxpxy L

⎠⎜⎝⎠

⎜⎝⎠

⎜⎝ nnn

nn ypxx L 1

8

Page 5: 10 Matlab Fitting

5

Higher‐Order Polynomials

9

( ) niyx ii K1, =• Data points

Linear Least Squares Algorithm

( ) baxxfy +==

( )baxye iii +−=

222

21 neeez +++= K

• Interpolating function (linear)

• Errors between function and data points

• Sum of the squares of the errors

( )[ ]2

1∑

=

+−=n

iii baxyz

• Compact notation

A least squares linear fit minimizes the square of the distance between every data point and the line of best fit

10

Page 6: 10 Matlab Fitting

6

polyfit Function

Polynomial curve fittingcoef = polyfit(x y n)coef = polyfit(x,y,n)A least‐square fit with polynomial of degree n. x and y are data vectors, and coef is vector of coefficients of the polynomial, coef = [q2 - !q3 - !/!/!/!- !qo - !qo,2]

11

Polynomial Curve Fitting x and y are vectors containing the x and y data to be fitted, and n is the order of the polynomial to return. For example, consider the x‐y test data.consider the x y test data.

x = [-1.0, -0.7, -0.2, 0.6, 1.0];y = [-2.1, 0.3 , 1.7, 1.9, 2.1];

A fourth order (n=4) polynomial that approximately fits the data is

p = polyfit(x,y,4)

p = -0.7801 1.8224 -1.0326 0.2776 1.8126

In other words, the polynomial function would be:

12

Page 7: 10 Matlab Fitting

7

Polyfit &  Polyval• MATLAB provides built-in functionality for fitting data

to polynomial equations.

polyfit function performs the fit and returns

p = polyfit(x,y,n)

Where

– polyfit function performs the fit and returns coefficients

– polyval function evaluates the polynomial using the polyfit coefficients

y = polyval(p,x)

WhereWherex – vector of x datay ‐ vector of y datan – order of the polynomial to

use (1= linear, 2= quadratic, 3= cubic…)

p – coefficients of thepolynomial

Wherex – vector of x datap – coefficients of the

polynomialy – vector of yfit data

13

polyfit - to find the polynomial (the coefficients)

x = [-1.0, -0.7, -0.2, 0.6, 1.0];

Polynomial Interpolation in Matlab

polyval – to evaluate the polynomial (e.g. to graph it)

y = [-2.1, 0.3, 1.7, 1.9, 2.1];

% For 5 points, we need a 4th degree polynomial

p = polyfit(x, y, 4);

interp_at_one_fourth = polyval(p, 0.25);% Evaluate at a range of values for a smooth plotxx = -1.0:0.1:1.0;yy = polyval(p, xx);plot(x,y,'or',xx,yy,'b-',0.25, interp_at_one_fourth,'sk');

14

Page 8: 10 Matlab Fitting

8

Polynomial Curve Fitting x = [-1.0, -0.7, -0.2, 0.6, 1.0];

y = [-2.1, 0.3, 1.7, 1.9, 2.1];y [ 2.1, 0.3, 1.7, 1.9, 2.1];

% For 5 points, we need a 4th degree polynomial

p = polyfit(x, y, 4)interp_at_one_fourth = polyval(p, 0.25)% Evaluate at a range of values for a smooth plotxx = -1.0:0.1:1.0;yy = polyval(p xx);yy = polyval(p, xx);plot(x,y,'or',xx,yy,'b-',0.25,interp_at_one_fourth,'sk');

15

2

2.5

p = polyfit(x, y, 4);

-0.5

0

0.5

1

1.5

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

-2

-1.5

-1

16

Page 9: 10 Matlab Fitting

9

2

2.5

p = polyfit(x, y, 3);

-0.5

0

0.5

1

1.5

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

-2

-1.5

-1

17

2

2.5

p = polyfit(x, y, 2);

-0.5

0

0.5

1

1.5

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

-2

-1.5

-1

18

Page 10: 10 Matlab Fitting

10

3

p = polyfit(x, y, 1);

1

0

1

2

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

-2

-1

19

Choosing the Right Polynomial

The degree of the correct approximating function depends on the type of data being analyzed.depends on the type of data being analyzed.

When a certain behavior is expected, such as the linear response of beam deflection under increasing loads, we know what type of function to use, and simply have to solve for its coefficients.

When we don’t know what sort of response to expect, ensure your data sample size is large enough to clearly distinguish which degree is the best fit.

20

Page 11: 10 Matlab Fitting

11

Basic Curve‐Fitting ToolsMethod 2Method 2Curve Fitting Tools can be accessed directly from the figure

i dwindow:

To access curve fitting directly from the figure window, select ‘basic fitting’ from the ‘tools’ pulldown menu in the figure window.

Tools Basic Fitting

Given x=[0:5]; y=[0,1,60,40,41,47];

Try fitting polynomials of various degrees...

This is a quick and easy method to calculate and visualize a variety of higher order functions including interpolation

21

Basic Curve‐Fitting Tools

clear;clcclear;clcx=[0:5]; y=[0,1,60,40,41,47];plot(x,y,'rh')axis([0 10 0 100]);

Try fitting polynomials of various degrees...

22

Page 12: 10 Matlab Fitting

12

Solution

23

Solution

24

Page 13: 10 Matlab Fitting

13

Solution

25

Solution

26

Page 14: 10 Matlab Fitting

14

Solution

27

Solution

28

Page 15: 10 Matlab Fitting

15

Solution

An example of a fifth-degree polynomial that passes through all six data points but exhibits large excursions between points. 29

Higher Order Curve Fitting

Caution:Higher order polynomial fits should Higher order polynomial fits should only be used when a large number of data points are available.Higher order polynomial fitting functions may fit more the data more 

l  b       i ld   accurately but may not yield an interpretable model.Higher order polynomial can introduce unwanted wiggles.

30

Page 16: 10 Matlab Fitting

16

Method 3Method 3

Higher Order Curve Fitting

Curve Fitting ToolboxThe curve fitting toolbox is accessible by the ‘cftool’ commandVery powerful tool for data smoothing, curve fitting, and applying and evaluating mathematical models to data points

31

Higher Order Curve Fitting

32

Page 17: 10 Matlab Fitting

17

Curve Fitting Toolbox

Before you can import data into the Curve Fitting Tool, the data

1. Loading Data Sets:y p g

variables must exist in the MATLAB workspace. You can import data into the Curve Fitting Tool with the Data GUI. You open this GUI by clicking the Data button on the Curve Fitting Tool. The Data Sets pane allows you to:Import predictor (X) data, response (Y) data, and weights. If you do not import weights, then they are assumed to be 1 for all data points. y p g y pSpecify the name of the data set. Preview the data. Click the Create data set button to complete the data import process.

33

Curve Fitting Toolbox

34

Page 18: 10 Matlab Fitting

18

Curve Fitting Toolbox

If your data is noisy, you might need to apply a smoothing

2. Smoothing Data Points:y y y g pp y g

algorithm to expose its features, and to provide a reasonable starting approach for parametric fitting.

The two basic assumptions that underlie smoothing are:

1. The relationship between the response data and the predictor data is smooth.

2. The smoothing process results in a smoothed value that is a better estimate of the original value because the noise has been reduced.

35

Curve Fitting Toolbox

The Curve Fitting Toolbox supports these smoothing methods:

2. Smoothing Data Points:g pp g

Moving Average Filtering: Lowpass filter that takes the average of neighboring data points. Lowess and Loess: Locally weighted scatter plot smooth. These methods use linear least squares fitting, and a first-degree polynomial (lowess) or a second-degree polynomial (loess). Robust lowess and loess methods that are resistant to outliers are also available. Savitzky-Golay Filtering: A generalized moving average where you derive the filter coefficients by performing an unweightedlinear least squares fit using a polynomial of the specified degree.

36

Page 19: 10 Matlab Fitting

19

Smoothing Method and Parameters

Curve Fitting Toolbox

Span: The number of data points used to compute each smoothed value.

• For the moving average and Savitzky-Golay methods, the span must be odd. For all locally weighted smoothing methods, if the span is less than 1, it is interpreted as the percentage of the total number of data pointspercentage of the total number of data points.

Degree: The degree of the polynomial used in the Savitzky-Golay method. The degree must be smaller than the span.

37

Excluding Data Points:

Curve Fitting Toolbox

It may be necessary to remove outlier points from a data set before attempting a curve fitTypically, data points are excluded so that subsequent fits are not adversely affected.Can help improve a mathematical model’sCan help improve a mathematical model s predictability

38

Page 20: 10 Matlab Fitting

20

Excluding Data Points:

h  C   i i   lb   id     h d     l d  

Curve Fitting Toolbox

The Curve Fitting Toolbox provides two methods to exclude data:Marking Outliers: Outliers are defined as individual data points that you exclude because they are inconsistent with the statistical nature of the bulk of the data. Sectioning: Sectioning excludes a window of response or predictor data. For example, if many data points in a data set are corrupted by large systematic errors  you might set are corrupted by large systematic errors, you might want to section them out of the fit. 

For each of these methods, you must create an exclusion rule, which captures the range, domain, or index of the data points to be excluded.

39

Plotting Fitting Curves:

Th  Fit Edit ll    t

Curve Fitting Toolbox

The Fit Editor allows you to:Specify the fit name, the current data set, and the exclusion rule. Explore various fits to the current data set using a library or custom equation, a smoothing spline, or an interpolant. O id  th  d f lt fit  ti   h   th  Override the default fit options such as the coefficient starting values. Compare fit results including the fitted coefficients and goodness of fit statistics. 

40

Page 21: 10 Matlab Fitting

21

Plotting Fitting Curves:

Curve Fitting Toolbox

The Table of Fits allows you to:Keep track of all the fits and their data sets for the current session. Display a summary of the fit results. Save or delete the fit results  Save or delete the fit results. 

41

Analyzing Fits:

Curve Fitting Toolbox

You can evaluate (interpolate or extrapolate), differentiate, or integrate a fit over a specified data range with the Analysis GUI. You open this GUI by clicking the Analysis button on the Curve Fitting Tool.

42

Page 22: 10 Matlab Fitting

22

Analyzing Fits:

Curve Fitting Toolbox

To Test your Model’s Predictions:Enter the appropriate MATLAB vector in the Analyze at Xi field. Select the Evaluate fit at Xi check box. Select the Plot results and Plot data set check boxes. Click the Apply buttonClick the Apply button. The numerical extrapolation results are displayed

43

Saving Your Work:

Curve Fitting Toolbox

You can save one or more fits and the associated fit results as variables to the MATLAB workspace. You can then use this saved information for documentation purposes, or to extend your data exploration and analysis.In addition to saving your work to MATLAB workspace variables, you can:

1. Save the session2. Generate an M‐file

44

Page 23: 10 Matlab Fitting

23

Plot of Linear Fit

This linear fit uses

every data point.

Notice the very

small slope; 30

40

50

60

70

y = f(x) is almost

independent of x.0 1 2 3 4 5 6 7 8 9 10

0

10

20

45

Bad Data

What about this point?

30

40

50

60

70Is it really a “good” data point?

What do you know about the data?

Is it monotonic?

0 1 2 3 4 5 6 7 8 9 100

10

20

46

Page 24: 10 Matlab Fitting

24

A linear fit ignoring one data point

Now the slope is greater d     f ll   h  

30

40

50

60

70 and seems to follow the data points pretty well.

Bad data point is ignored. 

But what if we "convicted" the wrong data point?

0 1 2 3 4 5 6 7 8 9 100

10

20g p

47

A linear fit ignoring one data point

30

40

50

60

70 Ignoring a different data point allows us to approximate the data pretty well with a second degree polynomial.

0 1 2 3 4 5 6 7 8 9 100

10

20

f(x) = -1.9726x2 + 18.2557x + 8.713248

Page 25: 10 Matlab Fitting

25

Common Fitting Functions

The linear function y = mx + b Its slope is m and its intercept is bIts slope is m and its intercept is b.

The power function y = bxm

x raised to some power mm does not need to be an integer or positiveno other terms – simpler than polynomial

The exponential function y = b(10)mxThe exponential function y  b(10)also written as  y = bemx

base (10 or e) raised to some power mx

In all 3, fitting involves estimating m and b !49

Plots tell which model to use

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

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.

50

Page 26: 10 Matlab Fitting

26

1- Examine the data near the origin.

☺The linear function can pass through the

Steps for Function Discovery

☺The linear function can pass through the origin only if b = 0.

☺The power function can pass through the origin but only if m > 0. (See Figure 1 for examples with b = 1.)

☺The exponential function can never pass through the origin (unless of course b = 0, which is a trivial case). (See Figure 2 for examples with b = 1.) .

51

clc;clear

x=linspace(0,4);

Examples of power functions 

3 5

4

b=1;

m=[-1,-.5,0,.5,1,2];

y1=b*x.^(m(1));

y2=b*x.^(m(2));

y3=b*x.^(m(3));

y4=b*x.^(m(4));1.5

2

2.5

3

3.5

m=2

m=1

m=0.5

y5=b*x.^(m(5));

y6=b*x.^(m(6));

plot(x,y1,'k.-',x,y2,'b.-',x,y3,'g.-',x,y4,'r.-',x,y5,'m.-',x,y6,'c.-')

axis([0 4 0 4])

gtext('m=2');gtext('m=1');gtext('m=0.5');gtext('m=0');

gtext('m=-0.5');gtext('m=-1');0 0.5 1 1.5 2 2.5 3 3.5 4

0

0.5

1m=0

m=-0.5

m=-1

Figure 1 52

Page 27: 10 Matlab Fitting

27

clc;clear

x=linspace(0,2);

Examples of exponential functions

3 5

4

b=1;

m=[-2,-1,0,1,2];

y1=b*exp(m(1).*x);

y2=b*exp(m(2).*x);

y3=b*exp(m(3).*x);

y4=b*exp(m(4).*x);1.5

2

2.5

3

3.5m=2

m=1

y5=b*exp(m(5).*x);

plot(x,y1,'r.-',x,y2,'b.-',x,y3,'g.-',x,y4,'m.-',x,y5,'c.-')

axis([0 2 0 4])

gtext('m=2');gtext('m=1');gtext('m=0');gtext('m=-1');gtext('m=-2');

0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 20

0.5

1

m=0

m=-1m=-2

Figure 2 53

2- Plot the data using rectilinear scales. If it forms a straight line, then it can be

Steps for Function Discovery

represented by the linear function and you are finished.

Otherwise, if you have data at x = 0, then

a. If y(0) = 0, try the power function.

b. If y(0) ≠ 0, try the exponential function.y( ) , y p

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

54

Page 28: 10 Matlab Fitting

28

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

Steps for Function Discovery

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.

55

Using Polyfit for Linear Curve Fit

p = polyfit(x,y,1)p is the vector of coefficients, [p1 p2].p1=m , p2=b

56

Page 29: 10 Matlab Fitting

29

Using Polyfit for Power Curve Fit

In this case:

Thus we can find the power function that fits the data by typing:

l fi (l ( ) l ( ) 1)p = polyfit(log(x),log(y),1)p is the vector of coefficients, [p1 p2].p1=m , p2=log(b)

57

Using Polyfit for Exponential Curve Fit

In this case:

Thus we can find the power function that fits the data by typing:

l fi ( l ( ) 1)p = polyfit(x,log(y),1)p is the vector of coefficients, [p1 p2].p1=m , p2=log(b)

58

Page 30: 10 Matlab Fitting

30

ExamplePlot and determine which curve fits best

x yDetermine the best 2.5 821

3 498

3.5 302

4 183

4.5 111

5 67

Determine the best fitting (linear, exponential, or power function) to describe the data. Plot the function on the same

5.5 41

6 25

7 9

8 3

9 1

function on the same plot with the data. Label and format the plots appropriately.

59

Programclc; close; clearx=[2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 7, 8, 9];y=[821 498 302 183 111 67 41 25 9 3 1];y=[821, 498, 302, 183, 111, 67, 41, 25, 9, 3, 1];plot(x,y,'kh'); xlabel('x'), ylabel('y');hold onp1=polyfit(x,y,1);p2=polyfit(log(x),log(y),1);p3=polyfit(x,log(y),1);x1=1:.1:10;y1=polyval(p1,x1);y2 polyval(p2 x1);y2=polyval(p2,x1);y3=polyval(p3,x1);plot(x1,y1,'g.:',exp(x1),exp(y2),'r.:',x1,exp(y3),'b.:')axis([1 10 -200 1200]);legend('Experimental Data','Line Fit.','Power Fit.','Exponential Fit.');

60

Page 31: 10 Matlab Fitting

31

1200Experimental DataLine Fit.Power Fit.

Resulte

400

600

800

1000y

Exponential Fit.

1 2 3 4 5 6 7 8 9 10-200

0

200

x61

Assessing Goodness of FitThe tough part of polynomial regression is knowing that the "fit" is a good one. Determining the quality of the fit requires experience, a sense of balance and some statistical summaries. 

One common goodness of fit involves a least‐squares approximation. This describes the distance of the entire set of data points from the fitted curve. The normalization of the data points from the fitted curve. The normalization of the residual errorminimizing the square of the sum of squares of all residual errors.The coefficient of determination (also referred to as the R2

value) for the fit indicates the percent of the variation in the data that is explained by the model. 

62

Page 32: 10 Matlab Fitting

32

Assessing Goodness of FitThis coefficient can be computed via the commands:

ypred = polyval(coeff,x); % predictions

dev = y - mean(y); % deviations - measure of spread

SST = sum(dev.^2); % total variation to be accounted for the fit

resid = y - ypred; % residuals - measure of mismatch

SSE = sum(resid.^2); % variation NOT accounted for the fit

normr = sqrt(SSE) % the 2-norm of the vector of the residuals for the fit

Rsq = 1 - SSE/SST; % R2 Error (percent of error explained)

The closer that Rsq is to 1, the more completely the fitted model "explains" the data.

63

ResidualsIt can be helpful to plot the model error samples directly—the residualsdirectly the residuals

For this would involve:

make another vector of model data that aligns with original data and subtract:

1 l fit( 1 ) % i i l ty1=polyfit(p1,x) ; %  original x vector

r1=y – y1; %  vector of model errors

plot(x, r1);    

64

Page 33: 10 Matlab Fitting

33

Residual in Line Fittx=[2.5 3 3.5 4 4.5 5 5.5 6 7 8 9];

y=[821,498,302,183,111,67,41,25,9,3,1];

2 3 4 5 6 7 8 9 10-500

0

500

1000p=polyfit(x,y,1);

x1=2:.1:10;

y1=polyval(p,x1);

y11=polyval(p,x);

r=y‐y11;

b l (2 1 1)

2 3 4 5 6 7 8 9 10

-500

0

500

subplot(2,1,1)

plot(x,y,'hr',x1,y1,'g‐');

subplot(2,1,2)

plot(x,r,'ob')

axis([2 10 ‐800 800]);65

Residual in Power Fittx=[2.5 3 3.5 4 4.5 5 5.5 6 7 8 9];

y=[821,498,302,183,111,67,41,25,9,3,1];

2 3 4 5 6 7 8 9 100

1000

2000

3000

4000

5000

6000p=polyfit(log(x),log(y),1);

x1=2:.1:10;

y1=polyval(p,log(x1));

y11=polyval(p,log(x));

r=y‐exp(y11);

b l (2 1 1)

2 3 4 5 6 7 8 9 10

-500

0

500

subplot(2,1,1)

plot(x,y,'hr',x1,exp(y1),'g‐');

subplot(2,1,2)

plot(x,r,'ob')

axis([2 10 ‐800 800]);66

Page 34: 10 Matlab Fitting

34

Residual in Exponential Fittx=[2.5 3 3.5 4 4.5 5 5.5 6 7 8 9];

y=[821,498,302,183,111,67,41,25,9,3,1];

2 3 4 5 6 7 8 9 100

500

1000

1500p=polyfit(x,log(y),1);

x1=2:.1:10;

y1=polyval(p, x1);

y11=polyval(p, x);

r=y‐exp(y11);

b l (2 1 1)

2 3 4 5 6 7 8 9 10

-500

0

500

subplot(2,1,1)

plot(x,y,'hr',x1,exp(y1),'g‐');

subplot(2,1,2)

plot(x,r,'ob')

axis([2 10 ‐800 800]);67

Exercises

Calculate the R2 error and Norm of the residual error for a 2nd order polynomial fit for the data in the previous example.

68

Page 35: 10 Matlab Fitting

35

Solution

x=[0,.5,1,1.5,2,2.5,3,3.5,4];y=[100,62,38,21,13,7,4,2,3];

l fit( 2)60

80

100

p=polyfit(x,y,2);x1=0:.1:4;y1 = polyval(p,x1); dev = y-mean(y); SST = sum(dev.^2)y11= polyval(p,x);resid = y - y11; SSE = sum(resid.^2)normr = sqrt(SSE); % residual normRsq = 1 - SSE/SST % R^2 Error

0 0.5 1 1.5 2 2.5 3 3.5 4-20

0

20

40

60

10

Rsq 1 SSE/SST % R 2 Error subplot(2,1,1)plot(x,y,'ro',x1,y1,'b-')subplot(2,1,2)plot(x,resid,'hr')

0 0.5 1 1.5 2 2.5 3 3.5 4-5

0

5 normr =

12.1376

Rsq =

0.9837

69

Linear Modeling with Non‐polynomial TermsFit the data in x and y with the following equation: xx xeaeaxay −− ++= 32

01

Perform the following:

x = [0, 0.3, 0.8, 1.1, 1.6, 2.3]';y = [0.6, 0.67, 1.01, 1.35, 1.47, 1.25]';

B [ ( i ( )) ( ) * ( ) ]

Create variables x and y as column vectors – use the transpose operator ( ' ) to get the correct dimensions for the ( \ ) operation.

321

B = [ ones(size(x)) exp(-x) x.*exp(-x) ];Create a matrix where each row has the terms of your equation evaluated at a value of x. This is your “systems of equations.”

[ 1 exp(0) 0*exp(0)

1 exp(-0.3) 0.3*exp(-0.3)

1 exp(-0.8) 0.8*exp(-0.8)

1 exp(-1.1) 1.1*exp(-1.1)…]70

Page 36: 10 Matlab Fitting

36

continued…

B\ U th l ft di i i ( \ ) t t t ll

Linear Modeling with Non‐polynomial Terms

a = B\yxx = [0:0.1:2.5]';yy = a(1) .* ones(size(xx)) + a(2).*exp(-xx) + a(3).* xx.*exp(-xx);

plot(X,yfit,'-',x,y,'o'), grid on

• Use the left division ( \ ) operator to tell MATLAB to solve the system of equations.

• Use the coefficients to evaluate the fit, then plot it.

1.5

Try It!0 0.5 1 1.5 2 2.50.5

1

71