Linear fit to data
1,162 ビュー (過去 30 日間)
古いコメントを表示
I have a data series, and I'm trying to fit two straight lines through a certain amount of points (91 data points from 2002 - 2003.5, then another 91 points from 2003.5 onwards)
I was thinking of using polyfit with n=1, but I don't quite understand how to use it. I then need to find the equations of the lines generated in the form y = mx+c, so maybe polyval?
I've attached a figure to demonstrate what I'm trying to achieve.
0 件のコメント
回答 (3 件)
Aniruddha Katre
2017 年 3 月 3 日
You are on the right track. You can use polyfit to fit a trend line to the data. The output of polyfit is a vector of coefficients corresponding to the polynomial you fit to the data. You can then use polyval for those coefficients to create the trend-line to add to the plot.
Your x-data for polyfit will be the dates, and the y-data will be the 91 values that you want to fit a straight line to.
Here's a quick example:
% Create and Plot Raw Data
x = 1:100;
y = 0.25*x + randn(1,100);
plot(x,y,'LineWidth',2)
% Fit line to data using polyfit
c = polyfit(x,y,1);
% Display evaluated equation y = m*x + b
disp(['Equation is y = ' num2str(c(1)) '*x + ' num2str(c(2))])
% Evaluate fit equation using polyval
y_est = polyval(c,x);
% Add trend line to plot
hold on
plot(x,y_est,'r--','LineWidth',2)
hold off
Benjamin
2019 年 12 月 17 日
Hello
I also have the same question of @JDILLA of fitting two line. The provided answer by @Aniruddha was very helpful, however, it does not address the whole question. I do appreciate if anybody knows the way to fit a bilinear line to a dataset given X0 as the intersection?
2 件のコメント
Yaoting Tseng
2020 年 3 月 26 日
I think both JDilla and Benjamin were talking about the so-called "Segmented regression" or "broken line regression". If it is for line fit, then "Segmented regression" becomes "Segmented linear regression". The "2003.5" number mentioned by JDilla is the so-called "breakpoints" which I think is quite subjected to personal decision.
Segmented regression:
See also the "Broken Line Regression"
Hope the questions were answered.
Benjamin
2020 年 3 月 26 日
@Yaoting
Thank you for your response. I actually found a better way, and that's the fmincon commnad in MATLAB. fmincon enables one to fit a multiple lines/curves based on the output of a function such as the error by minimizing it (the error).
here is the MATLAB fmincon command.
Linus Olofsson
2021 年 10 月 19 日
To find the point where the data changes from one line to another the matlab function "findchangepts" can be used. It allows for different settings, one of which is to look for one or more points where the input data changes from one linear data to another.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Linear and Nonlinear Regression についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!