Load the sample data.

load carbig

Fit a linear mixed-effects model for miles per gallon
(MPG), with fixed effects for acceleration, horsepower, and cylinders,
and potentially correlated random effect for intercept and acceleration
grouped by model year.

First, prepare the design matrices for fitting the linear mixed-effects
model.

X = [ones(406,1) Acceleration Horsepower];
Z = [ones(406,1) Acceleration];
Model_Year = nominal(Model_Year);
G = Model_Year;

Now, fit the model using `fitlmematrix` with
the defined design matrices and grouping variables.

lme = fitlmematrix(X,MPG,Z,G,'FixedEffectPredictors',....
{'Intercept','Acceleration','Horsepower'},'RandomEffectPredictors',...
{{'Intercept','Acceleration'}},'RandomEffectGroups',{'Model_Year'});

Create the design matrices that contain the data at which
to predict the response values. `Xnew` must have
three columns as in `X`. The first column must be
a column of 1s. And the values in the last two columns must correspond
to `Acceleration` and `Horsepower`,
respectively. The first column of `Znew` must be
a column of 1s, and the second column must contain the same `Acceleration` values
as in `Xnew`. The original grouping variable in `G` is
the model year. So, `Gnew` must contain values for
the model year. Note that `Gnew` must contain nominal
values.

Xnew = [1,13.5,185; 1,17,205; 1,21.2,193];
Znew = [1,13.5; 1,17; 1,21.2];
Gnew = nominal([73 77 82]);

Generate random responses for the data in the new design
matrices.

rng(123,'twister') % For reproducibility
ysim = random(lme,Xnew,Znew,Gnew)

ysim =
15.7416
10.6085
6.8796

Now, repeat the same for a linear mixed-effects model
with uncorrelated random-effects terms for intercept and acceleration.
First, change the original random effects design and the random effects
grouping variables. Then, fit the model.

Z = {ones(406,1),Acceleration};
G = {Model_Year,Model_Year};
lme = fitlmematrix(X,MPG,Z,G,'FixedEffectPredictors',....
{'Intercept','Acceleration','Horsepower'},'RandomEffectPredictors',...
{{'Intercept'},{'Acceleration'}},'RandomEffectGroups',{'Model_Year','Model_Year'});

Now, recreate the new random effects design, `Znew`,
and the grouping variable design, `Gnew`, using which
to predict the response values.

Znew = {[1;1;1],[13.5;17;21.2]};
MY = nominal([73 77 82]);
Gnew = {MY,MY};

Generate random responses using the new design matrices.

rng(123,'twister') % For reproducibility
ysim = random(lme,Xnew,Znew,Gnew)

ysim =
16.8280
10.4375
4.1027