2

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?

Mam Mam
  • 1,843
  • 2
  • 9
  • 3
    try Symbol[SymbolName[#[[0]]] <> ToString[#[[1]]]] & /@ yourlist or ReplaceAll[f_[i_Integer] :> Symbol@StringJoin[ToString /@ {f, i}]]@lyourlist – kglr May 17 '23 at 21:57
  • 1
    When you say "a lot", do you mean "a lot of a, b, c..." (so, you may have only three as: a[1], a[2], a[3], but you also have three each for 20 different symbols) or do you mean you have a[1]...a[500] and only a few different head-symbols? – lericr May 17 '23 at 22:04
  • @kglr, thanks a lot! – Mam Mam May 17 '23 at 22:16
  • 2
    A more general duplicate: https://mathematica.stackexchange.com/questions/94294/what-are-the-requirements-for-a-well-behaved-indexed-variable-subscript-toexpr -- Also related: https://mathematica.stackexchange.com/questions/59242/issue-with-very-large-lists-in-mathematica/59293#59293, https://mathematica.stackexchange.com/questions/51765/how-to-create-a-writable-and-clearable-symbol – Michael E2 May 18 '23 at 03:09

1 Answers1

4

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} *)

lericr
  • 27,668
  • 1
  • 18
  • 64
  • 2
    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" . – rhermans May 18 '23 at 08:00