I would like to dynamically parameterize an array for a state-space model depending on how many states I choose.
I am doing this with a loop –
Q <- function(params,states) {
qmat <- matrix(0,statespace,statespace)
for (i in 1:statespace)
qmat[i,i] <- statshockvar(params[(i-1)*5+1], params[(i-1)*5+2],
params[(i-1)*5+3],states[i])
qmat
}
This function is called many times, as the point of the program is to optimize a paramter set. However, this function setup is slowing down the optimization phase very substantially because this function and a bunch of others like it keep getting called, and they keep redefining the arrays.
How can I define the arrays I need once, dynamically, with the relevant parameters as above, and then be able to call the matrix function with a new set of parameters for optimization?
Thanks!
Edit –
statespace is just an integer describing the number of states to use in the model, say 3/
statshockvar <- function(meanrev,longrun,sigma,sstate) {
longrun*sigma^2/(2*meanrev)*(1-exp(-longrun))^2+sigma^2/longrun*(exp(-longrun) -
exp(-2*longrun))*sstate
}
statshockvar – in this particular example is the discretized variance of a CIR model for the term structure
Edit 2 –
params looks like this – please note these are just arbitrary number
params = c(
0.3275,
0.07,
0.197,
0,
0.05,
0.01,
0.2,
0.3,
0,
0.05,
0.01,
0.1,
0.3,
0,
0.05)
states would be something like this –
states = c(0.07,0.07,0.07)
again these states are arbitrary.
Here’s a solution:
Test with the example parameters: