Chinaunix首页 | 论坛 | 博客
  • 博客访问: 32690
  • 博文数量: 16
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 10
  • 用 户 组: 普通用户
  • 注册时间: 2015-05-16 19:44
个人简介

在不断学习新事物

文章分类
文章存档

2015年(16)

我的朋友
最近访客

分类: C/C++

2015-05-16 20:15:54

现想编个函数,
该函数的输入为x,y,n,
其中x为原始点的x坐标的一维数组,y为原始点的y坐标的一维数组,n为傅里叶函数的阶数,
输出为拟合后的点的y坐标

 


以下代码在7.1版以上均可运行。

将以下代码保存为M文件:

function yy = zzz700createFit(x, y, n)

xData = x(:);
yData = y(:);

% Set up fittype and options.
ft = fittype( ['fourier',num2str(n)'] );
opts = fitoptions( ft );
opts.Display = 'Off';

% Fit model to data.
[fitresult, gof] = fit( xData, yData, ft, opts );

%  拟合后的点的y坐标
yy = fitresult(xData);


在命令窗口输入:

% 输入x,y,n
x = 0:0.1:2*pi;  
y = rand(length(x),1);
n = 6;

% 输出为拟合后的点的y坐标

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 =

     General model:
     fitresult(x) = a*x^3+b*x^2+c*x^1+d
     Coefficients (with 95% confidence bounds):
       a =    0.005205  (-0.003479, 0.01389)
       b =     -0.1843  (-0.4727, 0.1041)
       c =       1.447  (-0.6652, 3.56)
       d =      0.7761  (-2.473, 4.025)

gof =

           sse: 1.5902
       rsquare: 0.8381
           dfe: 2
    adjrsquare: 0.5952

          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,...)

Description

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 Models

ffun = 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)

Using Custom Models

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 Functions

If 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) expression

You 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;
g = fittype( @(a, b, x) a*x.^2+b*x+c )

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 c
g = fittype( @(a, b, x) a*x.^2+b*x+c )

In 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' )
f1 = fit( xdata, ydata, g, 'problem', 2 )
f2 = fit( xdata, ydata, g, 'problem', 3 )

See Examples.

Using Linear Models

To 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) + c

islinear 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'}
Dependent and Independent Variables

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 Arguments

libname

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.

Name-Value Pair Arguments

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

Output Arguments

ffun

fittype object. You can use a fittype objectas an input to the fit function.

Examples

Construct a fittype object for the rat33 librarymodel:

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)
 

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)',...
'problem','n',...
'independent','u')
g =
General model:
g(a,b,n,u) = 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'})
h =
Linear model:
h(a1,a2,x) = a1*cos(x) + a2
 

Fit a curve defined by a file:

  1. Define a function in a MATLAB file:

    function y = 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 demonstration purposes.
    for i = 1:length( x )
    if x(i) < k,
    y(i) = a + b.* x(i);
    else
    y(i) = c + d.* x(i);
    end
    end
    end
  2. 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;...
    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 )
 

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...
( -(y-d).^2 ), 'independent', {'x', 'y'},...
'dependent', 'z' );
 

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 ), ...
'problem', {'c','d'}, 'independent', {'x', 'y'}, ...
'dependent', 'z' );
 

Use an anonymous function to pass workspace data into the fittype and fit functions.

  1. Create and plot an S-shaped curve. In later stepsyou will 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 )
    hold on
    plot( xs, ys, 'o', 'MarkerFaceColor', 'r' )
    hold off
    title S-curve
  2. Create 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' ) )
  3. 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 )
    title 'Fittype with b=1.1 and h=-0.8'
  4. Load and fit some data, using the fittypeft createdusing workspace values:

    % Load some data
    xdata = [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 data
    f = fit( xdata, ydata, ft, 'Start', [0, 1] )
    % Plot fit
    plot( f, xdata, ydata )
    title 'Fitted S-curve'
 

The following example demonstrates the differences between usinganonymous functions with problem parameters and workspace variablevalues.

  1. Load data, create a fittype fora curve using an anonymous function with problem parameters, and call fit specifyingthe problem parameters:

    % Load some random 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, 'start', [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. Note example specified c constants
    % do not make a good fit.
    plot( f1, xdata, ydata )
    hold on
    plot( f2, 'b' )
    hold off
  2. 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:
    try
    g = fittype( @(a,b,x) a*x.^2+b*x+c )
    catch e
    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, 'start', [1, 2] )
    % Note that this f1 is the same as the f1 above.
    % To change the value of c, create the fittype again:
    c = 1;
    g2 = fittype( @(a,b,x) a*x.^2+b*x+c ) % uses c = 1
    f2 = fit( xdata, ydata, g2, 'start', [1, 2] )
    % Note that this f2 is the same as the f2 above.
    % Plot results
    plot( f1, xdata, ydata )
    hold on
    plot( f2, 'b' )
    hold off
 

Here are other examples using fittype:

g = fittype('a*x^2+b*x+c')
g = fittype('a*x^2+b*x+c','coeff',{'a','b','c'})
g = fittype('a*time^2+b*time+c','indep','time')
g = fittype('a*time^2+b*time+c','indep','time','depen','height')
g = fittype('a*x+n*b','problem','n')
g = fittype({'cos(x)','1'}) % linear
g = fittype({'cos(x)','1'}, 'coefficients', {'a','b'}) % linear See Also

cfit | cflibhelp | fit | fitoptions | sfit

 

 

 ...................

 

formula-Formula ofcfit,sfit, orfittypeobjectSyntax

formula(fun)

Description

formula(fun) returns theformula of the cfit, sfit, or fittype object fun asa character array.

Examplesf = fittype('weibull');
formula(f)
ans =
a*b*x^(b-1)*exp(-a*x^b)

g = fittype('cubicspline');
formula(g)
ans =
piecewise polynomialSee Also

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)

Description

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.

Examples

Create 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');
options = fitoptions(f);

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'},...
{'Final',[0 0 0],'Levenberg'})See Also

fitoptions | get

 

.....................

 

get -Get fit options structure property names and valuesSyntax

get(options)
s = get(options)
value = get(options,fld)

Description

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');
get(options,'Method')
ans =
NonlinearLeastSquares
get(options,'MaxIter')
ans =
400
set(options,'Maxiter',1e3);
get(options,'MaxIter')
ans =
1000

Property values can also be referenced and assigned using thedot notation. For example:

options.MaxIter
ans =
1000
options.MaxIter = 500;
options.MaxIter
ans =
500See Also

fitoptions | set

 

.......................

 

numargs-

Number of input arguments ofcfit,sfit, orfittype

objectSyntax

nargs = numargs(fun)

Description

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)');
nargs = numargs(f)
nargs =
4
args = argnames(f)
args =
'a'
'b'
'n'
'x'See Also

argnames | fittype | formula

 

.........................

 

numcoeffs

-Number of coefficients ofcfit,sfit, orfittype

objectSyntax

ncoeffs = numcoeffs(fun)

Description

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)');
ncoeffs = numcoeffs(f)
ncoeffs =
3
coeffs = coeffnames(f)
coeffs =
'a'
'b'
'n'See Also

coeffnames | fittype | formula

 

 ...............

 

 

probnames

-Problem-dependent parameter names ofcfit,sfit, orfittypeobject

Syntax

pnames = probnames(fun)

Description

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(f)
ans =
'n'
probnames(f)
ans =
'a'
'b'

load census

c = fit(cdate,pop,f,'problem',{cdate(1),pop(1)},...
'StartPoint',2);
coeffvalues(c)
ans =
0.9877
probvalues(c)
ans =
1.0e+003 *
1.7900 0.0039See Also

coeffnames | fittype | probvalues

 

 ......

 

type-Name ofcfit,sfit, orfittypeobjectSyntax

name = type(fun)

Description

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)');
category(f)
ans =
custom
type(f)
ans =
customnonlinear

g = fittype('fourier4');
category(g)
ans =
library
type(g)
ans =
fourier4See Also

category | cflibhelp | fittype

阅读(3023) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~