'Can I substitute IndexedBase with numpy array

Can I substitute a IndexedBase with a numpy array to get a new sympy expression? Something like:

import numpy as np
import sympy as sy

A = sy.IndexedBase('A', shape=(5))
k = sy.IndexedBase('k', shape=(5))
i = sy.symbols('i',cls=sy.Idx)

expr1 = sy.Sum(A[i]/sy.exp(sy.I * k[i]),(i,1,5))

kz = np.arange(1,5)

expr2 = expr1.subs(k[:],kz[:])

last line = error.

Thanks!



Solution 1:[1]

This might work for you!

import numpy as np
import sympy as sp
import inspect
i ,m= sp.symbols('i,m', integer=True)

A = sp.IndexedBase('A', shape=(m))
k = sp.IndexedBase('k', shape=(m))
#i = sp.symbols('i',cls=sy.Idx)

expr1 = sp.Sum(A[i]/sp.exp(sp.I * k[i]),(i,0,m-1))
print(expr1)
print(expr1.doit())

f_lam = sp.lambdify((A, k,m), expr1, 'numpy')

print(inspect.getsource(f_lam))

M=5
A2 = np.random.uniform(0,1, M)
kz = np.arange(0,M)

print(f_lam(A2,kz,M))

#(-0.08145603175240379+0.27923362018114933j)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Taka