Solve nonlinear curve-fitting (data-fitting) problems in least-squares sense
Find coefficients x that solve the problem
given input data xdata, and the observed output ydata, where xdata and ydata are matrices or vectors, and F (x, xdata) is a matrix-valued or vector-valued function of the same size as ydata.
Optionally, the components of x can have lower and upper bounds lb, and ub. x, lb, and ub can be vectors or matrices; see Matrix Arguments.
The lsqcurvefit function uses the same algorithm as lsqnonlin. lsqcurvefit simply provides a convenient interface for data-fitting problems.
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(...)
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.
Note: Passing Extra Parameters explains how to pass extra parameters to fun, if necessary.
fun should return fun(x,xdata), and not the sum-of-squares sum((fun(x,xdata)-ydata).^2). lsqcurvefit implicitly computes the sum of squares of the components of fun(x,xdata)-ydata.
x = lsqcurvefit(fun,x0,xdata,ydata,lb,ub,options) minimizes with the optimization options specified in options. Use optimoptions 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 problem structure by exporting a problem from Optimization app, as described in Exporting Your Work.
Function Arguments contains general descriptions of arguments passed into lsqcurvefit. This section provides function-specific details for fun, options, and problem:
The function you want to fit. fun is a function that takes two inputs: a vector or matrix x, and a vector or matrix xdata. fun returns a vector or matrix F, the objective function evaluated at x and xdata. The function fun can be specified as a function handle for a function file:
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, xdata
fun can also be a function handle for an anonymous function.
f = @(x,xdata)x(1)*xdata.^2+x(2)*sin(xdata); x = lsqcurvefit(f,x0,xdata,ydata);
lsqcurvefit internally converts matrix x or F to vectors using linear indexing.
If the Jacobian can also be computed and the Jacobian option is 'on', set by
options = optimoptions('lsqcurvefit','Jacobian','on')
then the function fun must return, in a second output argument, the Jacobian value J, a matrix, at x. 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). (The Jacobian J is the transpose of the gradient of F.) For more information, see Writing Vector and Matrix Objective Functions.
Options provides the function-specific details for the options values.
|Objective function of x and xdata|
|Initial point for x, active set algorithm only|
|Input data for objective function|
|Output data to be matched by objective function|
|lb||Vector of lower bounds|
|ub||Vector of upper bounds|
|Options created with optimoptions|
Function Arguments contains general descriptions of arguments returned by lsqcurvefit. This section provides function-specific details for exitflag, lambda, and output:
Integer identifying the reason the algorithm terminated. The following lists the values of exitflag and the corresponding reasons the algorithm terminated:
Function converged to a solution x.
Change in x was less than the specified tolerance.
Change in the residual was less than the specified tolerance.
Magnitude of search direction smaller than the specified tolerance.
Number of iterations exceeded options.MaxIter or number of function evaluations exceeded options.MaxFunEvals.
Output function terminated the algorithm.
Problem is infeasible: the bounds lb and ub are inconsistent.
Optimization could not make further progress.
Structure containing the Lagrange multipliers at the solution x (separated by constraint type). The fields of the structure are
Lower bounds lb
Upper bounds ub
Structure containing information about the optimization. The fields of the structure are
Measure of first-order optimality
Number of iterations taken
Number of function evaluations
Total number of PCG iterations (trust-region-reflective algorithm only)
Optimization algorithm used
Final displacement in x (Levenberg-Marquardt algorithm).
Optimization options used by lsqcurvefit. Some options apply to all algorithms, some are only relevant when using the trust-region-reflective algorithm, and others are only relevant when you are using the Levenberg-Marquardt algorithm. Use optimoptions to set or change options. See Algorithm Options for detailed information.
The Algorithm option specifies a preference for which algorithm to use. It is only a preference, because certain conditions must be met to use the trust-region-reflective or Levenberg-Marquardt algorithm. For the trust-region-reflective 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 trust-region-reflective algorithm handles bound constraints.
Both algorithms use the following option:
Choose between 'trust-region-reflective' (default) and 'levenberg-marquardt'.
The Algorithm option specifies a preference for which algorithm to use. It is only a preference, because certain conditions must be met to use each algorithm. For the trust-region-reflective 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. The Levenberg-Marquardt algorithm does not handle bound constraints. For more information on choosing the algorithm, see Choosing the Algorithm.
Compare user-supplied derivatives (gradients of objective or constraints) to finite-differencing derivatives. The choices are 'on' or the default 'off'.
Display diagnostic information about the function to be minimized or solved. The choices are 'on' or the default 'off'.
Maximum change in variables for finite-difference gradients (a positive scalar). The default is Inf.
Minimum change in variables for finite-difference gradients (a positive scalar). The default is 0.
Level of display:
Scalar or vector step size factor. When you set FinDiffRelStep to a vector v, forward finite differences delta are
delta = v.*sign(x).*max(abs(x),TypicalX);
and central finite differences are
delta = v.*max(abs(x),TypicalX);
Scalar FinDiffRelStep expands to a vector. The default is sqrt(eps) for forward finite differences, and eps^(1/3) for central finite differences.
Finite differences, used to estimate gradients, are either 'forward' (default), or 'central' (centered). 'central' takes twice as many function evaluations, but should be more accurate.
The algorithm is careful to obey bounds when estimating both types of finite differences. So, for example, it could take a backward, rather than a forward, difference to avoid evaluating at a point outside bounds.
Check whether function values are valid. 'on' displays an error when the function returns a value that is complex, Inf, or NaN. The default 'off' displays no error.
If 'on', lsqcurvefit uses a user-defined Jacobian (defined in fun), or Jacobian information (when using JacobMult), for the objective function. If 'off' (default), lsqcurvefit approximates the Jacobian using finite differences.
Maximum number of function evaluations allowed, a positive integer. The default is 100*numberOfVariables.
Maximum number of iterations allowed, a positive integer. The default is 400.
Specify one or more user-defined functions that an optimization function calls at each iteration, either as a function handle or as a cell array of function handles. The default is none (). See Output Function.
Plots various measures of progress while the algorithm executes, select from predefined plots or write your own. Pass a function handle or a cell array of function handles. The default is none ():
For information on writing a custom plot function, see Plot Functions.
Termination tolerance on the function value, a positive scalar. The default is 1e-6.
Termination tolerance on x, a positive scalar. The default is 1e-6.
Typical x values. The number of elements in TypicalX is equal to the number of elements in x0, the starting point. The default value is ones(numberofvariables,1). lsqcurvefit uses TypicalX for scaling finite differences for gradient estimation.
The trust-region-reflective algorithm uses the following options:
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)
where Jinfo contains the matrix 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, in
[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:
In each case, J is not formed explicitly. lsqcurvefit uses Jinfo to compute the preconditioner. See Passing Extra Parameters for information on how to supply values for any additional parameters jmfun needs.
See Minimization with Dense Structured Hessian, Linear Equalities and Jacobian Multiply Function with Linear Least Squares for similar examples.
Sparsity pattern of the Jacobian for finite differencing. Set JacobPattern(i,j) = 1 when fun(i) depends on x(j). Otherwise, set JacobPattern(i,j) = 0. In other words, JacobPattern(i,j) = 1 when you can have ∂fun(i)/∂x(j) ≠ 0.
Use JacobPattern when it is inconvenient to compute the Jacobian matrix J in fun, though you can determine (say, by inspection) when fun(i) depends on x(j). lsqcurvefit can approximate J via sparse finite differences when you give JacobPattern.
In the worst case, if the structure is unknown, do not set JacobPattern. The default behavior is as if JacobPattern is a dense matrix of ones. Then lsqcurvefit computes a full finite-difference approximation in each iteration. This can be very expensive for large problems, so it is usually better to determine the sparsity structure.
Maximum number of PCG (preconditioned conjugate gradient) iterations, a positive scalar. The default is max(1,floor(numberOfVariables/2)). For more information, see Algorithms.
Upper bandwidth of preconditioner for PCG, a nonnegative integer. 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.
Termination tolerance on the PCG iteration, a positive scalar. The default is 0.1.
The Levenberg-Marquardt algorithm uses the following options:
Initial value of the Levenberg-Marquardt parameter, a positive scalar. Default is 1e-2. For details, see Levenberg-Marquardt Method.
'Jacobian' can sometimes improve the convergence of a poorly-scaled problem; the default is 'none'.
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 a 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);
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,resnorm x = 498.8309 -0.1013 resnorm = 9.5049
There may be a slight variation in the number of iterations and the value of the returned x, depending on the platform and release.
You can use the trust-region reflective algorithm in lsqnonlin, lsqcurvefit, and fsolve with small- to medium-scale problems without computing the Jacobian in fun or providing the Jacobian sparsity pattern. (This also applies to using fmincon or fminunc without computing the Hessian or supplying the Hessian sparsity pattern.) How small is small- to medium-scale? No absolute answer is available, as it depends on the amount of virtual memory in your computer system configuration.
Suppose your problem has m equations and n unknowns. If the command J = sparse(ones(m,n)) causes an Out of memory error on your machine, then this is certainly too large a problem. If it does not result in an error, the problem might still be too large. You can only find out by running it and seeing if MATLAB runs within the amount of virtual memory available on your system.
The trust-region-reflective method does not allow equal upper and lower bounds. For example, if lb(2)==ub(2), lsqcurvefit 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.
The function to be minimized must be continuous. lsqcurvefit might only give local solutions.
lsqcurvefit can solve complex-valued problems directly with the levenberg-marquardt algorithm. However, this algorithm does not accept bound constraints. For a complex problem with bound constraints, split the variables into real and imaginary parts, and use the trust-region-reflective algorithm. See Fit a Model to Complex-Valued Data.
Note: The Statistics Toolbox™ function nlinfit has more statistics-oriented outputs that are useful, for example, in finding confidence intervals for the coefficients. It also comes with the nlintool GUI for visualizing the fitted function.
The lsqnonlin function has more outputs related to how well the optimization performed. It can put bounds on the parameters, and it accepts many options to control the optimization algorithm.
The trust-region-reflective 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 Levenberg-Marquardt algorithm is used instead.
The preconditioner computation used in the preconditioned conjugate gradient part of the trust-region-reflective 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.
Trust-Region-Reflective Problem Coverage and Requirements
|For Large Problems|
The Levenberg-Marquardt algorithm does not handle bound constraints.
Since the trust-region-reflective algorithm does not handle underdetermined systems and the Levenberg-Marquardt does not handle bound constraints, problems with both these characteristics cannot be solved by lsqcurvefit.
By default lsqcurvefit chooses the trust-region-reflective algorithm. This algorithm is a subspace trust-region method and is based on the interior-reflective Newton method described in  and . Each iteration involves the approximate solution of a large linear system using the method of preconditioned conjugate gradients (PCG). See Trust-Region-Reflective Least Squares, and in particular, Large Scale Nonlinear Least Squares.
 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.
 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.
 Dennis, J. E. Jr., "Nonlinear Least-Squares," State of the Art in Numerical Analysis, ed. D. Jacobs, Academic Press, pp. 269-312, 1977.
 Levenberg, K., "A Method for the Solution of Certain Problems in Least-Squares," Quarterly Applied Math. 2, pp. 164-168, 1944.
 Marquardt, D., "An Algorithm for Least-Squares Estimation of Nonlinear Parameters," SIAM Journal Applied Math., Vol. 11, pp. 431-441, 1963.
 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.