Main Content

fittype

Fit type for curve and surface fitting

描述

example

aFittype= fittype(libraryModelName)creates thefittypeobjectaFittypefor the model specified bylibraryModelName.

aFittype= fittype(expression)creates a fit type for the model specified by the MATLAB®expression.

example

aFittype= fittype(expression,Name,Value)constructs the fit type with additional options specified by one or moreName,Valuepair arguments.

example

aFittype= fittype(linearModelTerms)creates a fit type for a custom linear model with terms specified the expressions inlinearModelTerms.

example

aFittype= fittype(linearModelTerms,Name,Value)constructs the fit type with additional options specified by one or moreName,Valuepair arguments.

example

aFittype= fittype(anonymousFunction)creates a fit type for the model specified byanonymousFunction.

example

aFittype= fittype(anonymousFunction,Name,Value)constructs the fit type with additional options specified by one or moreName,Valuepair arguments.

Examples

collapse all

Construct fit types by specifying library model names.

Construct afittypeobject for the cubic polynomial library model.

f = fittype('poly3')
f = Linear model Poly3: f(p1,p2,p3,p4,x) = p1*x^3 + p2*x^2 + p3*x + p4

Construct a fit type for the library modelrat33(a rational model of the third degree for both the numerator and denominator).

f = fittype('rat33')
f = General model Rat33: f(p1,p2,p3,p4,q1,q2,q3,x) = (p1*x^3 + p2*x^2 + p3*x + p4) / (x^3 + q1*x^2 + q2*x + q3)

For a list of library model names, seelibraryModelName.

Construct fit types for custom nonlinear models, designating problem-dependent parameters and independent variables.

Construct a fit type for a custom nonlinear model, designatingnas a problem-dependent parameter anduas the independent variable.

g = fittype('a*u+b*exp(n*u)',...'problem','n',...'independent','u')
g = General model: g(a,b,n,u) = a*u+b*exp(n*u)

Construct a fit type for a custom nonlinear model, designatingtimeas the independent variable.

g = fittype('a*time^2+b*time+c','independent','time','dependent','height')
g = General model: g(a,b,c,time) = a*time^2+b*time+c

Construct a fit type for a logarithmic fit to some data, use the fit type to create a fit, and plot the fit.

x = linspace(1,100); y = 5 + 7*log(x); myfittype = fittype('a + b*log(x)',...'dependent',{'y'},'independent',{'x'},...'coefficients',{'a','b'})
myfittype = General model: myfittype(a,b,x) = a + b*log(x)
myfit = fit(x',y',myfittype)
Warning: Start point not provided, choosing random start point.
myfit = General model: myfit(x) = a + b*log(x) Coefficients (with 95% confidence bounds): a = 5 (5, 5) b = 7 (7, 7)
plot(myfit,x,y)

Figure contains an axes object. The axes object contains 2 objects of type line. These objects represent data, fitted curve.

You can specify any MATLAB command and therefore any.mfile.

To use a linear fitting algorithm, specify a cell array of terms.

Identify the linear model terms you need to input tofittype:a*x + b*sin(x) + c. The model is linear ina,bandc. It has three termsx,sin(x)and1(becausec=c*1). To specify this model you use this cell array of terms:LinearModelTerms = {'x','sin(x)','1'}.

Use the cell array of linear model terms as the input tofittype.

ft = fittype({'x','sin(x)','1'})
ft = Linear model: ft(a,b,c,x) = a*x + b*sin(x) + c

创造e a linear model fit type fora*cos(x) + b.

ft2 = fittype({'cos(x)','1'})
ft2 = Linear model: ft2(a,b,x) = a*cos(x) + b

创造e the fit type again and specify coefficient names.

ft3 = fittype({'cos(x)','1'},'coefficients',{'a1','a2'})
ft3 = Linear model: ft3(a1,a2,x) = a1*cos(x) + a2

Define a function in a file and use it to create a fit type and fit a curve.

Define a function in a MATLAB file.

functiony = piecewiseLine(x,a,b,c,d,k)% PIECEWISELINE A line made of two pieces% that is not continuous.y = zeros(size(x));% This example includes a for-loop and if statement% purely for example purposes.fori = 1:length(x)ifx(i) < k, y(i) = a + b.* x(i);elsey(i) = c + d.* x(i);endendend

Save the file.

Define some data, create a fit type specifying the functionpiecewiseLine, create a fit using the fit typeft, and plot the results.

x = [0.81;0.91;0.13;0.91;0.63;0.098;0.28;0.55;...0.96;0.96;0.16;0.97;0.96]; y = [0.17;0.12;0.16;0.0035;0.37;0.082;0.34;0.56;...0.15;-0.046;0.17;-0.091;-0.071]; ft = fittype('piecewiseLine( x, a, b, c, d, k )') f = fit( x, y, ft,'StartPoint', [1, 0, 1, 0, 0.5] ) plot( f, x, y )

创造e a fit type using an anonymous function.

g = fittype( @(a, b, c, x) a*x.^2+b*x+c )

创造e a fit type using an anonymous function and specify independent and dependent parameters.

g = fittype( @(a, b, c, d, x, y) a*x.^2+b*x+c*exp(...-(y-d).^2 ),'independent', {'x','y'},...'dependent','z');

创造e a fit type for a surface using an anonymous function and specify independent and dependent parameters, and problem parameters that you will specify later when you callfit.

g = fittype( @(a,b,c,d,x,y) a*x.^2+b*x+c*exp( -(y-d).^2 ),...'problem', {'c','d'},'independent', {'x','y'},...'dependent','z');

Use an anonymous function to pass workspace data into thefittypeandfitfunctions.

创造e and plot an S-shaped curve. In later steps, you stretch and move this curve to fit to some data.

% Breakpoints.xs = (0:0.1:1).';% Height of curve at breakpoints.ys = [0; 0; 0.04; 0.1; 0.2; 0.5; 0.8; 0.9; 0.96; 1; 1];% Plot S-shaped curve.xi = linspace( 0, 1, 241 ); plot( xi, interp1( xs, ys, xi,'pchip'),'LineWidth', 2 ) holdonplot( xs, ys,'o','MarkerFaceColor','r') holdofftitleS-curve

创造e a fit type using an anonymous function, taking the values from the workspace for the curve breakpoints (xs) and the height of the curve at the breakpoints (ys). Coefficients areb(base) andh(height).

ft = fittype( @(b, h, x) interp1( xs, b+h*ys, x,'pchip') )

Plot thefittypespecifying example coefficients of baseb=1.1and heighth=-0.8.

plot( xi, ft( 1.1, -0.8, xi ),'LineWidth', 2 ) title'Fittype with b=1.1 and h=-0.8'

Load and fit some data, using the fit typeftcreated using workspace values.

% Load some dataxdata = [0.012;0.054;0.13;0.16;0.31;0.34;0.47;0.53;0.53;...0.57;0.78;0.79;0.93]; ydata = [0.78;0.87;1;1.1;0.96;0.88;0.56;0.5;0.5;0.5;0.63;...0.62;0.39];% Fit the curve to the dataf = fit( xdata, ydata, ft,'Start', [0, 1] )% Plot fitplot( f, xdata, ydata ) title'Fitted S-curve'

This example shows the differences between using anonymous functions with problem parameters and workspace variable values.

Load data, create a fit type for a curve using an anonymous function with problem parameters, and callfitspecifying the problem parameters.

% Load some data.xdata = [0.098;0.13;0.16;0.28;0.55;0.63;0.81;0.91;0.91;...0.96;0.96;0.96;0.97]; ydata = [0.52;0.53;0.53;0.48;0.33;0.36;0.39;0.28;0.28;...0.21;0.21;0.21;0.2];% Create a fittype that has a problem parameter.g = fittype( @(a,b,c,x) a*x.^2+b*x+c,'problem','c')% Examine coefficients. Observe c is not a coefficient.coeffnames( g )% Examine arguments. Observe that c is an argument.argnames( g )% Call fit and specify the value of c.f1 = fit( xdata, ydata, g,'problem', 0,'StartPoint', [1, 2] )% Note: Specify start points in the calls to fit to% avoid warning messages about random start points% and to ensure repeatability of results.% Call fit again and specify a different value of c,% to get a new fit.f2 = fit( xdata, ydata, g,'problem', 1,'start', [1, 2] )% Plot results. Observe the specified c constants% do not make a good fit.plot( f1, xdata, ydata ) holdonplot( f2,'b') holdoff

Modify the previous example to create the same fits using workspace values for variables, instead of using problem parameters. Using the same data, create a fit type for a curve using an anonymous function with a workspace value for variablec:

% Remove c from the argument list.tryg = fittype( @(a,b,x) a*x.^2+b*x+c )catche disp( e.message )end% Observe error because now c is undefined.% Define c and create fittype:c = 0; g1 = fittype( @(a,b,x) a*x.^2+b*x+c )% Call fit (now no need to specify problem parameter).f1 = fit( xdata, ydata, g1,'StartPoint', [1, 2] )% Note that this f1 is the same as the f1 above.% To change the value of c, recreate the fittype.c = 1; g2 = fittype( @(a,b,x) a*x.^2+b*x+c )% uses c = 1f2 = fit( xdata, ydata, g2,'StartPoint', [1, 2] )% Note that this f2 is the same as the f2 above.% Plot resultsplot( f1, xdata, ydata ) holdonplot( f2,'b') holdoff

Input Arguments

collapse all

Library model to fit, specified as a character vector or string scalar. This table shows some common examples.

Library Model Name

描述

'poly1'

Linear polynomial curve

'poly11'

Linear polynomial surface

'poly2'

Quadratic polynomial curve

'linearinterp'

Piecewise linear interpolation

'cubicinterp'

Piecewise cubic interpolation

'smoothingspline'

Smoothing spline (curve)

'lowess'

Local linear regression (surface)

For a list of library model names, seeModel Names and Equations.

Example:'poly2'

Data Types:char|string

Model to fit, specified as a character vector or string scalar. You can specify any MATLAB command and therefore any.mfile. SeeFit a Curve Defined by a File.

Data Types:char|string

Model to fit, specified as a cell array of character vectors or a string array. Specify the model terms by the expressions in the character vectors or string scalars. Do not include coefficients in the expressions for the terms. SeeLinear Model Terms.

Data Types:cell

Model to fit, specified as an anonymous function. For details, seeInput Order for Anonymous Functions.

Data Types:char

Name-Value Arguments

Specify optional comma-separated pairs ofName,Valuearguments.Nameis the argument name andValueis the corresponding value.Namemust appear inside quotes. You can specify several name and value pair arguments in any order asName1,Value1,...,NameN,ValueN.

Example:'coefficients',{'a1','a2'}

Coefficient names, specified as the comma-separated pair consisting of'coefficients'一个特征向量,字符串标量,单元阵列of character vectors, or string array. You can use multicharacter symbol names. You cannot use these names:i,j,pi,inf,nan,eps.

Data Types:char|string|cell

Dependent (response) variable name, specified as the comma-separated pair consisting of'dependent'and a character vector or string scalar. If you do not specify the dependent variable, the function assumesyis the dependent variable.

Data Types:char|string

Independent (response) variable names, specified as the comma-separated pair consisting of'independent'一个特征向量,字符串标量,单元阵列of character vectors, or string array. If you do not specify the independent variable, the function assumesxis the independent variable.

Data Types:char|string|cell

Fit options, specified as the comma-separated pair consisting of'options'and the name of afitoptionsobject.

Problem-dependent (fixed) parameter names, specified as the comma-separated pair consisting of'problem'一个特征向量,字符串标量,单元阵列of character vectors, or string array with one element per problem dependent constant.

Data Types:char|string|cell

Output Arguments

collapse all

Model to fit, returned as afittype. Afittypeencapsulates information describing a model. To create a fit, you need data, afittype, and (optionally)fitoptionsand an exclusion rule. You can use afittypeas an input to thefitfunction.

More About

collapse all

Dependent and Independent Variables

How do I decide which variables are dependent and independent?

To determine dependent and independent variables and coefficients, consider this equation:

y = f ( x ) = a + ( b * x ) + ( c * x 2 ) .

  • yis the dependent variable.

  • xis the independent variable.

  • a,b, andcare the coefficients.

The'independent'variable is what you control. The'dependent'variable is what you measure, i.e., it depends on the independent variable. The'coefficients'are the parameters that the fitting algorithm estimates.

For example, if you have census data, then the year is the independent variable because it does not depend on anything. Population is the dependent variable, because its value depends on the year in which the census is taken. If a parameter like growth rate is part of the model, so the fitting algorithm estimates it, then the parameter is one of the'coefficients'.

Thefittypefunction determines input arguments by searching the fit type expression input for variable names.fittypeassumesxis the independent variable,yis the dependent variable, and all other variables are coefficients of the model.xis used if no variable exists.

Input Order for Anonymous Functions

If the fit type expression input is an anonymous function, then the order of inputs must be correct. The input order enables thefittypefunction to determine which inputs are coefficients to estimate, problem-dependent parameters, and independent variables.

The order of the input arguments to the anonymous function must be:

fcn = @(coefficients,problemparameters,x,y) expression
You need at least one coefficient. The problem parameters andyare optional. The last arguments,xandy, represent the independent variables: justxfor curves, butxandyfor surfaces. If you don't want to usexand/oryto name the independent variables, then specify different names using the'independent'argument name-value pair. However, whatever name or names you choose, these arguments must be the last arguments to the anonymous function.

Anonymous functions make it easier to pass other data into thefittypeandfitfunctions.

  1. 创造e a fit type using an anonymous function and a variable value (c) from the workspace.

    c = 1; g = fittype( @(a, b, x) a*x.^2+b*x+c )
  2. Thefittypefunction can use the variable values in your workspace when you create the fit type. To pass in new data from the workspace, recreate the fit type, e.g.,

    c = 5% Change value of c.g = fittype( @(a, b, x) a*x.^2+b*x+c )
  3. Here, the value ofcis fixed when you create the fit type. To specify the value ofcat the time you callfit, you can use problem parameters. For example, make a fit withc = 2and then a new fit withc = 3.

    g = fittype( @(a,b,x,c) a*x.^2+b*x+c,'problem','c') f1 = fit( xdata, ydata, g,'problem', 2 ) f2 = fit( xdata, ydata, g,'problem', 3 )

Linear Model Terms

How do I define linear model terms?

To use a linear fitting algorithm, specifylinearModelTermsas a cell array or string array of terms. For example:

afittype = fittype({expr1,...,exprn})
Specify the model terms by the expressions in the character vectorsexpr2,...,exprn. Do not include coefficients in the expressions for the terms. If there is a constant term, use'1'as the corresponding expression in the cell array.

To specify a linear model of the following form:

coeff1 * term1 + coeff2 * term2 + coeff3 * term3 +...
where no coefficient appears within any ofterm1,term2, etc., use a cell array or string array where each term, without coefficients, is specified in a cell or element ofexpr, as follows:
LinearModelTerms = {'term1','term2','term3',...}

For example, the model

a*x + b*sin(x) + c
is linear ina,b, andc. It has three termsx,sin(x)and1(because c=c*1) and thereforeexpris:
LinearModelTerms = {'x','sin(x)','1'}

In the Curve Fitting app, see theLinear Fittingmodel type.

Algorithms

If the fit type expression input is a character vector, string scalar, or anonymous function, then the toolbox uses a nonlinear fitting algorithm to fit the model to data.

If the fit type expression input is a cell array or string array of terms, then the toolbox uses a linear fitting algorithm to fit the model to data.

Introduced before R2006a