Search code examples
pythonloopsvariablessymbolssympy

How to generate symbolic variables in a for loop using Sympy (Python)


Depending on the input of my tool I need multiple variables: A_n, B_n, C_n and D_n for n (integer) in range [1, x] to formulate x equation of the following form:

W(z) = A_n*cosh(beta*z) + B_n*sinh(beta*z) + C_n*cos(beta*z) + D_n*sin(beta*z)

I'm using Sympy, and I cannot find a way to replace n for the integer in range [1, x] and use that symbol (A1, A2, B1, B2, etc.) in a loop (to generate the symbol or for further calculations.

How can I write or call these variables conveniently in a for loop, such that I don't have to write it by hand?


Solution

  • You could use functions with integer arguments to represent your constants or indexed variables. Here is a toy example:

    >>> A,B,C = symbols('A:C', cls=Function)
    >>> eq = A(i)*x + B(i)*y + C(i)
    >>> [eq.subs(i,j) for j in range(2)]
    [x*A(0) + y*B(0) + C(0), x*A(1) + y*B(1) + C(1)]
    

    Those functions can be replaced with values when you known them.

    Instead of using these functions you could used Indexed, too:

    >>> Ai=Indexed('A',i)
    >>> Ai
    A[i]
    >>> _.subs(i,0)
    A[0]