lsqcurvefit

Solve nonlinear curve-fitting (data-fitting) problems in least-squares sense

Equation

Find coefficients x that best fit the equation

given input data xdata, and the observed output ydata, where xdata and ydata are matrices or vectors of length m, and F (x, xdata) is a matrix-valued or vector-valued function.

The function lsqcurvefit uses the same algorithm as lsqnonlin. Its purpose is to provide an interface designed specifically for data-fitting problems.

Syntax

x = lsqcurvefit(fun,x0,xdata,ydata)
x = lsqcurvefit(fun,x0,xdata,ydata,lb,ub)
x = lsqcurvefit(fun,x0,xdata,ydata,lb,ub,options)
x = lsqcurvefit(problem)
[x,resnorm] = lsqcurvefit(...)
[x,resnorm,residual] = lsqcurvefit(...)
[x,resnorm,residual,exitflag] = lsqcurvefit(...)
[x,resnorm,residual,exitflag,output] = lsqcurvefit(...)
[x,resnorm,residual,exitflag,output,lambda] = lsqcurvefit(...)
[x,resnorm,residual,exitflag,output,lambda,jacobian] = lsqcurvefit(...)

Description

lsqcurvefit solves nonlinear data-fitting problems. lsqcurvefit requires a user-defined function to compute the vector-valued function F (x, xdata). The size of the vector returned by the user-defined function must be the same as the size of the vectors ydata and xdata.

x = lsqcurvefit(fun,x0,xdata,ydata) starts at x0 and finds coefficients x to best fit the nonlinear function fun(x,xdata) to the data ydata (in the least-squares sense). ydata must be the same size as the vector (or matrix) F returned by fun.

x = lsqcurvefit(fun,x0,xdata,ydata,lb,ub) defines a set of lower and upper bounds on the design variables in x so that the solution is always in the range lb ≤ x ≤ ub.

x = lsqcurvefit(fun,x0,xdata,ydata,lb,ub,options) minimizes with the optimization options specified in the structure options. Use optimset to set these options. Pass empty matrices for lb and ub if no bounds exist.

x = lsqcurvefit(problem) finds the minimum for problem, where problem is a structure described in Input Arguments.

Create the structure problem by exporting a problem from Optimization Tool, as described in Exporting to the MATLAB® Workspace.

[x,resnorm] = lsqcurvefit(...) returns the value of the squared 2-norm of the residual at x: sum((fun(x,xdata)-ydata).^2).

[x,resnorm,residual] = lsqcurvefit(...) returns the value of the residual fun(x,xdata)-ydata at the solution x.

[x,resnorm,residual,exitflag] = lsqcurvefit(...) returns a value exitflag that describes the exit condition.

[x,resnorm,residual,exitflag,output] = lsqcurvefit(...) returns a structure output that contains information about the optimization.

[x,resnorm,residual,exitflag,output,lambda] = lsqcurvefit(...) returns a structure lambda whose fields contain the Lagrange multipliers at the solution x.

[x,resnorm,residual,exitflag,output,lambda,jacobian] = lsqcurvefit(...) returns the Jacobian of fun at the solution x.

Input Arguments

Function Arguments contains general descriptions of arguments passed into lsqcurvefit. This section provides function-specific details for fun, options, and problem:

fun

The function you want to fit. fun is a function that takes a vector x and returns a vector F, the objective functions evaluated at x. The function fun can be specified as a function handle for an M-file function

x = lsqcurvefit(@myfun,x0,xdata,ydata)

where myfun is a MATLAB® function such as

function F = myfun(x,xdata)
F = ...            % Compute function values at x

fun can also be a function handle for an anonymous function.

f = @(x,xdata)x(1)*xdata.^2+x(2)*sin(xdata),...
           'x','xdata';
x = lsqcurvefit(f,x0,xdata,ydata);

If the user-defined values for x and F are matrices, they are converted to a vector using linear indexing.

    Note   fun should return fun(x,xdata), and not the sum-of-squares sum((fun(x,xdata)-ydata).^2). The algorithm implicitly squares and sums fun(x,xdata)-ydata.

If the Jacobian can also be computed and the Jacobian option is 'on', set by

options = optimset('Jacobian','on')

then the function fun must return, in a second output argument, the Jacobian value J, a matrix, at x. Note that by checking the value of nargout the function can avoid computing J when fun is called with only one output argument (in the case where the optimization algorithm only needs the value of F but not J).

function [F,J] = myfun(x,xdata)
F = ...          % objective function values at x
if nargout > 1   % two output arguments
   J = ...   % Jacobian of the function evaluated at x
end
 

If fun returns a vector (matrix) of m components and x has length n, where n is the length of x0, then the Jacobian J is an m-by-n matrix where J(i,j) is the partial derivative of F(i) with respect to x(j). (Note that the Jacobian J is the transpose of the gradient of F.) For more information, see Jacobians of Vector and Matrix Objective Functions.

options

Options provides the function-specific details for the options values.

problem

objective

Objective function of x and xdata

x0

Initial point for x, active set algorithm only

xdata

Input data for objective function

ydata

Output data to be matched by objective function
lbVector of lower bounds
ubVector of upper bounds

solver

'lsqcurvefit'

options

Options structure created with optimset

Output Arguments

Function Arguments contains general descriptions of arguments returned by lsqcurvefit. This section provides function-specific details for exitflag, lambda, and output:

exitflag

Integer identifying the reason the algorithm terminated. The following lists the values of exitflag and the corresponding reasons the algorithm terminated:

 

1

Function converged to a solution x.

 

2

Change in x was less than the specified tolerance.

 

3

Change in the residual was less than the specified tolerance.

 

4

Magnitude of search direction smaller than the specified tolerance.

 

0

Number of iterations exceeded options.MaxIter or number of function evaluations exceeded options.FunEvals.

 

-1

Algorithm was terminated by the output function.

 

-2

Problem is infeasible: the bounds lb and ub are inconsistent.

 

-4

Optimization could not make further progress.

lambda

Structure containing the Lagrange multipliers at the solution x (separated by constraint type). The fields of the structure are

 lower

Lower bounds lb

 upper

Upper bounds ub

output

Structure containing information about the optimization. The fields of the structure are

 firstorderopt

Measure of first-order optimality (large-scale algorithm, [ ] for others).

 iterations

Number of iterations taken

 funcCount

Number of function evaluations

 cgiterations

Total number of PCG iterations (large-scale algorithm, [ ] for others)

 algorithm

Optimization algorithm used

 stepsize

Final displacement in x (medium-scale algorithm only).

 message

Exit message

Options

Optimization options used by lsqcurvefit. Some options apply to all algorithms, some are only relevant when using the large-scale algorithm, and others are only relevant when you are using the medium-scale algorithm. You can use optimset to set or change the values of these fields in the options structure options. See Optimization Options for detailed information.

The LargeScale option specifies a preference for which algorithm to use. It is only a preference, because certain conditions must be met to use the large-scale or medium-scale algorithm. For the large-scale algorithm, the nonlinear system of equations cannot be underdetermined; that is, the number of equations (the number of elements of F returned by fun) must be at least as many as the length of x. Furthermore, only the large-scale algorithm handles bound constraints:

LargeScale

Use large-scale algorithm if possible when set to 'on'. Use medium-scale algorithm when set to 'off'.

The large-scale algorithm is a more modern algorithm than the medium-scale algorithms. The large-scale algorithm handles both large-scale and medium-scale problems effectively.

Medium-Scale and Large-Scale Algorithms

These options are used by both the medium-scale and large-scale algorithms:

DerivativeCheck

Compare user-supplied derivatives (Jacobian) to finite-differencing derivatives.

Diagnostics

Display diagnostic information about the function to be minimized.

DiffMaxChange

Maximum change in variables for finite differencing.

DiffMinChange

Minimum change in variables for finite differencing.

Display

Level of display. 'off' displays no output, and 'final' (default) displays just the final output.

Jacobian

If 'on', lsqcurvefit uses a user-defined Jacobian (defined in fun), or Jacobian information (when using JacobMult), for the objective function. If 'off', lsqcurvefit approximates the Jacobian using finite differences.

MaxFunEvals

Maximum number of function evaluations allowed.

MaxIter

Maximum number of iterations allowed.

OutputFcn

Specify one or more user-defined functions that an optimization function calls at each iteration. See Output Function.

PlotFcns

Plots various measures of progress while the algorithm executes, select from predefined plots or write your own. Specifying @optimplotx plots the current point; @optimplotfunccount plots the function count; @optimplotfval plots the function value.

TolFun

Termination tolerance on the function value.

TolX

Termination tolerance on x.

TypicalX

Typical x values.

Large-Scale Algorithm Only

These options are used only by the large-scale algorithm:

JacobMult

Function handle for Jacobian multiply function. For large-scale structured problems, this function computes the Jacobian matrix product J*Y, J'*Y, or J'*(J*Y) without actually forming J. The function is of the form

W = jmfun(Jinfo,Y,flag,p1,p2,...) 
 

where Jinfo and the additional parameters p1,p2,... contain the matrices used to compute J*Y (or J'*Y, or J'*(J*Y)). The first argument Jinfo must be the same as the second argument returned by the objective function fun, for example by

[F,Jinfo] = fun(x)

Y is a matrix that has the same number of rows as there are dimensions in the problem. flag determines which product to compute:

  • If flag == 0 then W = J'*(J*Y).

  • If flag > 0 then W = J*Y.

  • If flag < 0 then W = J'*Y.

    In each case, J is not formed explicitly. fsolve uses Jinfo to compute the preconditioner. The optional parameters p1, p2, ... can be any additional parameters needed by jmfun. See Passing Extra Parameters for information on how to supply values for these parameters.

 

    Note   'Jacobian' must be set to 'on' for Jinfo to be passed from fun to jmfun.

See Nonlinear Minimization with a Dense but Structured Hessian and Equality Constraints for a similar example.

JacobPattern

Sparsity pattern of the Jacobian for finite differencing. If it is not convenient to compute the Jacobian matrix J in fun, lsqcurvefit can approximate J via sparse finite differences, provided the structure of J, i.e., locations of the nonzeros, is supplied as the value for JacobPattern. In the worst case, if the structure is unknown, you can set JacobPattern to be a dense matrix and a full finite-difference approximation is computed in each iteration (this is the default if JacobPattern is not set). This can be very expensive for large problems, so it is usually worth the effort to determine the sparsity structure.

MaxPCGIter

Maximum number of PCG (preconditioned conjugate gradient) iterations (see Algorithm).

PrecondBandWidth

The default PrecondBandWidth is 'Inf', which means a direct factorization (Cholesky) is used rather than the conjugate gradients (CG). The direct factorization is computationally more expensive than CG, but produces a better quality step towards the solution. Set PrecondBandWidth to 0 for diagonal preconditioning (upper bandwidth of 0). For some problems, an intermediate bandwidth reduces the number of PCG iterations.

TolPCG

Termination tolerance on the PCG iteration.

Medium-Scale Algorithm Only

These options are used only by the medium-scale algorithm:

LevenbergMarquardt

Choose Levenberg-Marquardt over Gauss-Newton algorithm.

LineSearchType

Line search algorithm choice.

Examples

Given vectors of data xdata and ydata, suppose you want to find coefficients x to find the best fit to the exponential decay equation

That is, you want to minimize

where m is the length of xdata and ydata, the function F is defined by

F(x,xdata) = x(1)*exp(x(2)*xdata);

and the starting point is x0 = [100; -1];.

First, write an M-file to return the value of F (F has n components).

function F = myfun(x,xdata)
F = x(1)*exp(x(2)*xdata);

Next, invoke an optimization routine:

% Assume you determined xdata and ydata experimentally
xdata = ...
 [0.9 1.5 13.8 19.8 24.1 28.2 35.2 60.3 74.6 81.3];
ydata = ...
 [455.2 428.6 124.1 67.3 43.2 28.1 13.1 -0.4 -1.3 -1.5];
x0 = [100; -1] % Starting guess
[x,resnorm] = lsqcurvefit(@myfun,x0,xdata,ydata)

Note that at the time that lsqcurvefit is called, xdata and ydata are assumed to exist and are vectors of the same size. They must be the same size because the value F returned by fun must be the same size as ydata.

After 27 function evaluations, this example gives the solution

x = 
498.8309 -0.1013 
resnorm = 
9.5049

There may be slight variation in the number of iterations and the value of the returned x that is dependent upon the platform and release.

Algorithm

Large-Scale Optimization

By default lsqcurvefit chooses the large-scale algorithm. This algorithm is a subspace trust-region method and is based on the interior-reflective Newton method described in [1] and [2]. Each iteration involves the approximate solution of a large linear system using the method of preconditioned conjugate gradients (PCG). See Trust-Region Methods for Nonlinear Minimization and Preconditioned Conjugate Gradients.

Medium-Scale Optimization

If you set the LargeScale option to 'off' with optimset, lsqcurvefit uses the Levenberg-Marquardt method with line search [4], [5], and [6]. Alternatively, you can select a Gauss-Newton method [3] with line search by setting the LevenbergMarquardt option to 'off' (and LargeScale to 'off') with optimset. The Gauss-Newton method is generally faster when the residual sum((fun(x,xdata)-ydata).^2) is small.

The default line search algorithm, i.e., the LineSearchType option, is 'quadcubic'. This is a safeguarded mixed quadratic and cubic polynomial interpolation and extrapolation method. You can select a safeguarded cubic polynomial method by setting the LineSearchType option to 'cubicpoly'. This method generally requires fewer function evaluations but more gradient evaluations. Thus, if gradients are being supplied and can be calculated inexpensively, the cubic polynomial line search method is preferable. The algorithms used are described fully in Standard Algorithms.

Diagnostics

Large-Scale Optimization

The large-scale method does not allow equal upper and lower bounds. For example, if lb(2)==ub(2), lsqlin gives the error

Equal upper and lower bounds not permitted.

(lsqcurvefit does not handle equality constraints, which is another way to formulate equal bounds. If equality constraints are present, use fmincon, fminimax, or fgoalattain for alternative formulations where equality constraints can be included.)

Limitations

The function to be minimized must be continuous. lsqcurvefit might only give local solutions.

lsqcurvefit only handles real variables (the user-defined function must only return real values). When x has complex variables, the variables must be split into real and imaginary parts.

Large-Scale Optimization

The large-scale algorithm for lsqcurvefit does not solve underdetermined systems; it requires that the number of equations, i.e., the row dimension of F, be at least as great as the number of variables. In the underdetermined case, the medium-scale algorithm is used instead. See Large-Scale Problem Coverage and Requirements for more information on what problem formulations are covered and what information must be provided.

The preconditioner computation used in the preconditioned conjugate gradient part of the large-scale method forms JTJ (where J is the Jacobian matrix) before computing the preconditioner; therefore, a row of J with many nonzeros, which results in a nearly dense product JTJ, can lead to a costly solution process for large problems.

If components of x have no upper (or lower) bounds, then lsqcurvefit prefers that the corresponding components of ub (or lb) be set to inf (or -inf for lower bounds) as opposed to an arbitrary but very large positive (or negative for lower bounds) number.

Medium-Scale Optimization

The medium-scale algorithm does not handle bound constraints.

Since the large-scale algorithm does not handle underdetermined systems and the medium-scale does not handle bound constraints, problems with both these characteristics cannot be solved by lsqcurvefit.

References

[1] Coleman, T.F. and Y. Li, "An Interior, Trust Region Approach for Nonlinear Minimization Subject to Bounds," SIAM Journal on Optimization, Vol. 6, pp. 418-445, 1996.

[2] Coleman, T.F. and Y. Li, "On the Convergence of Reflective Newton Methods for Large-Scale Nonlinear Minimization Subject to Bounds," Mathematical Programming, Vol. 67, Number 2, pp. 189-224, 1994.

[3] Dennis, J. E. Jr., "Nonlinear Least-Squares," State of the Art in Numerical Analysis, ed. D. Jacobs, Academic Press, pp. 269-312, 1977.

[4] Levenberg, K., "A Method for the Solution of Certain Problems in Least-Squares," Quarterly Applied Math. 2, pp. 164-168, 1944.

[5] Marquardt, D., "An Algorithm for Least-Squares Estimation of Nonlinear Parameters," SIAM Journal Applied Math., Vol. 11, pp. 431-441, 1963.

[6] More, J. J., "The Levenberg-Marquardt Algorithm: Implementation and Theory," Numerical Analysis, ed. G. A. Watson, Lecture Notes in Mathematics 630, Springer Verlag, pp. 105-116, 1977.

See Also

@ (function_handle), \ (matrix left division), lsqlin, lsqnonlin, lsqnonneg, optimset, optimtool, nlinfit

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS