Fitting a straight line to a specific region of the graph

12 views (last 30 days)
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

Accepted Answer

Star Strider
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.
.
  4 Comments
Star Strider
Star Strider on 7 Jul 2022
My pleasure!
If my Answer helped you solve your problem, please Accept it!
.

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 7 Jul 2022
Try this:
data = readmatrix('Mehl.txt');
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)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by