# Data fitted by two linear fits [duplicate]

can anybody help me please and tell me how to fit my set of points by two linear fits? It is always exactly two of them and are always linear and should cover all the data. The second line should always be steeper than the first one. I need Mathematica to determine the turning point and ideally tell me not just the two fitting functions but also their beginning and end coordinates, so I can then work directly with "red lines" instead of "blue dots" in further processing of data. Many thanks for the answers!

• Please post an example in Mathematica input form. Commented Nov 27, 2015 at 15:57
• Have a look Fitting piecewise functions
– user9660
Commented Nov 27, 2015 at 16:41

## 1 Answer

FindFit can fit a dataset to an arbitrary function, including piecewise functions (which appears to be your intended model).

As an example dataset:

dat = Table[{x + 5, 2 + 0.5 RandomReal[] + Piecewise[{{-x, x < 0}, {2 x, x >= 0}}]},
{x, -3, 5, 0.1}];

ListPlot[dat]


You can then use FindFit to find a fit:

model = d + Piecewise[{{a (x - c), x < c}, {b (x - c), x >= c}}];
fit = FindFit[dat, model, {a, b, c, d}, x]
fitdat = Table[{x, model /. fit}, {x, 2, 10, 0.1}];
ListLinePlot[{dat, fitdat}]


{a -> -1.02062, b -> 1.99791, c -> 4.98502, d -> 2.25592}

• Welcome to Mathematica.SE! 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Take the tour and check the faqs! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign!
– user9660
Commented Nov 27, 2015 at 16:29
• Thanks, that seems to be the right way to do it, but it somehow doesn't work fine for me. If I understand correctly, c is the turning point, right? So in the picture I originally posted in my question, c should be approximately 160. But when I try to run the code, c always results to be 1 for any set of data I try. What do I do wrong? :( Also, how can I put the fit into the plot together with data? Commented Nov 27, 2015 at 17:46
• And if I include the initial estimation of the c value like this FindFit[dat, Piecewise[{{a x, x < c}, {b x, x > c}}], {a, b, {c,160}}, x], then c is not fitted at all, it always results exactly to my estimation - no matter if my guess is 160 or 3 or whatever else. Commented Nov 27, 2015 at 21:24
• @Lucia The c value was not working correctly because my model was stupid and discontinuous except for when $c=0$ :) I've fixed my answer accordingly. It now should work correctly. Commented Nov 28, 2015 at 3:23