Summation of a product of a function and a vector in Sympy
Question:
I want to use the following expression in sympy.
For example I tried this sympy code, but an error has occurred.
from sympy import symbols, Matrix, Sum
n = symbols('n', integer=True, nonnegative=True)
expr = n**3 + 2 * n**2 + 3 * n # f(n)
matrix = Matrix([1, 234, 56, 7, 890]) # A_n
result = Sum(matrix[n] * expr, (n, 0, 4))
>>> TypeError: 'Symbol' object cannot be interpreted as an integer
How can I manage this? (How to use Symbol’s value as an index of Matrix?)
Answers:
You can use symbolic indices with a matrix but you need to use double indices:
In [2]: from sympy import symbols, Matrix, Sum
...:
...: n = symbols('n', integer=True, nonnegative=True)
...: expr = n**3 + 2 * n**2 + 3 * n # f(n)
...: matrix = Matrix([1, 234, 56, 7, 890]) # A_n
...:
...: result = Sum(matrix[n, 0] * expr, (n, 0, 4))
In [3]: result
Out[3]:
4
_______
╲
╲
╲ ⎛⎡ 1 ⎤⎞
╲ ⎜⎢ ⎥⎟
╲ ⎜⎢234⎥⎟
╲ ⎛ 3 2 ⎞ ⎜⎢ ⎥⎟
╱ ⎝n + 2⋅n + 3⋅n⎠⋅⎜⎢56 ⎥⎟[n, 0]
╱ ⎜⎢ ⎥⎟
╱ ⎜⎢ 7 ⎥⎟
╱ ⎜⎢ ⎥⎟
╱ ⎝⎣890⎦⎠
╱
‾‾‾‾‾‾‾
n = 0
In [4]: result.doit()
Out[4]: 99134
I want to use the following expression in sympy.
For example I tried this sympy code, but an error has occurred.
from sympy import symbols, Matrix, Sum
n = symbols('n', integer=True, nonnegative=True)
expr = n**3 + 2 * n**2 + 3 * n # f(n)
matrix = Matrix([1, 234, 56, 7, 890]) # A_n
result = Sum(matrix[n] * expr, (n, 0, 4))
>>> TypeError: 'Symbol' object cannot be interpreted as an integer
How can I manage this? (How to use Symbol’s value as an index of Matrix?)
You can use symbolic indices with a matrix but you need to use double indices:
In [2]: from sympy import symbols, Matrix, Sum
...:
...: n = symbols('n', integer=True, nonnegative=True)
...: expr = n**3 + 2 * n**2 + 3 * n # f(n)
...: matrix = Matrix([1, 234, 56, 7, 890]) # A_n
...:
...: result = Sum(matrix[n, 0] * expr, (n, 0, 4))
In [3]: result
Out[3]:
4
_______
╲
╲
╲ ⎛⎡ 1 ⎤⎞
╲ ⎜⎢ ⎥⎟
╲ ⎜⎢234⎥⎟
╲ ⎛ 3 2 ⎞ ⎜⎢ ⎥⎟
╱ ⎝n + 2⋅n + 3⋅n⎠⋅⎜⎢56 ⎥⎟[n, 0]
╱ ⎜⎢ ⎥⎟
╱ ⎜⎢ 7 ⎥⎟
╱ ⎜⎢ ⎥⎟
╱ ⎝⎣890⎦⎠
╱
‾‾‾‾‾‾‾
n = 0
In [4]: result.doit()
Out[4]: 99134