I want to use the following expression in sympy.
For example I tried this sympy code, but an error has occurred.
JavaScript
x
9
1
from sympy import symbols, Matrix, Sum
2
3
n = symbols('n', integer=True, nonnegative=True)
4
expr = n**3 + 2 * n**2 + 3 * n # f(n)
5
matrix = Matrix([1, 234, 56, 7, 890]) # A_n
6
7
result = Sum(matrix[n] * expr, (n, 0, 4))
8
>>> TypeError: 'Symbol' object cannot be interpreted as an integer
9
How can I manage this? (How to use Symbol’s value as an index of Matrix?)
Advertisement
Answer
You can use symbolic indices with a matrix but you need to use double indices:
JavaScript
1
30
30
1
In [2]: from sympy import symbols, Matrix, Sum
2
:
3
n = symbols('n', integer=True, nonnegative=True) :
4
expr = n**3 + 2 * n**2 + 3 * n # f(n) :
5
matrix = Matrix([1, 234, 56, 7, 890]) # A_n :
6
:
7
result = Sum(matrix[n, 0] * expr, (n, 0, 4)) :
8
9
In [3]: result
10
Out[3]:
11
4
12
_______
13
╲
14
╲
15
╲ ⎛⎡ 1 ⎤⎞
16
╲ ⎜⎢ ⎥⎟
17
╲ ⎜⎢234⎥⎟
18
╲ ⎛ 3 2 ⎞ ⎜⎢ ⎥⎟
19
╱ ⎝n + 2⋅n + 3⋅n⎠⋅⎜⎢56 ⎥⎟[n, 0]
20
╱ ⎜⎢ ⎥⎟
21
╱ ⎜⎢ 7 ⎥⎟
22
╱ ⎜⎢ ⎥⎟
23
╱ ⎝⎣890⎦⎠
24
╱
25
‾‾‾‾‾‾‾
26
n = 0
27
28
In [4]: result.doit()
29
Out[4]: 99134
30