MATLAB: How to get R squared of linear regression using fitlm

fitlmlinear regressionrsquaredstatisticsvariance

I have data with low variances. I fit a linear regression model, and I expect to get high R2 because it is a good fit. But I get very low R squared indicating that I have big variances. So I wonder what is wrong here.
This is my x and y data:
x= [ 0 0 0 0.0136 0.0136 0.0136 0.0304 0.0304 0.0304 0.0938 0.0938 0.0938 0.1505 0.1505 0.1505];
y=[90.0000 91.0000 89.0000 89.3268 87.8679 88.9533 93.7081 87.8315 91.1389 88.8301 90.6050 88.6748 90.5922 89.4413 90.8470];
f1 = fitlm( x,y)
Rsquared=f1.Rsquared.Ordinary
figure; plot(x,y,'or'); ylim([80 100])
___________________________________________
f1 =
Linear regression model:
y ~ 1 + x1
Estimated Coefficients:
Estimate SE tStat pValue
________ _______ _______ __________
(Intercept) 89.722 0.58035 154.6 1.3066e-22
x1 2.304 7.192 0.32036 0.75378
Number of observations: 15, Error degrees of freedom: 13
Root Mean Squared Error: 1.57
R-squared: 0.00783, Adjusted R-Squared: -0.0685
F-statistic vs. constant model: 0.103, p-value = 0.754

Best Answer

Nothing is wrong here, and everything is working as expected. It just shows that a linear model is not a good fit to your data.
x = [ 0 0 0 0.0136 0.0136 0.0136 0.0304 0.0304 0.0304 0.0938 0.0938 0.0938 0.1505 0.1505 0.1505];
y = [90.0000 91.0000 89.0000 89.3268 87.8679 88.9533 93.7081 87.8315 91.1389 88.8301 90.6050 88.6748 90.5922 89.4413 90.8470];
f1 = fitlm( x,y);
y_predict = f1.predict(x')';
Rsquared = f1.Rsquared.Ordinary;
figure; plot(x,y,'or', x,y_predict,'+b-');
Now in contrast, check the Rsquared when data is actually linear
x = [ 0 0 0 0.0136 0.0136 0.0136 0.0304 0.0304 0.0304 0.0938 0.0938 0.0938 0.1505 0.1505 0.1505];
y = 90 + 100*x + randn(size(x))*2; % the data is intentionally generated to be linear with some randomness
f1 = fitlm( x,y);
y_predict = f1.predict(x')';
Rsquared = f1.Rsquared.Ordinary;
figure; plot(x,y,'or', x,y_predict,'+b-');
There is also a valuable lesson about accepting the output of statistical tools, developed by experts over the years, instead of relying on your intuition that data "looks" linear. Otherwise, people will continue to downplay a global pandemic as a hoax while the exponential growth is standing right behind them, about to hit them in their head.
Related Question