8
$\begingroup$

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?

$\endgroup$
12
  • $\begingroup$ Check this out, particularly the part on sparse arrays $\endgroup$
    – Rojo
    May 26, 2014 at 19:10
  • 2
    $\begingroup$ @Rojo I am getting old $\endgroup$
    – Nasser
    May 26, 2014 at 19:36
  • 1
    $\begingroup$ ... and I am already reading it, and thank both of you :) $\endgroup$
    – eldo
    May 26, 2014 at 19:37
  • 2
    $\begingroup$ 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}]. $\endgroup$
    – Szabolcs
    May 26, 2014 at 19:55
  • 1
    $\begingroup$ @Szabolcs - magic ! answer just arrived :) $\endgroup$
    – eldo
    May 26, 2014 at 22:00

1 Answer 1

10
$\begingroup$

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.