MATLAB: How to fit segmental regession with matlab

Curve Fitting ToolboxMATLABsegmental regression fit

Hello,
there are many threaads about this theme, but I couldnt find the one which fits my problem.
I have set of datapoints with X and Y coordinates. From experience I can say, that they are best represented with two straight lines with an Intersection point.
So, there are two linear regression formulas f1(x) = m1 * x + b1 , f2(x) = m2 * x + b2. How can I get the best matching parameter pairs (with minimal squared error) [m1 m2] and [b1 b2] using a matlab fit?

Best Answer

Actually, you are fitting the intersection point as well. The code below is not guaranteed to result in a continuous function, but you can probably adapt the cost function to get that property.
f1=@(x,b) b(1)*x+b(2);
f2=@(x,b) b(1)*x+b(2);
f_composite=@(x,b) ...
f1(x,b(1:2)).*double(x>b(5)) + ...
f2(x,b(3:4)).*double(x<=b(5));
initial_guess=[1 1 1 1 0];
OLS=@(b,x,y,f) sum((f(b,x) - y).^2);
% %adapted Ordinary Least Squares cost function
% OLS_as_char=[...
% 'sum((f(b,x) - y).^2) +'... % OLS part
% 'inf^(any(b<bounds(:,1))-1) +'...%converts true to inf
% 'inf^(any(b>bounds(:,2))-1)'];
opts = optimset('MaxFunEvals',50000, 'MaxIter',10000);
% Use 'fminsearch' to minimise the 'OLS' function
fit_val = fminsearch(OLS, initial_guess(:), opts,x,y,f_composite);