Search code examples
pythonnumpytheano

Theano matrix composed of theano scalars


How can I create a theano matrix composed of theano scalars? The following code creates a numpy array composed of theano scalars. But I want to have a theano matrix instead.

C = T.cos
S = T.sin
q = T.fscalar(name="q%d"%self.i)

names = ['x','y','z']
Sx,Sy,Sz = map(lambda name: T.fscalar(name=name),names)

self.mat = np.array([[C(q),-S(q)*C(alpha),S(q)*S(alpha),a*C(q)+Sx],
                    [S(q),C(q)*C(alpha),-C(q)*S(alpha),a*S(q)+Sy],
                    [0,S(alpha),C(alpha),d+Sz],
                    [0,0,0,1]])

Solution

  • You can use theano.tensor.stacklists in much the same way as you would use np.array to construct a normal numpy array:

    import numpy as np
    import theano
    from theano import tensor as te
    
    a = te.fscalar("a")
    b = te.fscalar("b")
    M = te.stacklists([[a, b], [b, a]])
    
    f = theano.function([a, b], M)
    
    print(f(1.0, 2.0))
    # [[ 1.  2.]
    #  [ 2.  1.]]
    

    You could achieve the same result by using theano.tensor.stack or theano.tensor.concatenate to construct a 1D vector from your scalars, then using its reshape method to reshape it into a matrix/tensor with your desired dimensions.