I am looking for a way to generate time-dependent arrays of variable dimensions in Mathematica. For example, if I want an array with 15 variables

x={x1[t], x2[t], x3[t], x4[t], x5[t], x6[t], x7[t], x8[t], x9[t], 
 x10[t], x11[t], x12[t], x13[t], x14[t], x15[t]}.



is thr a way to automate this?

Array[Symbol["x" <> ToString @ #][t] &, 15]

{x1[t], x2[t], x3[t], x4[t], x5[t], x6[t], x7[t], x8[t], x9[t], x10[t], x11[t], x12[t], x13[t], x14[t], x15[t]}

Array[Symbol[StringJoin["y", ToString /@ {##}]][t] &, {2, 2}]

{{y11[t], y12[t]}, {y21[t], y22[t]}}

As rhermans pointed out, a better approach is

Array[x[##][t], 15]

{x[1][t], x[2][t], x[3][t], x[4][t], x[5][t], x[6][t], x[7][t], x[8][t], x[9][t], x[10][t], x[11][t], x[12][t], x[13][t], x[14][t], x[15][t]}


Array[y[##][t], {2,2}]

{{y[1, 1][t], y[1, 2][t]}, {y[2, 1][t], y[2, 2][t]}}

If you want x[1] to appear as x1, say, you can use Format:

Format[x[a_]] := Symbol["x" <> ToString[a]]
Array[x[##][t] &, {5}]

{x1[t], x2[t], x3[t], x4[t], x5[t]}


Format[y[a__]] := Subscript[y, a]
Array[y[##][t] &, {2, 2}] // TeXForm

$ \left( \begin{array}{cc} y_{1,1}(t) & y_{1,2}(t) \\ y_{2,1}(t) & y_{2,2}(t) \\ \end{array} \right)$

  • 1
    $\begingroup$ So you disagree with @LeonidShifrin that says "Using strings and subsequently ToString - ToExpression [or Symbol] just to generate variable names is pretty much unacceptable, or at the very least should be the last thing you try. I don't know of a single case where this couldn't be replaced with a better solution" in this question ? $\endgroup$
    – rhermans
    Jul 19 '18 at 11:48
  • 1
    $\begingroup$ @rhermans, very good point:) Array[x[##][t] &, 15] would also look much cleaner. $\endgroup$
    – kglr
    Jul 19 '18 at 11:52

Based on this question I would go for

Through@Array[x, 15][t]


Through@Flatten[Array[y, {2, 2}]][t]


Array[x[#][t] &, 15]


Array[y[#1, #2][t] &, {2, 2}]

or as suggested by @kglr, very elegant.

Array[y[##][t] &, {2, 2}]

To answer without using strings, you can change the structure slightly:

x[n_] := Array[x[#, t] &, n]

Now you have:

{x[1, t], x[2, t], x[3, t], x[4, t], x[5, t]}

This has the advantage that you can refer to the whole collection of functions using x (with one argument) and can refer to each individual function using x[i,t] (with two arguments). For the 2D case:

y[n_] := Array[y[#1, #2, t] &, {n, n}]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.