Post by janeI have tried to use the command lsqcurvefit to fit the nonlinear
function to some data. However, there is a need that when x = 0, I
should also get the yhat = 0. So I think I need to do the constrain
regression. My question is how I can use the lsqcurvefit to do the
constrain nonlinear regression.
Thank you
Jane
You can't do this directly with LSQCURVEFIT ... you might want to use
FMINCON instead and minimize the sum of the squared errors. Here's a small
example that will work with MATLAB 6.0 (R12) and later, and also
demonstrates how some of the new functionality of MATLAB 7.0 (R14) can prove
useful in solving problems like this.
function [c, anonfun] = foo
% Generate data
x = 0:5;
y = x.^2+rand(size(x));
% Set up options structure for FMINCON
options = optimset('fmincon');
% Turn off the LargeScale algorithm and prevent any information from being
% displayed in the Command Window
options = optimset(options, 'LargeScale', 'off', 'Display', 'off');
% Call FMINCON
c = fmincon(@objfun, zeros(3,1), [], [], [], [], [], [], @nonlcon, options,
x, y);
% In MATLAB 7.0 (R14) the above line could also have been written
%
% c = fmincon(@(c) objfun(c, x, y), zeros(3,1), [], [], [], [], [], [],
@nonlcon, options);
%
% and the nonlinear constraint function nonlcon below would not have needed
% to accept the parameters x and y, which it does not use. Its calling
% syntax would have been:
%
% function [c_ineq, c_eq] = nonlcon(c)
% Display the equation
fprintf('The equation is y = %g*x^2 + %g*x + %g', c)
% Allocate this variable so that if the anonymous function line below is
% commmented out, MATLAB will not complain that we have not defined one of
% the output arguments yet
anonfun = [];
% Comment the next line of code out if using a version of MATLAB prior to
7.0 (R14)
% This is an anonymous function that is returned by foo so that you can
% evaluate the fit outside of foo.m
anonfun = @(x) evaluate(c, x);
% Subfunction to evaluate the residuals
function z=objfun(c, x, y)
% Evaluate the function for the given coefficients c, calculate residuals
r = evaluate(c, x) - y;
% Return the sum of the squares of the residuals
z = sum(r.^2);
% Subfunction to evaluate the function
function y = evaluate(c, x)
y = c(1)*x.^2+c(2)*x+c(3);
% Nonlinear constraint function
function [c_ineq, c_eq] = nonlcon(c, x, y)
% No nonlinear inequality constraints
c_ineq = [];
% Constrain the objective function to evaluate to 0 at x=0
c_eq = evaluate(c, 0);
--
Steve Lord
***@mathworks.com