I need to fit a curve, obtained from experimental data, with a piecewise linear model (4 knots and therefore 3 lines).
I tried using the MATLAB function
coeff = lsqnonlin(@fun,X0,[],[],[],x,y);
where $fun$ is a function defined as:
[f] = fun (X,x,y)
A = X(1);
.
.
.
F = X(6);
if x(i) <= kn1
f(i) = A+B*x(i)-y(i);
elseif x(i) > kn1 && x(i) <= kn2
f(i) = C+D*x(i)-y(i);
else
f(i) = E+F*x(i)-y(i);
end
In this way I should find the coefficients $A,B,C,D,E,F$ which minimize the difference between the model and the real curve (represented by $y$). $X$ is the coefficients vector.
The main problem I have is that the knots $kn1$ and $kn2$ cannot be placed anywhere: usually MATLAB places the knots at the same distance one from the other, but in my case I need that the knots are placed in the exact point where the real curve changes its slope (of course the change in the slope does not occur suddenly, it is gradual since it is a curved line but I need to approximate it).
To do that I thought about some constrained optimization to be run before the fitting, in order to find those 2 points before computing the function $fun$. The MATLAB function I could use to do that is
x_opt = fmincon ( fun2, x02, A2, b, Aeq, beq, lb, ub )
but I do not know how to express the constraints related to the slope changes.
Is there any other way I could to this?
cvx
. As another idea... you can find (possible) nodes computing the (abrupt) changes in derivative and curvature of your data. $\endgroup$ – nicoguaro♦ Nov 10 '14 at 17:04