2
$\begingroup$

I have a lot of elements of this kind: a[1], a[2], a[3], ... I would like to rename each of them as follows: a[1]=a1, a[2]=a2, a[3]=a3, ...

The elements a1, a2, a3,... differ from each other only by the string type number, so it is not very clear how to apply Table to them, for example.

Is it possible to do this kind of renaming in some loop?

$\endgroup$
4

1 Answer 1

4
$\begingroup$

Not sure if this works in your context, but if you have no reason to distinguish the "atomic" symbol from the bracket expression, you could just create down values:

a[id_] := Symbol["a" <> ToString[id]]

Once you do that, you won't have to do any replacing, the evaluation engine will apply the transformation for you wherever the bracket expressions occur.

a[5]
(* a5 *)

(* but later ...*)
a5 = 17;
a[5]
(* 17 *)

(* or similarly ...*)
a[5] = 17;
a5
(* 17 *)

(* and also ... *)
Array[a, 5]
(* {a1, a2, a3, a4, 17} *)

(* and also ...*)
Table[a[i], {i, 1, 5}]
(* {a1, a2, a3, a4, 17} *)
$\endgroup$
1
  • 2
    $\begingroup$ It may be relevant to read this answer by Leonid Shifrin arguing that "Using strings and subsequently ToString - ToExpression just to generate variable names is pretty much unacceptable, or at the very least should be the last thing you try" . $\endgroup$
    – rhermans
    May 18 at 8:00

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.