分类: C/C++
2012-05-08 13:21:44
yy = zzz700createFit(x, y, n)
.......................
matlab非线性回归
x = [0, 1, 3, 5, 10, 24], y = [1, 1.4, 4.5, 3.5, 2.1, 1.3],
函数可能是y=a*x^3+b*x^2+c*x^1+d。
以下代码在7.1版以上均可运行。
close all
clear,clc
x = [0, 1, 3, 5, 10, 24];
y = [1, 1.4, 4.5, 3.5, 2.1, 1.3];
xData = x';
yData = y';
% Set up fittype and options.
ft = fittype( 'a*x^3+b*x^2+c*x^1+d', 'independent', 'x', 'dependent', 'y' );
opts = fitoptions( ft );
opts.Display = 'Off';
opts.StartPoint = [0.795199901137063 0.186872604554379 0.489764395788231 0.445586200710899];
% Fit model to data.
[fitresult, gof] = fit( xData, yData, ft, opts )
% Plot fit with data.
figure( 'Name', '拟合图' );
h_ = plot( fitresult, x, y, '* '); % 拟合图 原始数据
legend off; % turn off legend from plot method call
set(h_(2),'Color',[1 0 0],...
'LineStyle','-', 'LineWidth',2,...
'Marker','none', 'MarkerSize',6);
h = legend('原始数据','拟合曲线',2,'Location','Best');
set(h,'Interpreter','none')
title('拟合图 原始数据')
% Label axes
xlabel( 'x' );
ylabel( 'y' );
grid on
fitresult =
rmse: 0.8917
......................
x=[3.23E+04
5.71E+04
1.49E+05
1.61E+05
1.79E+05
2.02E+05
2.11E+05
2.45E+05
2.68E+05
4.14E+05
5.11E+05
7.79E+05
7.22E+05
1.28E+06
1.01E+06
1.34E+06
1.60E+06
2.01E+06
1.02E+07
1.02E+07
1.46E+07
4.63E+07
1.61E+08
1.42E+09
1.22E+09
3.77E+09];
y=[151
140
140
130
130
130
110
120
120
120
110
100
90.5
90.5
80.2
101
89.3
81.4
80.2
70
76.1
70.8
74.4
71.1
60.9
65.8];
xData = x;
yData = y;
% Set up fittype and options.
ft = fittype( '(230-a)*exp(-((x-1/4)/b)^c)+a', 'independent', 'x', 'dependent', 'y' );
opts = fitoptions( ft );
opts.Display = 'Off';
opts.Lower = [40 10000 0];
opts.StartPoint = [0.278498218867048 0.546881519204984 0.957506835434298];
opts.Upper = [100 1000000000 10];
% Fit model to data.
[fitresult, gof] = fit( xData, yData, ft, opts )
% Plot fit with data.
figure( 'Name', '拟合图 ' );
h = plot( fitresult, xData, yData , '* ');
set(h(2),'Color',[1 0 0],...
'LineStyle','-', 'LineWidth',2,...
'Marker','none', 'MarkerSize',6);
h = legend('原始数据','拟合曲线',2,'Location','NorthEast');
title('拟合图 原始数据')
% Label axes
xlabel( 'x' );
ylabel( 'y' );
grid on
fitresult =
General model:
fitresult(x) = (230-a)*exp(-((x-1/4)/b)^c)+a
Coefficients (with 95% confidence bounds):
a = 69.11 (63.03, 75.19)
b = 1.528e+005 (1.036e+005, 2.021e+005)
c = 0.3109 (0.2448, 0.377)
gof =
sse: 1.1832e+003
rsquare: 0.9337
dfe: 23
adjrsquare: 0.9279
rmse: 7.1724
....................
fittype -Fit type for curve and surface fittingSyntax
ffun = fittype(libname)
ffun = fittype(expr)
ffun = fittype({expr1,...,exprn})
ffun = fittype(expr, Name, Value,...)
ffun= fittype({expr1,...,exprn}, Name, Value,...)
ffun = fittype(libname) constructsthe fittype object ffun forthe library model specified by libname. Displaylibrary model names using the cflibhelp function.See Using Library Models.
ffun = fittype(expr) constructs ffun forthe custom model specified by the expression expr.The expression can be a string, cell array, or anonymous function.See Using Custom Models.
ffun = fittype({expr1,...,exprn}) constructsa custom linear model with terms specified by the cell array of expressionsin the strings expr1, expr2,... , exprn. See Using Linear Models.
ffun = fittype(expr, Name, Value,...) or ffun= fittype({expr1,...,exprn}, Name, Value,...) constructsthe fittype using specified name-value pair argumentsspecifying values other than the default values. For supported names-valuepair arguments, see Input Arguments.
Using Library Modelsffun = fittype(libname) constructs the fittype forthe library model libname. Choices for libname includeany of the names of library models described in cflibhelp. The following table showssome common examples.
libname | Description |
---|---|
'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) |
ffun = fittype(expr) constructs a custommodel fittype for the MATLAB expression containedin the string, cell array, or anonymous function expr.
The fittype automatically determines inputarguments by searching expr for variable names.The fittype assumes x is theindependent variable, y is the dependent variable,and all other variables are coefficients of the model. x isused if no variable exists. See Dependent and Independent Variables.
All coefficients must be scalars. You cannot use the followingcoefficient names in the expression string expr: i, j, pi, inf, nan,and eps.
If expr is a string or anonymous function,then the toolbox uses a nonlinear fitting algorithm to fit the modelto data (see Using Anonymous Functions).To use a linear fitting algorithm, use a cell array of terms (see Using Linear Models).
Using Anonymous FunctionsIf expr is an anonymous function, then theorder of inputs must be correct. The input order enables the fittype classto determine which inputs are coefficients to estimate, problem-dependentparameters and independent variables. The order of the input argumentsto the anonymous function must be:
EXPR = @(coefficients, problemparameters, x, y) expressionYou need at least one coefficient. The problem parametersand y are optional. The last arguments, x and y,represent the independent variables: just x forcurves, but x and y for surfaces.If you don't want to use x and/or y asthe names of the independent variables, then specify different namesusing the 'independent' argument name-value pair.However, whatever name or names you choose, these arguments must bethe last arguments to the anonymous function.
Anonymous functions make it easier to pass other data into the fittype and fit functions.For example, to create a fittype using an anonymousfunction and a variable value (c) from the workspace:
c = 1;The fittype canuse the variable values in your workspace at the time you create the fittype.To pass in new data from the workspace, create the fittype again,e.g.,
c=5 % Change value of cIn this case the value of c isfixed when you create the fittype. To specify thevalue of c at the time you call fit,you can use problem parameters. For example, to make a fit with c= 2 and then a new fit with c = 3:
g = fittype( @(a,b,x) a*x.^2+b*x+c, 'problem', 'c' )See Examples.
Using Linear ModelsTo use a linear fitting algorithm, specify expr asa cell array of terms, as follows: ffun = fittype({expr1,...,exprn}).Specify the model terms by the expressions in the strings expr1, expr2,... , exprn. Do not include coefficients in theexpressions for the terms. If there is a constant term, use '1' asthe 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 of term1, term2,etc.), use a cell array where each term, without coefficients, isspecified in a cell of expr, as follows:
EXPR = {'term1', 'term2', 'term3', ... }For example, the model
a*x + b*sin(x) + cislinear in a, b and c.It has three terms x, sin(x) and 1 (becausec=c*1) and so expr is
EXPR = {'x','sin(x)','1'}To determine what are dependent and independent variables andcoefficients, consider this equation:
y is the dependent variable.
x is the independent variable.
a, b, and c arethe 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' arethe parameters that the fitting algorithm estimates.
For example, if you have census data, then the year is the independentvariable because it does not depend on anything. Population is thedependent variable, because its value depends on the year in whichthe census is taken. If a parameter like growth rate is part of themodel, if the fitting algorithm estimates it, then it is one of the 'coefficients'.
See Examples for how to specifyan independent variable and coefficient names.
Input Argumentslibname | Library model name. Display choices using the cflibhelp function. |
expr | Custom model expression. The expression can be a string, cellarray, or anonymous function. You can specify any MATLAB command and therefore any .m file. |
Optional comma-separated pairs of Name,Value arguments,where Name is the argumentname and Value is the correspondingvalue. Name must appearinside single quotes ('').You can specify several name-value pairarguments in any order as Name1,Value1,…,NameN,ValueN.
coefficients | The coefficient names. Use a cell array for multiple names.You can use multicharacter symbol names. You cannot use the followingnames: i, j, pi, inf, nan, eps. |
dependent | The dependent (response) variable name. Default: y |
independent | The independent (predictor) variable name. Default: x |
options | The default fit options for the object. |
problem | The problem-dependent (fixed) parameter names. Use a cell arrayfor multiple names. Default: None |
ffun | fittype object. You can use a fittype objectas an input to the fit function. |
Construct a fittype object for the rat33 librarymodel:
f = fittype('rat33')Construct a fittype object for a custom nonlinearmodel, designating n as a problem-dependent parameterand u as the independent variable:
g = fittype('a*u+b*exp(n*u)',...Construct a fittype object for a custom linearmodel, specifying the coefficient names:
h = fittype({'cos(x)','1'},'coefficients',{'a1','a2'})Fit a curve defined by a file:
Define a function in a MATLAB file:
function y = piecewiseLine( x, a, b, c, d, k )Define some data, create a fittype specifyingthe function piecewiseLine, create a fit usingthe fittype, and plot the results:
x = [0.81;0.91;0.13;0.91;0.63;0.098;0.28;0.55;...Create a fittype using an anonymous function:
g = fittype( @(a, b, c, x) a*x.^2+b*x+c )Create a fittype for a surface using an anonymousfunction and specifying independent and dependent parameters:
g = fittype( @(a, b, c, d, x, y) a*x.^2+b*x+c*exp...Create a fittype for a surface using an anonymousfunction and specifying independent and dependent parameters, andproblem parameters that you will specify later when you call fit:
g = fittype( @(a,b,c,d,x,y) a*x.^2+b*x+c*exp( -(y-d).^2 ), ...Use an anonymous function to pass workspace data into the fittype and fit functions.
Create and plot an S-shaped curve. In later stepsyou will stretch and move this curve to fit to some data.
% BreakpointsCreate a fittype using an anonymousfunction, taking the values from the workspace for the curve breakpoints(xs) and the height of the curve at the breakpoints(ys). Coefficients are b (base)and h (height).
ft = fittype( @(b, h, x) interp1( xs, b+h*ys, x, 'pchip' ) )Plot the fittype specifying examplecoefficients of base b=1.1 and height h=-0.8.
plot( xi, ft( 1.1, -0.8, xi ), 'LineWidth', 2 )Load and fit some data, using the fittypeft createdusing workspace values:
% Load some dataThe following example demonstrates the differences between usinganonymous functions with problem parameters and workspace variablevalues.
Load data, create a fittype fora curve using an anonymous function with problem parameters, and call fit specifyingthe problem parameters:
% Load some random data:Modify the example above to create the same fits usingworkspace values for variables, instead of using problem parameters.Using the same data, create a fittype for a curveusing an anonymous function with a workspace value for variable c:
% Remove c from the argument list:Here are other examples using fittype:
g = fittype('a*x^2+b*x+c')cfit | cflibhelp | fit | fitoptions | sfit
...................
formula-Formula ofcfit,sfit, orfittypeobjectSyntax
formula(fun)
formula(fun) returns theformula of the cfit, sfit, or fittype object fun asa character array.
Examplesf = fittype('weibull');coeffnames | coeffvalues | fittype | numcoeffs | probnames
......................
set-Assign values in fit options structureSyntax
set(options)
s = set(options)
set(options,fld1,val1,fld2,val2,...)
set(options,flds,vals)
set(options) displays allproperty names of the fit options structure options.If a property has a finite list of possible string values, these valuesare also displayed.
s = set(options) returnsa structure s with the same property names as options.If a property has a finite list of possible string values, the valueof the property in s is a cell array containingthe possible string values. If a property does not have a finite listof possible string values, the value of the property in s isan empty cell array.
set(options,fld1,val1,fld2,val2,...) setsthe properties specified by the strings fld1, fld2,... to the values val1, val2,..., respectively.
set(options,flds,vals) setsthe properties specified by the cell array of strings flds tothe corresponding values in the cell array vals.
ExamplesCreate a custom nonlinear model, and create a default fit optionsstructure for the model:
f = fittype('a*x^2+b*exp(n*c*x)','problem','n');Set the Robust and Normalize propertiesof the fit options structure using property name/value pairs:
set(options,'Robust','LAR','Normalize','On')Set the Display, Lower,and Algorithm properties of the fit options structureusing cell arrays of property names/values:
set(opts,{'Disp','Low','Alg'},...
.....................
get -Get fit options structure property names and valuesSyntax
get(options)
s = get(options)
value = get(options,fld)
get(options) displays allproperty names and values of the fit options structure options.
s = get(options) returnsa copy of the fit options structure options asthe structure s.
value = get(options,fld) returnsthe value of the property fld of the fitoptions structure options. fld canbe a cell array of strings, in which case value isalso a cell array.
Examplesoptions = fitoptions('fourier1');Property values can also be referenced and assigned using thedot notation. For example:
options.MaxIter
.......................
numargs-
Number of input arguments ofcfit,sfit, orfittype
objectSyntaxnargs = numargs(fun)
nargs = numargs(fun) returnsthe number of input arguments nargs of the cfit, sfit,or fittype object fun.
Examplesf = fittype('a*x^2+b*exp(n*x)');
.........................
numcoeffs
-Number of coefficients ofcfit,sfit, orfittype
objectSyntaxncoeffs = numcoeffs(fun)
ncoeffs = numcoeffs(fun) returnsthe number of coefficients ncoeffs of the cfit, sfit,or fittype object fun.
Examplesf = fittype('a*x^2+b*exp(n*x)');coeffnames | fittype | formula
...............
probnames
-Problem-dependent parameter names ofcfit,sfit, orfittypeobject
Syntaxpnames = probnames(fun)
pnames = probnames(fun) returnsthe names of the problem-dependent (fixed) parameters of the cfit, sfit,or fittype object fun as acell array of strings.
Examplesf = fittype('(x-a)^n + b','problem',{'a','b'});coeffnames | fittype | probvalues
......
type-Name ofcfit,sfit, orfittypeobjectSyntax
name = type(fun)
name = type(fun) returns the custom orlibrary name name of the cfit, sfit,or fittype object fun as a characterarray.
Examplesf = fittype('a*x^2+b*exp(n*x)');