# What is the most efficient way to turn a metric formula into a metric tensor?

I have a metric formula:

ds=(-dt^2)*(c3+a3*t)^2+(dxC^2*(t0^2+t1^2)^2)/(4*t0^4)+
(dxM^2*(t0^2+t1^2)^2)/(4*t0^4)+(dxY^2*(t0^2+t1^2)^2)/(4*t0^4)


How do I turn this into a matrix (metric tensor)? My best attempt so far is:

g = {{Coefficient[ds, dt^2], 0, 0, 0},
{0,Coefficient[ds, (dxC)^2], 0, 0},
{0, 0, Coefficient[ds, (dxM)^2], 0},
{0, 0, 0, Coefficient[ds, (dxY)^2]}}


But this seems clumsy - forcing each of the components into the matrix. Is there a more elegant way?

You need CoefficientArrays:

CoefficientArrays[ds, {dt, dxC, dxM, dxY}] // Last
% // MatrixForm


First define the metric tensor G with unassigned values via G=Array[g,{4,4}]. I'll use $$(-,+,+,+)$$ for the metric signature, so let dx={-dt,dxC,dxM,dxY}. Then Sum[G[[i, j]]*dx[[i]]*dx[[j]], {i, 4}, {j, 4}] gives you the metric, which should be equal to ds.

Define the coefficients relative to g[i,j] or Flatten@G via

forms = Coefficient[Sum[G[[i, j]]*dx[[i]]*dx[[j]], {i, 4}, {j, 4}], Flatten@G, 1];


which gives you every symbolic differential form appearing in G. Now use forms with ds to list the components of the metric:

coeff = Table[Coefficient[ds, forms[[i]], 1], {i, Length@forms}];


and define the g's via

MapThread[(#1 = #2) &, {Flatten@G, coeff}];


To check, just input G

In[7]:= G

Out[7]= {{-(c3 + a3 t)^2, 0, 0, 0}, {0, (t0^2 + t1^2)^2/(4 t0^4), 0, 0}, {0,
0, (t0^2 + t1^2)^2/(4 t0^4), 0}, {0, 0, 0, (t0^2 + t1^2)^2/(
4 t0^4)}}


One approach is to replace each dt^2 etc. in the original expression by the matrix expression for the appropriate symmetric 2-tensor.

For this we first define a list of symbols used for the 1-forms,

oneformsymbols = {dt, dxC, dxM, dxY};


and a list of corresponding vectors,

oneforms = IdentityMatrix[4];


From these we construct a list of replacement rules for the 2-tensors

replacementrules = Flatten[
Table[
oneformsymbols[[i]] oneformsymbols[[j]] ->
Normal@Symmetrize@TensorProduct[oneforms[[i]], oneforms[[j]]]
,
{i, 4},
{j, 1, i}
]
, 1]


With these replacement rules in hand one can generate the matrix of metric components from the line element ds by

ds /. replacementrules


Note that this setup can also deal with metrics with off-diagonal elements.