MATLAB: Broken stick regression and find change point

broken stick regressionfindchangeptssegmented regression

Hi!
I've got two vectors, one with data on outside temperature, and the other one is heat supply for a building. I can scatter plot the vectors to get a visual of how the heat supply increases with lower temperature (Celsius). For higher temperature heat is only needed for water and therefore there is no longer a dependency between increasing temperature and lowered heat demand. As can be seen in the picture below
I would like to find the change point, (the temperature where building heating is starting to be needed) and perform a segmented regression (broken stick), one line for the temperature dependent part, and one line for the independent. Is there a way to do that in for example the curve fitting app? Or how do i write it in code?
I know about the function Findchangepts, but it only works with 1 vector, not 2, and not with a matrix.

Best Answer

Since you provide no data, I'll make some up.
plot(xdata,ydata,'o')
grid on
Not quite the same as yours, since yours is clearly not uniform variance. I will assume there is an unknown break location, and employ a model where the function is constant above the break, and continuous but not differentiable at the break.
Two small helper functions...
coefs = @(xbreak) [ones(numel(xdata),1),min(xdata,xbreak)-xbreak]\ydata;
errfun = @(xbreak) norm([ones(numel(xdata),1),min(xdata,xbreak)-xbreak]*coefs(xbreak) - ydata);
They assume that xdata and ydata are column vectors of the same length, residing in your workspace.
Solve for the break point:
xbreak = fminbnd(errfun,0,1)
xbreak =
0.59438654958197
Not bad, since the real function that I created had a break at 0.60.
C = coefs(xbreak)
ans =
-0.462584832269373
-1.32149120536521
Above the break point, the function is constant, at -0.4625...
Below the break point, the slope is estimated at -1.32.
So, the line below the break point can be written as
y = (x - xbreak)*C(2) + C(1)
Above the break point, it is simply
y = C(1)