7

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]}.

or

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

is thr a way to automate this?

kosa
  • 485
  • 2
  • 10

3 Answers3

5
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]}

and

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]}

or

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

kglr
  • 394,356
  • 18
  • 477
  • 896
  • 1
    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 ? – rhermans Jul 19 '18 at 11:48
  • 1
    @rhermans, very good point:) Array[x[##][t] &, 15] would also look much cleaner. – kglr Jul 19 '18 at 11:52
3

Based on this question I would go for

Through@Array[x, 15][t]

and

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

or

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

and

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

or as suggested by @kglr, very elegant.

Array[y[##][t] &, {2, 2}]
rhermans
  • 36,518
  • 4
  • 57
  • 149
1

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

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

Now you have:

x[5]
{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}]
bill s
  • 68,936
  • 4
  • 101
  • 191