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

    %% Longitudinal Study with a Covariate  

%% 
% Load the sample data. 
load(fullfile(matlabroot,'examples','stats','weight.mat'))

%%
% |weight| contains data from a longitudinal study, where 20 subjects are
% randomly assigned to 4 exercise programs (A, B, C, D), and their weight
% loss is recorded over six 2-week time periods. This is simulated data.  

%% 
% Store the data in a table. Define |Subject| and |Program| as categorical
% variables. 
tbl = table(InitialWeight,Program,Subject,Week,y);
tbl.Subject = nominal(tbl.Subject);
tbl.Program = nominal(tbl.Program);  

%% 
% Fit a linear mixed-effects model where the initial weight, type of program,
% week, and the interaction between the week and type of program are the
% fixed effects. The intercept and week vary by subject. 
%
% |fitlme| uses program A as a reference and creates the necessary dummy
% variables $I$[.]. Since the model already has an intercept, |fitlme| only
% creates dummy variables for programs B, C, and D. This is also known as
% the |'reference'| method of coding dummy variables. This model corresponds to
%
% $$\begin{array}{l}
% {y_{im}} = {\beta _0} + {\beta _1}I{W_i} + {\beta _2}Wee{k_i} + {\beta _3}I{\left[ {PB} \right]_i} + {\beta _4}I{\left[ {PC} \right]_i} + {\beta _5}I{\left[ {PD} \right]_i}\\
% \quad \quad  + {\beta _6}\left( {Wee{k_i}*I{{\left[ {PB} \right]}_i}} \right) + {\beta _7}\left( {Wee{k_i}*I{{\left[ {PC} \right]}_i}} \right) + {\beta _8}\left( {Wee{k_i}*I{{\left[ {PD} \right]}_i}} \right)\\
% \quad \quad  + b{}_{0m} + \,{b_{1m}}Wee{k_{im}} + {\varepsilon _{im}},
% \end{array}$$
%
% where $i$ = 1, 2, ..., 120, and $m$ = 1, 2, ..., 20. $\beta_{j}$
% are the fixed-effects coefficients, $j$ = 0, 1, ..., 8, and $b_{1m}$
% and $b_{1m}$ are random effects. $IW$ stands for initial
% weight and I[.] is a dummy variable representing a type of program. For
% example, $I[PB]_{i}$ is the dummy variable representing
% program B. The random effects and observation error have these prior distributions:
% $b_{0m}$ ~ N(0, $\sigma^{2}_{0}$),
% $b_{1m}$ ~ N(0, $\sigma^{2}_{1}$),
% and $\epsilon_{im}$ ~ N(0, $\sigma^{2}$). 
lme = fitlme(tbl,'y ~ InitialWeight + Program*Week + (Week|Subject)') 

%%
% The $p$-values 0.022863 and 0.011567 indicate significant effects of subject
% initial weights and time in the amount of weight lost. The weight loss
% of subjects who are in program B is significantly different relative to
% the weight loss of subjects who are in program A. The lower and upper
% limits of the covariance parameters for the random effects do not include
% 0, thus they are significant. You can also test the significance of the
% random effects using the |compare| method.