Ask Your Question
1

How to define multiple objects with a for loop?

asked 2019-06-07 02:50:09 +0100

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: https://ask.sagemath.org/question/792... 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
2

answered 2019-06-07 08:25:30 +0100

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):

a[1][3]
1-form a_13 on the 2-dimensional differentiable manifold M

and

latex(a[1][3])
a_{13}

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

Comments

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 17:13:08 +0100 )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

Stats

Asked: 2019-06-07 02:50:09 +0100

Seen: 894 times

Last updated: Jun 07 '19