When to use indexed variables

6

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?

eldo

Posted 2014-05-26T19:07:08.887

Reputation: 34 072

Check this out, particularly the part on sparse arrays

– Rojo – 2014-05-26T19:10:42.000

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 – 2014-05-26T19:27:55.967

see http://library.wolfram.com/conferences/devconf99/lichtblau/

– Nasser – 2014-05-26T19:30:50.460

@Nasser, you were too slow to post the last link – Rojo – 2014-05-26T19:34:55.470

1@Rojo I am getting old – Nasser – 2014-05-26T19:36:28.090

1... and I am already reading it, and thank both of you :) – eldo – 2014-05-26T19:37:41.213

2Indexed 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 – 2014-05-26T19:55:04.077

Not necessarily a duplicate, but related

– bobthechemist – 2014-05-26T21:17:24.657

@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 – 2014-05-26T21:25:41.243

1@Szabolcs - magic ! answer just arrived :) – eldo – 2014-05-26T22:00:28.063

@Szabolcs please consider expanding on your comment as an answer, even if CW. – Verbeia – 2014-06-03T10:26:22.800

@Verbeia You're right, I should be better about this ... done. – Szabolcs – 2014-06-03T14:38:52.137

Answers

8

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

Posted 2014-05-26T19:07:08.887

Reputation: 213 047