Fitting a straight line to a specific region of the graph

26 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Star Strider
Star Strider el 7 de Jul. de 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 comentarios
Luna Häring
Luna Häring el 7 de Jul. de 2022
Thank you so much, it worked!!!
Star Strider
Star Strider el 7 de Jul. de 2022
My pleasure!
If my Answer helped you solve your problem, please Accept it!
.

Iniciar sesión para comentar.

Más respuestas (1)

Image Analyst
Image Analyst el 7 de Jul. de 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)

Categorías

Más información sobre 2-D and 3-D Plots en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by