Categories &

Functions List

Function Reference: fitlmematrix

statistics: lme = fitlmematrix (X, y, Z, G)
statistics: lme = fitlmematrix (…, name, value)

Fit a linear mixed-effects model from design matrices.

fitlmematrix (X, y, Z, G) fits the linear mixed-effects model $$ y = X\beta + Zb + \varepsilon $$ with fixed-effects design X, response y, random-effects design Z, and grouping variable G. The random effects b are normally distributed with mean zero and an unstructured covariance Psi (shared across the levels of the grouping variable), and the observation errors are independent N(0, sigma2).

X is an n-by-p numeric matrix and y an n-by-1 response vector. Z is an n-by-q random-effects design and G an n-by-1 grouping variable (numeric, logical, char, cell array of strings, or categorical). To specify several grouping terms, pass Z and G as cell arrays of the same length, one design and one grouping variable per term.

The following name/value pairs are accepted:

"FitMethod"
The estimation criterion, either "ML" (maximum likelihood, the default) or "REML" (restricted maximum likelihood).
"FixedEffectPredictors"
A cell array of p names for the columns of X (default {"x1", …, "xp"}).
"RandomEffectPredictors"
A cell array (one entry per grouping term) of cell arrays naming the columns of each Z (default z1, z2, …).
"RandomEffectGroups"
A cell array of names for the grouping terms (default g1, g2, etc.).

The returned lme is a LinearMixedModel object describing the fitted model: the estimated fixed effects and their statistics (lme.Coefficients), the covariance parameters (covarianceParameters), the random-effects BLUPs (randomEffects), the log-likelihood, and methods for prediction, residuals, and hypothesis tests.

Only the full (unstructured) random-effects covariance is currently supported.

See also: LinearMixedModel, fitlm, parseWilkinsonFormula

Source Code: fitlmematrix

A random-intercept model on a small balanced data set: five subjects measured at four values of a predictor x.

 x = repmat ([1 2 3 4]', 5, 1);
 subject = reshape (repmat (1:5, 4, 1), [], 1);
 y = 2 + 0.8 * x + reshape (repmat ([1 -1 0.5 -0.5 0]', 1, 4)', [], 1) ...
         + 0.1 * sin (1:20)';
 X = [ones(20,1), x];
 lme = fitlmematrix (X, y, ones (20, 1), subject, "FitMethod", "REML");
 beta = fixedEffects (lme);
 [psi, mse] = covarianceParameters (lme);
 printf ("intercept = %.4f, slope = %.4f\n", beta);
intercept = 1.9951, slope = 0.8040
 printf ("between-subject var = %.4f, residual var = %.4f\n", psi{1}, mse);
between-subject var = 0.6123, residual var = 0.0059