# Function definition with sub (super) cripted variables [duplicate]

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

Is there a way around this?

• Don't use Subscript. It is evil. Maybe it is myfunction[x_] := Indexed[x, 1] + 1 what you want... – Henrik Schumacher Jan 10 '19 at 16:55
• – xzczd Jan 10 '19 at 17:05
• I've added 869 as a duplicate because the answer is exactly the same if we replace Module with Pattern name. – Kuba Jan 11 '19 at 8:05

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.

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