# Nonlinear fit with piecewise functions

I have an ensemble of data points $(x_i,y_i)$ and I need to fit them according to $y=F(a,b,x)$ if $x \leq x_{ref}$ and $y=G(c,d,x)$ if $x \geq x_{ref}$. The parameters I need to adjust are then $a,b,c,d,x_{ref}$. Models $F$ and $G$ are nonlinear with respect to the parameters.

For sure, if I select $x_{ref}$ among the $x_i$, I can run separate curve fits, add the sum of squares and change $i$ until I find a minimum.

Is there any way

1. to automate this procedure with Mathematica (this would provide the best values of $a,b,c,d$ for the best $x_{ref}$ selected among the $x_i$)
2. perform in a second step the full regression

Any help will be appreciated.

-
Please include a small complete example, it will help to work on something concrete. – b.gatessucks Mar 16 '14 at 10:06

## 1 Answer

If I understand your query, you want to do something like this (xref of 5 hard-coded here):

ClearAll[data, fitfn, x, a, b, c, d]

(* fake some non-linear data *)
data = {#, If[# < 5, 2 # ^1.5, 4 #^2.5]} & /@ Range[20];

(* fit function *)
fitfn[x_, a_, b_, c_, d_] := Piecewise[{{a x^b, x < 5}, {c x^d, x >= 5}}]

(* find parameters*)
sol = FindFit[data, fitfn[x, a, b, c, d], {a, b, c, d}, x];

(* data vs fit *)
Column[{sol,
ListPlot[{Sort@data, Table[fitfn[x, a, b, c, d] /. sol, {x, 1, 20}]}, Joined -> True,
ImageSize -> 300]}, Left, 2]


-
This is a almost what I am looking for but it does not answer the problem of finding the $5$ which is a parameter to be adjusted. The function must have the $5$ as a tunable parameter. Would you find a way to answer the first question (loop around the $x_i=x_{ref}$ to find the best point) and complete the second one with $x_{ref}$ as adjustable parameter). Thank you ! – Claude Leibovici Mar 16 '14 at 12:39
@ClaudeLeibovici: No. Everything you need to polish this and add search is in the answer, this is not a code-for-free site. Make an attempt and show your code, if you get stuck or have problems, post a new question or update this one. – ciao Mar 18 '14 at 8:36
I am not looking for a code-for-free site but for help since I am a more than limited user. – Claude Leibovici Mar 18 '14 at 8:51