MATLAB: Using the deviation of a linear regression calculation to trim the calculated data in the linear regression itself.

deviatedeviationlinear regressionMATLABplotting

I have calculated the linear regression of a set of data:
-42.1274227227296 -6.79715991020203
-46.6343683929176 -12.2348878383636
-47.8862977457476 -13.5943198204041
-49.1382270985776 -14.9537518024445
-53.6451727687656 -20.3914797306061
-55.7734526685766 -25.8292076587677
-56.3994173449916 -27.1886396408081
-57.1505749566896 -28.5480716228485
-58.4025043095196 -31.2669355869293
where the 1st column is the X coordinates and the 2nd column is the Y coordinates.
I would like the linear regression to be calculated in a loop (unless there is a better way of doing this) so that it can be calculated using a minimum of the first 5 points, and then keep plotting until it reaches a point which deviates away from the current linear regression by a fixed (user defined) threshold.
The current code used for the linear regression is:
LinearRegression = [ones(length(DATA(:,1)),1) DATA(:,2)]\DATA(:,1);
Plot of linear regression:
figure
scatter(DATA(:,1),DATA(:,2),'o','b')
hold on
plot(DATA(:,1),1/LinearRegression(2)*(DATA(:,1)-LinearRegression(1)),'r')
Thanks in advance!

Best Answer

Thanks for both of your help.
I have implemented the below and it seems to do what I was looking for (note: I have changed variable names, so if it doesn't run for you, check consistency in variable names):
MaxDev = 3; % user defined angle (in degrees)
if length(DATA)<5
LinearRegression = [ones(length(DATA(:,1)),1) DATA(:,2)]\DATA(:,1);
disp('Result inaccurate due to limited amount of data points')
else
LinearInit = [ones(length(DATA(1:5,1)),1) DATA(1:5,2)]\DATA(1:5,1);
InitAngle = abs(atan(1/LinearInit(2)))*180/pi;
for i = 5:length(DATA)
LinearRegressionTmp = [ones(length(DATA(1:i,1)),1) DATA(1:i,2)]\DATA(1:i,1);
TmpAngle = abs(atan(1/LinearRegressionTmp (2)))*180/pi;
if abs(TmpAngle - InitAngle) > MaxDev
LinearRegression = [ones(length(DATA(1:i-1,1)),1) DATA(1:i-1,2)]\DATA(1:i-1,1);
disp('Calculation stopped due to large deviation')
break
else
LinearRegression = [ones(length(DATA(1:i,1)),1) DATA(1:i,2)]\DATA(1:i,1);
end
end
end