0

I would like to define mutliple variables that are labelled by some coefficients, and these variables are not related to each other. The prime example would be the coefficients of an arbitrary multivariate function:

\sum_{i,j,k} c_{i,j,k} G(i, j, k)

In mathematica I simply would write

c[1,1,1] = 1
...
c[1,2,1] = x
...
c[2,3,2] = x^100-x
...
c[10,10,10] = 0

(* Example of use *)
expr = Sum[ c[i,j,k] G(i,j,k), {i,0,10}, {j,0,10}, {k,0,10}}]

where I defined all the coefficients by hand. Now, I am trying to do the same in Python. The way I currently implement it is via a function:

import sympy
x = sympy.Symbol("x")
def coeff(a,b,c):
    if (a,b,c) == (1,1,1): return 1
    ...
    elif (a,b,c) == (1,2,1): return x
    ...
    elif (a,b,c) == (2,3,2): return x**100-x
    ...
    else:
        return None

It seems it will not scale well if there is a large number of coefficients. My first thought to do it in Python was to use lists, but it only works if the labels are sequential, e.g. i=0,1,2,... which is not my case and does not work if the labels are not integers. Dictionaries also seem tempting but also seem quite messy to define and add coefficients after the fact. Is there a best practice to do such a thing in Python?

1 Answer 1

1

Without knowing more about SymPy, it seems like you want a matrix / multi-dimensional array. That could be nested dictionaries -- but in your case I think it's just a dictionary using a tuple of dimensions as the key.

The syntax is virtually identical to your example above.

c = {}
c[1,1,1] = 1
c[1,2,1] = x
c[2,3,2] = x^100-x
c[10,10,10] = 0

The part I'm unsure about is whether the value of x changes over time and is ran as if it were a function. If so, this won't work as the value of x gets staged into the dictionary using whatever its value was at time of being set.

Sign up to request clarification or add additional context in comments.

1 Comment

In this case the value of x does change over time so your answer is perfect, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.