MATLAB Answers

Calculate R squared from a linear regress

691 views (last 30 days)
JFz on 22 Jan 2018
Commented: Star Strider on 22 Jan 2018
Hi, I have a set of scattered data and I can use the operator "\" to do a linear fit on the data. But is there a simple matlab function to get the R^2? I am trying to skip the calculation shown on page:
BTW, I don't have machine learning toolbox.
Thanks for any help. If there is no simple matlab function, then I will have to try to calculate by using the sample code shown on the above page.


Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 22 Jan 2018
It depends on the regression you’re doing. If you have a simple bivariable (as opposed to multivariable) linear regression, you can simply square one of the off-diagonal elements of the (2x2) matrix returned by corrcoef. It will give the same result.


Show 3 older comments
Star Strider
Star Strider on 22 Jan 2018
As always, my pleasure!
This will provide a sort of computational ‘proof’. It uses polyfit and polyval, not the backslant operator, otherwise being the same:
A = 1:100; % Create Data
B = 1 + 2*A + 10*randn(size(A)); % Create Data
b = polyfit(A, B, 1);
f = polyval(b, A);
Bbar = mean(B);
SStot = sum((B - Bbar).^2);
SSreg = sum((f - Bbar).^2);
SSres = sum((B - f).^2);
R2 = 1 - SSres/SStot
R = corrcoef(A,B);
Rsq = R(1,2).^2
JFz on 22 Jan 2018
Thank you! This really helps a lot.

Sign in to comment.

More Answers (0)




Translated by