# Piecewise linear approximation of an experimental data curve. Knots position constrained

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?

• If you want to approximate your data as piecewise linear the position of your nodes is what determines the equations. – nicoguaro Nov 9 '14 at 23:33
• Yes right, because from that point on the slope of the curve changes. What I am trying to do is to make matlab find these points and use them as knots to be used inside the function $fun$. At the moment I choose them looking at the plot of the experimental curve but, since I have to run this analysis many times, I would like to have a procedure to choose the knots position – Rhei Nov 10 '14 at 6:27
• Do you always have the same number of pieces? If that is the case you can just optimize for the positions of your nodes. If your function looks like a convex one, you can try something like this, from cvx. As another idea... you can find (possible) nodes computing the (abrupt) changes in derivative and curvature of your data. – nicoguaro Nov 10 '14 at 17:04