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!
Asked
Active
Viewed 256 times
1
-
1Please post an example in Mathematica input form. – Daniel Lichtblau Nov 27 '15 at 15:57
-
2Have a look Fitting piecewise functions – Nov 27 '15 at 16:41
1 Answers
2
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}
Karsten7
- 27,448
- 5
- 73
- 134
Peter Richter
- 353
- 1
- 5
-
Welcome to Mathematica.SE!
- As you receive help, try to give it too, by answering questions in your area of expertise.
- Take the tour and check the faqs!
- 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!
– Nov 27 '15 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? – Lucia Nov 27 '15 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. – Lucia Nov 27 '15 at 21:24
-
@Lucia The
cvalue 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. – Peter Richter Nov 28 '15 at 03:23


