How to calculate a line-of-best-fit equation (y=mx+b) from a simple x-y dataset, and then to use this equation to calculate r-square?
2 views (last 30 days)
Show older comments
Hi,
As stated in the title, I am trying to calculate a line-of-best-fit equation (y=mx+b) from a simple x-y dataset, and then to use this equation to calculate r-square.
At the moment I have the following syntax defining the x & y variables:
x1=dat(:,8); y1=dat(:,14);
But I am unsure of where to go from here. I have been searching these forums & MATLAB Help but I have been unable to find a workable solution.
Therefore my 2 questions are: 1. How do I use MATLAB to get a line-of-best-fit equation for this x-y dataset? 2. How do I use this equation (in conjuction with the x-y dataset) to calculate r-square?
Also, I am new to MATLAB so please go easy on me!
Thanks,
Alan
0 Comments
Accepted Answer
Sean de Wolski
on 16 Jun 2011
doc polyfit
and then
doc polyval
doc corrcoef
like magic!
Welcome to MATLAB Answers!
2 Comments
More Answers (2)
Matt Tearle
on 16 Jun 2011
Approach 1: what Sean said. (Note corrcoef gives the correlation coefficient r, not the coefficient of determination r^2)
Approach 2: use regress, if you have Statistics Toolbox. This allows all sorts of fancy stuff beyond just a fit, as well as post-fit diagnostics.
Approach 3: DIY:
F = [x1.^0 x1]; % make design matrix [1,x]
c = F\y1 % get least-squares fit
res = y1 - F*c; % calculate residuals
r2 = 1 - var(res)/var(y) % calculate R^2
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!