Is this code for plotting linear regression in loglog scale and confidence intervals correct?

3 views (last 30 days)
Dear MatLab users,
I have a bunch of data x and y, I want to do a linear regression of the natural logarithm of my data. Then, I want to plot the original data, the linear fit, and the linear fit plus the standard deviation (i.e. the condifence intervals). I tried several solutions that I found in other answers, but in the end I had to mix a bit of all of them. I THINK I did it correctly, but I would like your opinion. Is my code correct?
N = 1 ;
x = 100*rand(20,1);
y = 100*rand(20,1);
ln_x = log(x) ;
ln_y = log(y) ;
fit_ln_xy = fitlm( ln_x, ln_y ) ;
p = polyfit( ln_x, ln_y , 1) ;
y_fit = polyval( p , ln_x );
loglog( x , y , '*' )
hold on
loglog( x , exp(y_fit) , 'k' , 'linewidth', 1.5)
loglog( x , exp(y_fit + N*fit_ln_xy.RMSE ) , 'b--' , 'linewidth', 1.2)
loglog( x , exp(y_fit - N*fit_ln_xy.RMSE ) , 'r--' , 'linewidth', 1.2)
legend('Original data ' , 'linear fit' , 'linear fit + 1 std' , 'linear fit - 1 std')

Accepted Answer

Gaurav Garg
Gaurav Garg on 29 Dec 2020
Hi Gianluca,
Yes, the code seems to be correct.
Moreover, you can look at the documentation on how to train/test data using linear regression and some other functions you can use here.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!