I like using subscripts a lot. However, it is regrettably not possible to do, for example:

myfunction[Subscript[x,1]_] := Subscript[x,1] +1

where instead of the subscript, I would use Ctrl+_ to make the subscript. See below

enter image description here

Is there a way around this?


Mathematica is a rewrite language. x_ means "match something and give it the name x for rewrite purposes". Subscript[x,1]_ is meaningless, because Subscript[x,1] isn't a symbol.

One way to deal with things like this is to deconstruct them and reconstruct what you want.

myfunction[var_Subscript] := Subscript[var[[1]], var[[2]]] + var[[2]]^2

The argument pattern here recognizes anything with the head Subscript. The function body deconstructs it and reconstructs using both parts of the Subscript expression.

myfunction[Subscript[x, 2]]
(* 4 + Subscript[x, 2] *)

If you only want it to work when the subscript is 1, perhaps the handiest way is to put that in the argument pattern and do your deconstruction there:

anotherway[Subscript[x_, 1]] := Subscript[x, 1] + 1
anotherway[Subscript[y, 1]]
(* 1 + Subscript[y, 1] *)

You can also do implement this kind of restriction with Condition, left as an exercise for the reader.

| improve this answer | |
  • $\begingroup$ Oh, and yes, subscripts can cause you much confusion unless you really understand Mathematica as a rewrite language. @Henrik Schumacher@ is right. $\endgroup$ – John Doty Jan 10 '19 at 17:39

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