Contents
Read in small car dataset and plot mpg vs. weight
load carsmall whos isdata = isfinite(MPG)&isfinite(Weight)&isfinite(Horsepower); y = MPG(isdata); x = Weight(isdata); N = length(y) clf subplot(2,2,1) plot(x,y,'x') xlabel('weight [lb]') ylabel('MPG') hold on Name Size Bytes Class Attributes Acceleration 100x1 800 double Cylinders 100x1 800 double Displacement 100x1 800 double Horsepower 100x1 800 double MPG 100x1 800 double Mfg 100x13 2600 char Model 100x33 6600 char Model_Year 100x1 800 double Origin 100x7 1400 char Weight 100x1 800 double N = 93
Linear regression analysis
r = corrcoef(x,y) r = r(1,2) title(['r = ' num2str(0.01*round(r*100))]) xbar = mean(x); ybar = mean(y); sigx = std(x); sigy = std(y); a1 = r*sigy/sigx yfit = ybar + a1*(x - xbar); plot(x,yfit,'k-') r = 1.0000 -0.8591 -0.8591 1.0000 r = -0.8591 a1 = -0.0086
Use Matlab regress function
X = [x ones(N,1)]; a = regress(y,X) plot(x,X*a,'r-'); a = -0.0086 49.23