# How to make formal variables with more than one index?

I'd like to make formal variables that can be multiplied, added etc. but have them labelled by two indices.
Here: https://ask.sagemath.org/question/792... it's done for variables with one index, and I asked a similar question about defining differential forms with multi-labels here: https://ask.sagemath.org/question/468... I see no clear way of merging these two approaches.

edit retag close merge delete

Sort by » oldest newest most voted Consider the following code:

sage: m, n = 3, 2
sage: g = matrix(m+1, n+1, [var("g_{}{}".format(i,j),
....: latex_name="g_{{{}{}}}".format(i,j))
....: for i in [0..m] for j in [0..n]])
sage: g
[g_00 g_01 g_02]
[g_10 g_11 g_12]
[g_20 g_21 g_22]
[g_30 g_31 g_32]


It creates a matrix g of symbolic variables g_00, g_01, etc. You can access each variable either by g_ij or g[i,j].

Edit. To cope with a more general case you can use a dictionary, for example:

sage: m, n, p = 3, 2, 2
sage: g = {(i,j,k): var("g_{}{}{}".format(i,j,k),
....: latex_name="g_{{{}{}{}}}".format(i,j,k))
....: for i in [0..m] for j in [0..n] for k in [0..p]}
sage: g
{(0, 0, 0): g_000,
(0, 0, 1): g_001,
(0, 0, 2): g_002,
(0, 1, 0): g_010,
(0, 1, 1): g_011,
.................................
(3, 2, 0): g_320,
(3, 2, 1): g_321,
(3, 2, 2): g_322}


Variables can be accessed by g_ijk or g[(i,j,k)].

more

Thanks! What if I wanted to make variables with 3 indices? It doesn't seem like the matrix approach would work in that case.