0
$\begingroup$

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

$\endgroup$
1

2 Answers 2

2
$\begingroup$

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.

badarg

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

$\endgroup$
2
$\begingroup$

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]]

Mathematica graphics

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

V 13.3 on windows 10

$\endgroup$

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