www.gusucode.com > stats 源码程序 matlab案例代码 > stats/OrdinaryLeastSquaresIllustrationExample.m

    %% Ordinary Least Squares Illustration
%%
% For illustration, randomly generate input and corresponding output data
% using the linear function $y_i = 3 + 2x_i + \varepsilon_i$, where
% $x_i$ and $\varepsilon_i$ are random Gaussian variables with mean 0 and
% standard deviation 1.  Plot the data. The coefficient choices in this
% example are arbitrary.

% Copyright 2015 The MathWorks, Inc.

n = 20; % Sample size
rng(1); % For reproducibility

x = randn(n,1);
y = 3 + 2*x + randn(n,1);

figure
hold on
plot(x,y,'o');
xlabel('x');
ylabel('y');
%%
% Plot three lines that could describe the relationship between $x$ and
% $y$.
x1 = [-2,2.5];
y1 = 3*x1;
y2 = 2 + 2.5*x1;
y3 = 3.5 + 1.5*x1;

plot(x1,[y1;y2;y3]);
legend('Data','y1','y2','y3','Location','Best')
hold off;
%%
% Some of the lines seem to fit to the data better than others.  These
% three are just examples, but you can imagine many more that might fit to
% the data better.
%%
% Plot the vertical distances from the line $y3$ to each data point.
xVert = [x,x]';
yVert = [y,3.5 + 1.5*x]';

figure;
plot(x,y,'o');
hold on;
plot(x1,y3,'r');
plot(xVert,yVert,'k--')
xlabel('x');
ylabel('y');
hold off;
%%
% Ordinary least squares finds the line that minimizes the sum of the
% squared, vertical distances between each possible line and the data.