[R] "(de)linearizing" array indices
Tamas Papp
tpapp at axelero.hu
Fri Apr 2 14:15:24 CEST 2004
Hi,
I have a dynamic programming problem with many state variables, let's
call them l, n, m, etc. The transition probabilities are originally
given in an array form, eg
transtition[l,m,n,ll,mm,nn]
give the probability of going from l,m,n to ll,mm,nn.
However, the numerical solution is best handled when I "flatten" the L
x M x N state space into a single one (call it S), ie a linear index,
so I can deal with the problem using simple matrix algebra. After I
get the solution, I need to get back the original state variables.
At the moment I am using two functions like this:
pack <- function(l, m, n) {
(((((l - 1) * M) + m - 1) * N) + n
}
unpack <- function(s) {
s <- s - 1
n <- s %% N + 1
s <- s %/% N
m <- s %% M + 1
l <- s %/% M + 1
list(l=l, m=m, n=n)
}
to convert between S and L x N x M.
Sure, it works, but looks ugly as hell. And I am positive that I am
abusing the R language with the above code. So could somebody give me
a nicer solution?
Thanks,
Tamas
--
Tamás K. Papp
E-mail: tpapp at axelero.hu
Please try to send only (latin-2) plain text, not HTML or other garbage.
More information about the R-help
mailing list