www.gusucode.com > stats 源码程序 matlab案例代码 > stats/FitLinearMixedEffectsModelExample.m
%% Fit Linear Mixed-Effects Model %% % Load the sample data. load imports-85 %% % Store the variables in a table. tbl = table(X(:,12),X(:,14),X(:,24),'VariableNames',{'Horsepower','CityMPG','EngineType'}); %% % Display the first five rows of the table. tbl(1:5,:) %% % Fit a linear mixed-effects model for miles per gallon in the city, with % fixed effects for horsepower, and uncorrelated random effect for intercept % and horsepower grouped by the engine type. lme = fitlme(tbl,'CityMPG~Horsepower+(1|EngineType)+(Horsepower-1|EngineType)'); %% % In this model, |CityMPG| is the response variable, horsepower is the predictor % variable, and engine type is the grouping variable. The fixed-effects % portion of the model corresponds to |1 + Horsepower|, because the intercept % is included by default. %% % Since the random-effect terms for intercept and horsepower are uncorrelated, % these terms are specified separately. Because the second random-effect % term is only for horsepower, you must include a |–1| to eliminate the % intercept from the second random-effect term. %% % Display the model. lme %% % Note that the random-effects covariance parameters for intercept and horsepower % are separate in the display. %% % Now, fit a linear mixed-effects model for miles per gallon in the city, % with the same fixed-effects term and potentially correlated random effect % for intercept and horsepower grouped by the engine type. lme2 = fitlme(tbl,'CityMPG~Horsepower+(Horsepower|EngineType)'); %% % Because the random-effect term includes the intercept by default, you % do not have to add |1|, the random effect term is equivalent to |(1 + % Horsepower|EngineType)|. %% % Display the model. lme2 %% % Note that the random effects covariance parameters for intercept and horsepower % are together in the display, and it includes the correlation (|'corr'|) % between the intercept and horsepower.