Matthias Schilling
Matthias Schilling

Reputation: 59

sum over matrix entries in sympy 1.0 with python 3.5

I just discovered Sympy so I'm still not quite sure how to best work with it. I have an equation

Image

with X a 20x5 Matrix, Y a 20x1 Matrix/Vektor and beta a 5x1 Matrix/Vektor

However the notation I know only allows me to use the i as a variable, not as a position in a Matrix. Code:

 from sympy import exp, init_printing, sqrt, sin, tan, cos, diff, Sum, Matrix, log, symbols, MatrixSymbol
 init_printing()
 X = MatrixSymbol('X',20,5)
 Y = MatrixSymbol('Y',20,1)
 beta = MatrixSymbol('beta',5,1)
 expr = Sum((Y[i]*exp((Matrix(X[i,:])*Matrix(beta))[0,0])),(i,1,20))

This throws the following Error:

 IndexError: Single index only supported for non-symbolic indices.

Googling it didn't really get me so far, as google always seems to want to talk about numpy instead of sympy. Also, I'm guessing this is all pretty basic, so pls pls share your wisdom ;)

Upvotes: 1

Views: 1814

Answers (1)

Francesco Bonazzi
Francesco Bonazzi

Reputation: 1957

Use IndexedBase:

In [1]: X = IndexedBase("X")

In [2]: Y = IndexedBase("Y")

In [4]: beta = IndexedBase("beta")

In [5]: expr = Sum(Y[i]*exp(Sum(X[i, j]*beta[j], (j, 1, 5))), (i, 1, 20))

In [7]: pprint(expr)
  20                                 
_____                                
\    `                               
 \        5                          
  \      __                          
   \     \ `                         
    )     )   beta[j]*X[i, j]        
   /     /_,                         
  /     j = 1                        
 /     e                     *Y[i]
/____,                               
i = 1        

Also take care that SymPy interprets functions mathematically. That is, the exponential of a matrix is not the exponential of its components, rather it is the matrix to which to Taylor expansion of the exponential converges. It only makes sense for square matrices.

Upvotes: 4

Related Questions