RE: Fitting a piecewise continuous Function
- To: mathgroup at smc.vnet.net
- Subject: [mg16741] RE: [mg16646] Fitting a piecewise continuous Function
- From: "Ersek, Ted R" <ErsekTR at navair.navy.mil>
- Date: Wed, 24 Mar 1999 02:23:53 -0500
- Sender: owner-wri-mathgroup at wolfram.com
Jason Gill wrote: ----------------------------- I am trying to fit a piecewise continuous function to some data. Here is a simple example, I hope someone can help me out with. Here I have a function In[69]:= testF[t_]:=r0/;t<ti; testF[t_]:=r0+5*(t-ti)/;t>=ti; The question is, how can I perform a NonlinearFit using the above function to some data. Suppose I have the sample data below, how do I Fit the function to the data, with fit parameters. r0, and ti. Sample data: data1=Table[5,{i,1,10}]; data2=Table[5*i,{i,1,10}]; data=Transpose[{Range[Length[Join[data1,data2]]],Join[data1,data2]}]; I tried (after clearing the values for r0 & t) to perform a NonlinearFit In[7]:= NonlinearFit[data,testF[t],{t},{{r0,5},{ti,10}}] Out: The model is not numerical at {r0->5,ti->10,t->1}. but this does not work. What technique do I need to use to get Mathematica to perform the fit as I have described? What am I missing? Any suggestions would be welcome. ------------------------- Jason, (1)- I am pretty sure the second argument to NonlinearFit has to be a function of the parameters. (2)- The algorithm needs to be able to find the derivatives with respect to each parameter. You defined your function using (expr/;cond), and D[expr, variable] doesn't deal with this very well. Instead you can define your function using Which[test1, value1, test2, value2] or If[cond, expr1, expr2] and D[expr, variable] will work very well. In the event you can't find a way to express the function in a form D[expr, variable] can work with, you could tell NonlinearFit how to compute the derivatives with the option (Gradient). The code below seems to work for your example. ----------------------------- In[1]:= testF[t_,r0_,ti_]:= If[t<ti,r0, r0+5(t-ti)] In[2]:= (* Notice D[testF[t,r0,ti], r0] works. *) D[testF[t,r0,ti], r0] Out[2]= If[t<ti,1,1] In[3]:= data1=Table[5,{i,1,10}]; data2=Table[5*i,{i,1,10}]; data=Transpose[{Range[Length[Join[data1,data2]]],Join[data1,data2]}]; In[4]:= <<Statistics`NonLinearFit` In[5]:= NonlinearFit[data,testF[t,r0,ti],{t},{{r0,5},{ti,10}}] Out[5]= If[t<11.0, 5.0 ,5 .0 + 5 (t-11.0)] -------------------- Regards, Ted Ersek