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$
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.

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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