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

    %% Fit Linear Regression Using Specified Model Formula  
% Fit a linear regression model using a model formula specified by
% Wilkinson notation.
%% 
% Load the sample data. 
load carsmall  

%% 
% Store the variables in a table. 
tbl = table(Weight,Acceleration,Model_Year,MPG,'VariableNames',{'Weight','Acceleration','Model_Year','MPG'});  

%% 
% Fit a linear regression model for miles per gallon (MPG) with weight and
% acceleration as the predictor variables. 
lm = fitlm(tbl,'MPG~Weight+Acceleration') 

%%
% The $p$-value of 0.18493 indicates that |Acceleration| does not have a
% significant impact on |MPG|.  

%% 
% Remove |Acceleration| from the model, and try improving the model by adding
% the predictor variable |Model_Year|. First define |Model_Year| as a nominal
% variable. 
tbl.Model_Year = categorical(tbl.Model_Year);
lm = fitlm(tbl,'MPG~Weight+Model_Year') 

%%
% Specifying |modelspec| using Wilkinson notation enables you to update
% the model without having to change the design matrix. |fitlm| uses only
% the variables that are specified in the formula. It also creates the necessary
% two dummy indicator variables for the categorical variable |Model_Year|.