8

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?

rhermans
  • 36,518
  • 4
  • 57
  • 149
eldo
  • 67,911
  • 5
  • 60
  • 168
  • Check this out, particularly the part on sparse arrays – Rojo May 26 '14 at 19:10
  • Indexed variables can be used as dictionary table. So anywhere you might need a dictionary table, they are useful. http://en.wikipedia.org/wiki/Associative_array – Nasser May 26 '14 at 19:27
  • see http://library.wolfram.com/conferences/devconf99/lichtblau/ – Nasser May 26 '14 at 19:30
  • @Nasser, you were too slow to post the last link – Rojo May 26 '14 at 19:34
  • 2
    @Rojo I am getting old – Nasser May 26 '14 at 19:36
  • 1
    ... and I am already reading it, and thank both of you :) – eldo May 26 '14 at 19:37
  • 2
    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}]. – Szabolcs May 26 '14 at 19:55
  • Not necessarily a duplicate, but related – bobthechemist May 26 '14 at 21:17
  • @Szabolcs - Thanks, that was an easy to understand example. Since I regularly read your answers on all topics, I would like to ask you a favour: A couple of days ago another newbie asked an interesting question: link. However, he never got an answer from you experts. Would you please have a short look on this question? – eldo May 26 '14 at 21:25
  • 1
    @Szabolcs - magic ! answer just arrived :) – eldo May 26 '14 at 22:00
  • @Szabolcs please consider expanding on your comment as an answer, even if CW. – Verbeia Jun 03 '14 at 10:26
  • @Verbeia You're right, I should be better about this ... done. – Szabolcs Jun 03 '14 at 14:38

1 Answers1

10

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.

Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263