MATLAB: Using polyfit to fit 5 individual lines that intersect the y-axis

MATLABplotpolyfit

I am working on plotting straight lines through the y-axis of a specific data set based on an interval on the x-axis of 50. The range on the x-axis is 0 to 250 (km).
A = importdata('data.txt');
x = A(:,1);
y = A(:,2);
p = polyfit(x,y,2);
x2 = 0:50:250;
y2 = polyval(p,x2);
plot(x,y,'o',x2,y2);

Best Answer

A = importdata('VERY_EXPENSIVE.txt');
x = A(:,1);
y = A(:,2) ;
%
xi = 0:50:250 ;
xi(1) = min(x) ; xi(end) = max(x) ;
yi = interp1(x,y,xi) ;
C = zeros(5,1) ; % y-intercept
hold on
for i = 1:5
x1 = x(x>=xi(i) & x<xi(i+1)) ;
y1 = interp1(x,y,x1) ;
p = polyfit(x1,y1,1) ;
C(i) = p(2) ;
y2 = polyval(p,x1) ;
plot(x1,y1,'.') ;
plot(x1,y2,'-') ;
end