# Function 'cholesky_decompose' producing NaN

Dear Stan Community,

I am making some adjustments to the DCCMGARCH stan model in the R package ‘bmgarch’. I am adding a mixing factor over the mean and the conditional covariance (mixing elements are given as data).

However, in order to mix over the covariance matrix H, I have to perform a cholesky decomposition. But this is producing only NaN values and hence the stan model cannot be optimized.

Could someone maybe help and see where it goes wrong? Many thanks in advance.

Summary of code (full code in attachments) :

``````data {
//...
cov_matrix[nt] B[T];
vector[nt] mu_m[T];
//
}
transformed parameters {
//...
cov_matrix[nt] H[T];
matrix[nt,nt] H_chol[T];
//...
H[t,] = quad_form_diag(R[t,],     D[t,]);  // H = DRD;
H_chol[t,] = cholesky_decompose(H[t,]);
}
}
model{
for(t in 1:T){
print("B[t,]",B[t,])
print("H_chol[t,]",H_chol[t,])
rts[t,] ~ multi_normal(mu_m[t,], H_chol[t,]* B[t,] * (H_chol[t,])');
}
}
``````

DCCMGARCH.stan (7.1 KB)

Can you share some dummy data that reproduces the issue?

Yes certainly. I have attached “Sample_Data.csv”.

I have amended the bmgarch function to require input ‘B’ and ‘mu’ (see attachments). This is how i call the function:

``````#Initial settings with no mixing over the H matrix and a 0 mu vector.
mu <- array(rep(0, 600*3), c(600,3));
B <- array(rep(0, 600*3*3), c(600,3,3));
for (i in seq_len(600)){
B[i,,] <- matrix(c(1,0,0,0,1,0,0,0,1),3,3) #identity matrix
}

bmfit_sample_data_v01 <- bmgarch(
Sample_Data,
B = B,
mu = mu,
xC = NULL,
parameterization = "DCC",
P = 1,
Q = 1,
iterations = 100,
chains = 1,
standardize_data = FALSE,
distribution = "Gaussian",
meanstructure = "constant",
sampling_algorithm = "MCMC"
)

``````

Sample_Data.csv (22.3 KB)
bmgarch.R (11.8 KB)

The error is occurring because the assignment to `H_chol` is happening in the loop over `t`:

``````H_chol[t,] = cholesky_decompose(H[t,]);
``````

But that loop starts at `t=2`, so `H_chol[1,]` is not assigned any values and remains initialised to `nan`. To resolve this, simply add the cholesky decompose under the initial assignment of `H[1]`:

``````  H[1] = Qr[1,];
H_chol[1,] = cholesky_decompose(H[1,]);
``````

Thanks a lot for your help!

1 Like