Ask Your Question

How to define multiple objects with a for loop?

asked 2019-06-06 19:50:09 -0500

sum8tion gravatar image

While this question can be answered in greater generality, I'm specifically writing a program in which I need to systematically define and label a bunch of differential forms.
Suppose I have the set up

M = manifold(2, 'M')
U = M.open_subset('U')
c_xy.<x,y> = U.chart()
eU = c_xy.frame()

Now I want to have a bunch of differential forms indexed by 2 numbers (as they will be going into a matrix).
Instead of writing them all out by hand as

a_00 = M.diff_form(1, name='a_00')
a_01 = M.diff_form(1, name='a_01')
a_33 = M.diff_form(1, name='a_33')

Is there any way I can write a for loop to build these for me? I've seen a similar question asked here: but I'm not sure how to extend to the 2-index case. Also, the linked example works for symbols, but I don't know if this can be made to work for defining a list of objects like differential forms.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2019-06-07 01:25:30 -0500

eric_g gravatar image

I would advise to create a nested list of objects:

a = [[M.diff_form(1, name='a_{}{}'.format(i, j), 
                  latex_name='a_{{{}{}}}'.format(i, j)) 
      for j in range(4)] for i in range(4)]

Then you access to a_ij via a[i][j]. For instance (first line is input, second line is output):

1-form a_13 on the 2-dimensional differentiable manifold M



It is possible to dynamically inject names like a_13 in the global namespace, by adding new entries in the dictionary globals(), but this is generally not recommended.

edit flag offensive delete link more


and what if I also wanted to define a list of variables as in the question I linked to above, but having tow indices?
That is, generating a collection of formal variables g[0][0], g[0][1], ..., g[2][1], g[2][2]?

sum8tion gravatar imagesum8tion ( 2019-06-18 10:13:08 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2019-06-06 19:50:09 -0500

Seen: 60 times

Last updated: Jun 07