I am new to Mathematica and encounter the following problem.

Define two variables g = 1 and Subscript[g, 1]= 1. If we execute $g = 2$, then Subscript[g, 1] will return $2_1$.

I simply want define variables g and g_1, which would not interfere each other in any other language.

  • 5
    $\begingroup$ "which would not interfere each other in any other language", well, to be fair, most other languages don't support subscripts at all. My advice is to just not use subscripts. Call it g and g1. As you noticed, subscripts do cause problems. $\endgroup$ – Szabolcs Oct 23 '17 at 21:18
  • 2
    $\begingroup$ To understand why, read Everything is an Expression. You can "symbolize" $g_1$ with the Notation package, but that's not without compromises either. Personally I never use it. $\endgroup$ – Szabolcs Oct 23 '17 at 21:19
  • $\begingroup$ In defense of the Notations package -- which there is not a lot of love for :) -- I do use it but a user needs to understand its limitations (and strengths) when deciding to use it $\endgroup$ – Mike Honeychurch Oct 23 '17 at 21:39
  • 1
    $\begingroup$ Yeah, subscripts are evil. $\endgroup$ – Henrik Schumacher Oct 23 '17 at 21:47
  • $\begingroup$ For a moment I thought the site is in beta and we're seeding it with canonical questions. $\endgroup$ – LLlAMnYP Oct 24 '17 at 15:09

Mathematica does not evaluate expression like any other language I can think of. To use it successfully you will have to adjust to that fact.

Subscript[g, 1] in not interpreted as a variable but as an expression, and is evaluated like any other expression, which is why when g has a value, you get what you see.

When g is value free, Subscript[g, 1], a down-value is established for Subscript.

Subscript[g, 1] = 1;
DownValues @ Subscript

{HoldPattern[Subscript[g, 1]] :> 1}

Because of this down-value, when the expression Subscript[g, 1] is seen again, it will match the lhs of this down-value and the rhs, 1, will be returned. If g has a value, that value is substituted into Subscript[g, 1] to produce Subscript[2, 1]. That pattern doesn't match the down-value so 1 is not retrieved. Which means you can't get variable-like behavior from Subscript[g, 1] if g has a value. Sorry, but that is way it works.

I strongly urge you to look at this question and get Wagner's book as a free download. It will be a great help in orienting you to the Mathematica way.


A couple possible alternatives:

  1. Use "g" in the subscript instead:

    Subscript["g", 1]
    Subscript[g, 1]

enter image description here

You can't tell the difference in StandardForm.

  1. Give Subscript the HoldFirst attribute:

    SetAttributes[Subscript, HoldFirst];
    g = 2;
    Subscript[g, 1]

enter image description here


Your Answer

