# how to create, print and use variables using a loop in Mathematica?

I want to create, print and be able to use (i.e. do symbolic operations) variables in Mathematica using a for loop or equivalent.

So, I have a bunch of variables of this form:

$$dS_i = -\beta_i S_i$$ where $i$ is an index.

I would like to end up with the variables defined in the notebook like this:

$$dS_1 = -\beta_1 S_1$$ $$dS_2 = -\beta_2 S_2$$ $$dS_3 = -\beta_3 S_3$$

etc.

So that I can see each of them in my screen and I can actually perform symbolic operations with them (e.g. $dS_1 + dS_2$).

If I do:

Do[Print["dI", i, "= -beta", i, "*S"], {i, 4}]


then I get the printing part but they are not variables, just strings.

I have also tried:

Table[dI[i] = -beta[i]*S, {i, 4}]


which generates the variables but then I don't get to see them on the screen.

• You should consider using [[]] a.k.a Part instead of []. And also this question just needs more details. You can always use the symbolic entities and pipe them to, say, Grid. – Sektor May 15 '15 at 18:34

You could do something like this:

expr[i_] := Defer[dS[i] = -β[i]*S]

Do[expr[i][]; CellPrint@Cell[BoxData@ToBoxes@expr[i], "Output"], {i, 4}]


In the Do loop I evaluate the assignment and also create a cell with the definition. You could use "Input" instead of "Output" if you prefer.

• Thanks Simon, with the Input option this is exactly what I was looking for! – Laura May 15 '15 at 21:06

You could try something like the following:

Table[dS[i] = -β[i]*S[i], {i, 4}];


To see the definitions for dS use the function Definition.

Definition[dS]
(*
dS=-S β

dS=-S β

dS=-S β

dS=-S β
*)


See that you can perform operations on dS.

dS + dS
(* -S β - S β *)


Dos this work

Do[dI[i] = -beta[i]*S; Print["dI", i, "= -beta", i, "*S"], {i, 4}]


Any method that can print what you want has to change the expression to a kid of String. At the end, the printed expression the way you what has to be kind of String

You can try Inactivate

Do[dI[i] = -beta[i]*S; Print[Inactivate[dI[i] = -beta[i]*S]], {i, 4}]

• Thanks Algohi, it kind of works, not exactly what I wanted... If I change what you wrote a bit, like this: Do[dI[i] = -beta[i]*S; Print["dI[", i, "]= -beta", i, "*S"], {i, 4}] the variables in memory match the ones being printed on the screen, but what is printed is still strings, if you understand what I mean... – Laura May 15 '15 at 19:12