Is it possible to extract also R^2 value from linear fit between 2 vectors ?

Hello,
I know that it is possible to find fit parameters using polyfit command.
F.e., linearCoefficients = polyfit(x, y, 1)
Is it possible to extract also R^2 value from linear fit between 2 vectors ?
Thank you !

 Accepted Answer

It is, however polyfit wil not do it for you.
Try this:
x = 1:10; % Create ‘x’
y = randn(size(x)) + 0.2*x; % Create ‘y’
linearCoefficients = polyfit(x, y, 1); % Coefficients
yfit = polyval(linearCoefficients, x); % Estimated Regression Line
SStot = sum((y-mean(y)).^2); % Total Sum-Of-Squares
SSres = sum((y-yfit).^2); % Residual Sum-Of-Squares
Rsq = 1-SSres/SStot; % R^2

4 Comments

Thank you very much !!!
Can you please also comment if R^2 result is contained in the following commands ? :
[P,S] = polyfit(X,Y,N) returns the polynomial coefficients P and a
structure S for use with POLYVAL to obtain error estimates for
predictions. S contains fields for the triangular factor (R) from a QR
decomposition of the Vandermonde matrix of X, the degrees of freedom
(df), and the norm of the residuals (normr). If the data Y are random,
an estimate of the covariance matrix of P is (Rinv*Rinv')*normr^2/df,
where Rinv is the inverse of R.
[P,S,MU] = polyfit(X,Y,N) finds the coefficients of a polynomial in
XHAT = (X-MU(1))/MU(2) where MU(1) = MEAN(X) and MU(2) = STD(X). This
centering and scaling transformation improves the numerical properties
of both the polynomial and the fitting algorithm.
My pleasure.
Neither polyfit nor polyval return the value.
The polyfit function optionally returns a covariance matrix (in the ‘S’ output in this example) that can be used to calculate the confidence intervals for the parameters and the regression, although it does not calculate them directly. The polyval function can use these to return a ‘delta’ output that is similar to the confidence intervals on the regression, although not exactly.
My pleasure!
If my Answer helped you solve your problem, please Accept it!

Sign in to comment.

More Answers (1)

As of R2024a, polyfit will actually do this for you.
x = 1:10;
y = randn(size(x)) + 0.2*x;
[linearCoefficients,structOutput] = polyfit(x, y, 1);
Rsq = structOutput.rsquared;

Categories

Find more on Descriptive Statistics and Insights in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!