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""ML" (maximum likelihood, the
default) or "REML" (restricted maximum likelihood)."FixedEffectPredictors"{"x1", …, "xp"})."RandomEffectPredictors"z1, z2, …)."RandomEffectGroups"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