Linear fit to data
조회 수: 1,533 (최근 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.
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!