# Fitting a straight line to a specific region of the graph

12 views (last 30 days)
Luna Häring on 7 Jul 2022
Commented: Star Strider on 7 Jul 2022
Hello, I want to fit a polynomial of 1 degree to a graph. The linear function should only be fittet to a certain region which I determined with T. Somehow it won't work and I can't figure out why.
%Choosing section for the linear fit (preperiod)
T=(0:67.842);
xpreperiod= xm(T);
ypreperiod= ym(T);
%erforming a linear fit using polynomial of 1 degree
%p beeing the coefficients and S beeing the error
[p, S]=polyfit(xpreperiod,ypreperiod,1);
fitT=polyval(p,xpreperiod)
plot(xm,ym,'b') % plotting original data in blue
plot(xpreperiod,fitT,'r') % plotting to fitted line in red

Star Strider on 7 Jul 2022
I suspect the problem is in using‘T’ as a subscript, since subscript values must be integers greater than 0 or logical values.
Assuming that it is a time vector, perhaps —
T=(0:67.842);
Tv = T(T>=0 & T<=67.842); % Create 'logical' Index Vector
xpreperiod= xm(Tv);
ypreperiod= ym(Tv);
It would be nice to have your data to test this with.
.
Star Strider on 7 Jul 2022
My pleasure!
.

Image Analyst on 7 Jul 2022
Try this:
T = data(:, 1);
ym = data(:, 2);
plot(T, ym, 'b-', 'LineWidth', 2);
grid on;
indexes = T > 0 & T < 67.842;
% Do the fit
coefficients = polyfit(T(indexes), ym(indexes), 1);
% Draw the fitted line.
xFit = T(indexes); % Or T if you just want to see the line over the whole plot.
yFit = polyval(coefficients, xFit);
hold on;
plot(xFit, yFit, 'r-', 'LineWidth', 2)
fontSize = 20;
xlabel('T', 'FontSize', fontSize)
ylabel('y', 'FontSize', fontSize)
caption = sprintf('y = %f * T + %f', coefficients(1), coefficients(2));
title(caption, 'FontSize', fontSize)