Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Curve fitting
Date: Wed, 14 Oct 2009 11:35:19 +0000 (UTC)
Organization: The MathWorks Ltd
Lines: 64
Message-ID: <hb4d1n$brp$1@fred.mathworks.com>
References: <hb12d7$jrp$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-05-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1255520119 12153 172.30.248.35 (14 Oct 2009 11:35:19 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Wed, 14 Oct 2009 11:35:19 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 915772
Xref: news.mathworks.com comp.soft-sys.matlab:577190


Hi Mohammad, 

It is possible to fit piecewise functions to a set of data using either lsqcurvefit from the Optimization Toolbox. 

Firstly, for the example you state, I think you may have your inequalities mis-typed. I think your equation should be

if 0<= x <= p1
   f(x) = f_1(x, p1, p2, p3)
else
   f(x) = f_2(x, p1, p2, p3)
end

Now, say you have a MATLAB function, called myFunction which evaluates the equation above

function y = myFunction(x, p1, p2, p3)

if 0<= x <= p1
   y = f_1(x, p1, p2, p3)
else
   y = f_2(x, p1, p2, p3)
end

To fit p1, p2, p3 for this equation using the data (xdata, ydata), you can use lsqcurvefit. First, you need to write an objective function for lsqcurvefit. This function must be able to evaluate your equation at each of the data points, xdata.

function y = objfun(p, xdata)

% Assume each row of xdata is a point.
numDataPoints = size(xdata, 1);
y = zeros(numDataPoints, 1);

% Evaluate myFunction at each point in xdata. Note, there are more efficient ways to do this, just using a for loop for clarity.
for i = 1:numDataPoints
  y(i) = myFunction(xdata(i, :), p(1), p(2), p(3));
end

Now call lsqcurvefit:

estP = lsqcurvefit(@objfun, p0, xdata, ydata);

where, p0 is a 1-by-3 vector containing an initial guess for the parameter values p(1), p(2) and p(3). The fitted parameters are returned in the variable estP.

As a cautionary note, fitting piecewise equations using least squares techniques can be tricky. In your case, a good initial guess for p(1) will be very useful.

To get more help on LSQCURVEFIT, see the Optimization Toolbox documentation. 

Hope this helps.

Cheers, 

Paul


"Mohammad Monfared" <gohardoust@gmail.com> wrote in message <hb12d7$jrp$1@fred.mathworks.com>...
> Hi,
> I'd like to fit a function, f(x), to my data (x,y). 'f' has three parameter to be determined p1, p2, p3, and is of form:  
> 
> f_1(x)          0 <= x >= p1  ;
> f_2(x)          p1 < x  ;
> 
> How can I do this job while have two equation for f(x) ?
> ( I have access to the Optimization toolbox)
> 
> thanks a lot,
> Mohammad,