TestGuest
TestGuest

Reputation: 603

plotting linear regression results in MATLAB

I am using MATLB's fitlm function to fit a linear regression to my data. This is done quite easily. Where I am not yet so sure is how to plot my data. For instance from the regression table, if you run the code below, I would think that the regression line would have intercept = 0.023851 and slope = 0.56421. However, when I follow the instructions of MATLAB to determine intercept and slope (see code below), I get other values. Which are correct, and why so?

x = [0.0001;0.066578214;0.09611659;0.075839223;0.125;0.037889785;0.070220426;0.070648;0.082886425;0.095050538;0.058966667;0.0456;0.070994624;0.048540228;0.06561828;0.053916667;0.035954301;0.037634409;0.044335551;0.061270917;0.163333333;0.079986559;0.070616667]

y = [0.082;0.0452;0.072340;0.0543;0.0932;0.0321;0.078;0.06021;0.0734;0.103;0.0436;0.0482;0.08732;0.05421;0.0589;0.04321;0.043215;0.054321;0.05467;0.0432;0.109;0.0723;0.09821]

mdl = fitlm(x,y,'linear','RobustOpts','on')

%% plot raw data
hold on

plot(x,y,'*') % plot datapoints

%% as suggested by matlab on https://ch.mathworks.com/help/matlab/data_analysis/linear-regression.html
X = [ones(length(x),1) x];
b = X\y % this is however another intercept as seen in the table!

yCalc2 = X*b;
plot(x,yCalc2,'-')
legend('Data','Slope','Slope & Intercept','Location','best');

Upvotes: 1

Views: 825

Answers (1)

PawelK
PawelK

Reputation: 396

You are calling mdl with RobustOpts value-pair set to on. This will cause the function to use robust fitting function. Therefore the result will be, in general, different than that of least-squares method. You can try running mdl = fitlm(x,y,'linear','RobustOpts','off') and see that result is the same as using \ operator (least squares). It is impossible to say which values are "correct", they are just obtained using different method i.e. optimising different fitting function.

Upvotes: 2

Related Questions