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
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityHow 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
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.