# How do I define a function that accepts a subscripted variable? [duplicate]

How do I define a function with subscripted variable? I want to write the following expression

$$\qquad f[a_9] =1+ a_7 + a_9$$

I wrote

f[Subscript[a, 9]_] := 1 + [Subscript[a, 7]+ [Subscript[a, 9]


but it doesn't work

• Commented Dec 26, 2019 at 1:36

Ordinarily, you don't need indicate that the argument is subscripted. If you were to define f with

f[u_] := 1 + Subscript[a, 7] + u


Then f will accept any argument including a subscripted variable. For example

f[42]


43 + Subscript[a, 7]

Subscript[a, 9] = 42; f[Subscript[a, 9]]


43 + Subscript[a, 7]

Subscript[a, 9] =.; f[Subscript[a, 9]]


1 + Subscript[a, 7] + Subscript[a, 9]

However, if your intention is to restrict f to accept only subscripted forms as it argument, then you need to do something like this:

Clear[f]
f::badarg = "argument not a subscripted form";
SetAttributes[f, HoldFirst]
f[u : Subscript[_, _]] := 1 + Subscript[a, 7] + u
f[___] /; (Message[f::badarg]; False) = Null;


Then arguments that are not subscripted forms will be rejected; given such a form f will not evaluate.

The other two example given above will still work exactly as they did.

It is now 2023 and Mathematica version 13.2 and this problem still exists.

Just do

f[Subscript[a_, 9]] := 1 + Subscript[a, 7] + Subscript[a, 9]
f[Subscript[a, 9]]


ps. Subscript variables are bad. Avoid them. I never use them myself.

V 13.3 on windows 10