MATLAB: Using Two Best Fit Lines on the Same Set of Data

polyfit bestfit

clear all clf x = [0 .5 1 1.1 1.2 1.3 1.4 1.5 1.6 1.69 1.76 1.81 1.84 1.86 1.88 1.90 1.91 1.92 1.94 1.95 1.95 1.96 1.97 1.99 2]; y = [0 0.000001 0.000002 0.000003 0.000004 0.000005 0.000006 .00037 .00416 .0570 .34080 .89310 1.58 2.34 3.14 3.97 4.82 5.69 6.57 7.46 8.37 9.29 10.2 12.5 14.9]; plot(x,y,'bp') z = polyfit(x(0:1.4),y(0:0.000006),1); Slope = z(1); Intercept = z(2); y_best=Slope*x+Intercept; hold on plot(x,y_best)
//I also want to put another best fit line over the last portion of data. I can't even get it to work for the first line, so I am not sure what to do.
Thanks for the help!

Best Answer

I’m not quite sure what you intend by ‘last portion’ so I took a wild guess. Change the threshold for ‘Lidx2’ to meet your requirements.
The Code
x = [0 .5 1 1.1 1.2 1.3 1.4 1.5 1.6 1.69 1.76 1.81 1.84 1.86 1.88 1.90 1.91 1.92 1.94 1.95 1.95 1.96 1.97 1.99 2];
y = [0 0.000001 0.000002 0.000003 0.000004 0.000005 0.000006 .00037 .00416 .0570 .34080 .89310 1.58 2.34 3.14 3.97 4.82 5.69 6.57 7.46 8.37 9.29 10.2 12.5 14.9];
plot(x,y,'bp')
Lidx1 = x <= 1.4; % Logical Index Vector

z1 = polyfit(x(Lidx1),y(Lidx1),1);
y1_best = polyval(z1, x(Lidx1));
Lidx2 = x >= 1.85; % Logical Index Vector
z2 = polyfit(x(Lidx2),y(Lidx2),1);
y2_best = polyval(z2, x(Lidx2));
hold on
plot(x(Lidx1),y1_best,'-bp')
plot(x(Lidx2),y2_best,'-gp')
hold off