# Inserting random variable into a matrix

I’m a beginner with Pymc and unfamiliar with Pytensor. I am trying to write a model with matrices that include both constant and random entries. How can I insert the random entries into a pytensor variable matrix? I find it totally baffling that for a tensorvariable matrix F, F[r,c].set() seems to be a valid function but I can’t find anything about it in the documentation.

Hi there!

Sorry you’re feeling baffled. The function you want is `pt.set_subtensor`, as in:

``````X = pt.zeros((5, 5))
X = pt.set_subtensor(X[0, 1], 1)
X.eval()
>>> Out: array([[0., 1., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])
``````

You can pass any arbitrary symbolic value to the 2nd argument of `set_subtensor`, so this works fine:

``````with pm.Model() as m:
X = pt.zeros((5, 5))
a = pm.Normal('a')
X = pt.set_subtensor(X[0, 1], a)
``````

You can use this to allocate any slice you like, not just single entries. So this also works fine:

``````with pm.Model(coords={'dim':['a', 'b', 'c', 'd', 'e']}) as m:
X = pt.zeros((5, 5))
a = pm.Normal('a', dims=['dim'])
X = pt.set_subtensor(X[0, :], a)
``````

That replaces the entire first row of `X` with iid draws from `a`.

1 Like