Multiple regressions in a scatter plot

I have several scatter plots that look like a hockey stick, or even more crooked, and I want to fit a linear trend in each of the segments. Is there a way to get this? Thanks

답변 (3개)

bym
bym 2011년 9월 24일

1 개 추천

one way: [edit: added pp]
pp = mkpp([0 5 10],[[.5,0];[4,2.5]]);
x = (0:.1:10)';
y = ppval(pp,x);
y = y+rand(101,1); % make hockey stick example data
plot(x,y,'b.') % plot data
hold on
x1 = x(1:50); x1 = [ones(size(x1)),x1];
x2 = x(51:101); x2 = [ones(size(x2)),x2];
y1 = y(1:50); y2 = y(51:101);
c1 = x1\y1; c2 = x2\y2; % least squares coefficients
yhat1 = x1*c1; yhat2 = x2*c2; % fits
plot(x(1:50),yhat1,'--',...
x(51:101),yhat2,'--','LineWidth',2)
[edit]
% R^2 calculation
res1 = y1-yhat1; res2 = y2-yhat2;
r_sq1 = 1-(sum(res1.^2)/sum((y1-mean(y1)).^2));
r_sq2 = 1-(sum(res2.^2)/sum((y2-mean(y2)).^2));

댓글 수: 3

the cyclist
the cyclist 2011년 9월 25일
What is "pp" in your second line?
Walter Roberson
Walter Roberson 2011년 9월 25일
Looks like a pp = polyfit() call went missing, but I don't know what parameters were intended.
bym
bym 2011년 9월 25일
sorry about that, sloppy cut and paste. Thanks for pointing that out

댓글을 달려면 로그인하십시오.

the cyclist
the cyclist 2011년 9월 23일

0 개 추천

One way to do this would be with the nlinfit() function of the Statistics Toolbox. You could define a function that is parameterized to be a series of line segments, and then nlinfit() will find the parameters that give the best fit to the data.

댓글 수: 1

Julio
Julio 2011년 9월 23일
The problem is I don't have the statistics toolbar in my university's Matlab

댓글을 달려면 로그인하십시오.

Julio
Julio 2011년 9월 25일

0 개 추천

Thanks a million! it works nice. Although I will have to look manually for the breaks of all the plot, but at least I can do it now. But how can I get now the R^2 of the fits?

카테고리

질문:

2011년 9월 23일

Community Treasure Hunt

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

Start Hunting!

Translated by