# When to use indexed variables

Still learning the fundamentals of the language I would like to ask you what advantages there might be in writing something like:

a[1] = 2;
a[2] = 4;
a[3] = "x";


It seems to me that it is always better to write

a = {2, 4, "x"};


Do you know about any practical constructs where indexed variables would offer an advantage?

• Check this out, particularly the part on sparse arrays
– Rojo
Commented May 26, 2014 at 19:10
• @Rojo I am getting old Commented May 26, 2014 at 19:36
• ... and I am already reading it, and thank both of you :)
– eldo
Commented May 26, 2014 at 19:37
• Indexed variables can be used symbolically. You can Solve[a[1]^2==2, a[1]] but you can't Solve[a[[1]]^2==2, a[[1]] ]. This is what we typically use when we don't know the number of symbolic variables we need beforehand. I would sometimes define a 3 by 3 matrix with explicit symbolic elements as Array[a, {3,3}]. Commented May 26, 2014 at 19:55
• @Szabolcs - magic ! answer just arrived :)
– eldo
Commented May 26, 2014 at 22:00

## 1 Answer

Indexed variables can be used in symbolic calculations. They're useful when the number of variables used needs to be changed programmatically.

Here's an example:

vars = Array[a, 3]
(* {a[1], a[2], a[3]} *)

Minimize[vars.vars, vars]
(* {0, {a[1] -> 0, a[2] -> 0, a[3] -> 0}} *)


They can also be used to emulate sparse arrays, as described here.