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
  • 3
    $\begingroup$ try Symbol[SymbolName[#[[0]]] <> ToString[#[[1]]]] & /@ yourlist or ReplaceAll[f_[i_Integer] :> Symbol@StringJoin[ToString /@ {f, i}]]@lyourlist $\endgroup$
    – kglr
    Commented May 17, 2023 at 21:57
  • 1
    $\begingroup$ 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? $\endgroup$
    – lericr
    Commented May 17, 2023 at 22:04
  • $\begingroup$ @kglr, thanks a lot! $\endgroup$
    – Mam Mam
    Commented May 17, 2023 at 22:16
  • 2
    $\begingroup$ A more general duplicate: mathematica.stackexchange.com/questions/94294/… -- Also related: mathematica.stackexchange.com/questions/59242/…, mathematica.stackexchange.com/questions/51765/… $\endgroup$
    – Michael E2
    Commented May 18, 2023 at 3:09

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
    Commented May 18, 2023 at 8:00

Your Answer

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

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