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)
%erforming a linear fit using polynomial of 1 degree
%p beeing the coefficients and S beeing the error
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 —
Tv = T(T>=0 & T<=67.842); % Create 'logical' Index Vector
It would be nice to have your data to test this with.
More Answers (1)
Image Analyst on 7 Jul 2022
data = readmatrix('Mehl.txt');
T = data(:, 1);
ym = data(:, 2);
plot(T, ym, 'b-', 'LineWidth', 2);
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);
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)