lsqfit (MathScript RT Module Function)

LabVIEW 2012 MathScript RT模块帮助

版本日期:June 2012



Owning Class: approximation

Requires: MathScript RT Module


x = lsqfit(fun, a0, xdata, ydata)

x = lsqfit(fun, a0, xdata, ydata, lb, ub)

[x, normres] = lsqfit(fun, a0, xdata, ydata)

[x, normres] = lsqfit(fun, a0, xdata, ydata, lb, ub)

[x, normres, resid] = lsqfit(fun, a0, xdata, ydata)

[x, normres, resid] = lsqfit(fun, a0, xdata, ydata, lb, ub)

Legacy Name: lsqcurvefit


Uses the least-squares method to compute the solution to a nonlinear curve-fitting problem.




Name Description
fun Specifies the nonlinear function, defined and saved in a .m file, to fit.
a0 Specifies an initial guess for the parameter vector.
xdata Specifies the input data vector of the nonlinear function fun.
ydata Specifies the output data vector of the nonlinear function fun.
lb Specifies the lower bounds of the parameter vector. length(lb) must equal length(a0).
ub Specifies the upper bounds of the parameter vector. length(ub) must equal length(a0).


Name Description
x Returns the coefficients that minimize the mean square error between the solution vector and the observed y-values.
normres Returns the value of the squared 2-norm of the residual.
resid Returns the residue of the fitted curve.


This function uses the Levenberg-Marquardt algorithm to determine the set of parameters that best fit the set of input data points (xdata, ydata) as expressed by the nonlinear function ydata = f(a, xdata), where a is the set of parameters.

The function to fit is defined by the input parameter fun, which is a script file and takes the form of the following equation:

[F, df] = myfun(a, xdata)

where F is the array of values evaluated at xdata: myfun(a, xdata), and df is a two-dimensional array of the partial derivatives at xdata with respect to the coefficients, or the Jacobian value J. The calculation of the partial derivatives is optional. If you do not calculate the derivatives in the script, df must equal zeros(0, 0), and LabVIEW calculates the derivatives numerically.

The following table lists the support characteristics of this function.

Supported in the LabVIEW Run-Time Engine No
Supported on RT targets Yes
Suitable for bounded execution times on RT Not characterized


% The myfun function is defined by:
%function [F, df] = myfun(a, xdata)
%F = a(1)*xdata.^2 + a(2)*cos(xdata);
%df = zeros(0, 0);

a = [2, 1.5];
x = 0:1:19;
noise = randnormal(size(x)) / 5;
y = a(1)*x.^2 + a(2)*cos(x) + noise;
[x, normres, resid] = lsqfit('myfun', [10, 10], x, y);