I would like to initialize an array of size K of matrixes of size QxK where for the kth element of the array, the kth column of the matrix is 0. So far I’ve tried initializing a vector of size QK(K-1) and then create a new array in the transformed parameter block that I fill as I want but that fails because I can’t slice the original vector of parameters properly. Is there any easy fix to this for Q>0 and K > 1? I attached an example for reference! Thanks! 22%20PM|547x499
Does simple for loop work?
matrix[Q,K] X[K];
for (k in 1:K) {
for (q in 1:Q) {
X[k,q,k] = 0;
}
}
To my knowledge, I can’t overwrite elements of a parameter object in the transformed parameters block. I may be wrong though. Something I did consider was to initialize
parameters {
matrix[Q, K] lambda[K];
}
transformed parameters {
matrix[Q,K] lambda_prime[K];
lambda_prime = lambda;
for (k in 1:K) {
for (q in 1:Q) {
lambda_prime[k,q,k] = 0;
}
}
but then there would be K parameters that would just float freely and this seems like a less than ideal solution.
For problems like this, I just initialize a vector with as many elements as I actually need. Then ‘unroll’ them into the shape I need in transformed parameters.
As in, vector in parameters{}, then matrix in transformed parameters {}. Then loop over the matrix elements, adding each vector element where they should go. Something like:
int count = 1;
for(i in 1:I){
for(j in 1:J){
if(i == j){mat[i,j] == 0}
else {
mat[i,j] = vec[count]; count += 1;
}
}
}
Thanks. My bad. I tried that but started with:
transformed parameters {
int counter;
counter = 1;
}
which threw the error: “Parameters or transformed parameters cannot be integer or integer array; found int variable declaration, name=counter”. I will try that. Thanks a lot!
Ah, you need to do it within another scope.
transformed parameters {
matrix[dims,here] mat;
{
int count = 1;
putForloopHere
}
}
This seems to have worked (at least it doesn’t throw any errors yet).
parameters {
vector[Md_var * K * (K - 1)] lambda;
}
transformed parameters {
matrix[Md_var, K] lambda_prime[K];
{
int count = 1;
for (i in 1:K){
for (j in 1:K){
for (q in 1:Md_var){
if (i == j){
lambda_prime[i, q, j] = 0;
} else {
lambda_prime[i, q, j] = lambda[count]; count += 1;
}
}
}
}
}
}