3
$\begingroup$

I'm looking for a procedural way to define a symbol for a variable, based on a string. For instance, ToExpression["A^B"] gives us Power[A,B] (which, might be enough if we know that B will never get any value throughout the code).

However, as soon as we assign a number to B, we start getting troubles. For example, ToExpression["A^0"] evaluates to 1, ToExpression["A^(-1)"] evaluates to 1/A, and so on, but I would like to get Superscript[A,0] and Superscript[A,-1], and so on instead. How can I achieve that?

$\endgroup$
3
  • 1
    $\begingroup$ Superscript or Subscript? $\endgroup$
    – xzczd
    Commented Nov 10, 2023 at 3:46
  • $\begingroup$ Sorry, I meant to say 'Superscript'. I've edited the question to fix it. $\endgroup$
    – JuanC97
    Commented Nov 10, 2023 at 3:49
  • 1
    $\begingroup$ Instead of using strings, use formatted indexed variables, e.g., Format[A[n_]] := Superscript[A, n] then {A[0], A[1], A[-1]} $\endgroup$
    – Bob Hanlon
    Commented Nov 10, 2023 at 3:54

1 Answer 1

8
$\begingroup$

Something like this?:

convert[str_] := str // StringReplace["^" :> "~Superscript~"] // ToExpression

convert /@ {"A^B", "A^0", "A^-1", "A^(-1)"}
(* {Superscript[A, B], Superscript[A, 0], Superscript[A, -1], 
   Superscript[A, -1]} *)

Another method:

convert[str_] := Block[{Power = Superscript}, ToExpression@str]
$\endgroup$
2
  • $\begingroup$ Loved the second method. I modified it to Block[{Power = Superscript}, ToExpression[str, TeXForm]] to guarantee that "A^{-1}" also gets mapped into Superscript[A,-1]. $\endgroup$
    – JuanC97
    Commented Nov 10, 2023 at 4:05
  • $\begingroup$ @JuanC97 Alternatively, add a line Superscript[a_, {b_}] := Superscript[a, b]. (This will also work on the first method. ) $\endgroup$
    – xzczd
    Commented Nov 10, 2023 at 4:09

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.