Suppose that the variables x
and theta
can take the possible values [0, 1, 2]
and [0, 1, 2, 3]
, respectively.
Let's say that in one realization, x = 1
and theta = 3
. The natural way to represent this is by a tuple (1,3)
. However, I'd like to instead label the state (1,3)
by a single index. A 'brute-force' method of doing this is to form the Cartesian product of all the possible ordered pairs (x,theta)
and look it up:
import numpy as np
import itertools
N_x = 3
N_theta = 4
np.random.seed(seed = 1)
x = np.random.choice(range(N_x))
theta = np.random.choice(range(N_theta))
def get_box(x, N_x, theta, N_theta):
states = list(itertools.product(range(N_x),range(N_theta)))
inds = [i for i in range(len(states)) if states[i]==(x,theta)]
return inds[0]
print (x, theta)
box = get_box(x, N_x, theta, N_theta)
print box
This gives (x, theta) = (1,3)
and box = 7
, which makes sense if we look it up in the states
list:
[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]
However, this 'brute-force' approach seems inefficient, as it should be possible to determine the index beforehand without looking it up. Is there any general way to do this? (The number of states N_x
and N_theta
may vary in the actual application, and there might be more variables in the Cartesian product).