# Get all variables in an expression with Variables[] [duplicate]

"ϕ" <> "1";
Variables[%]

Exp["ϕ" <> "1"];
Variables[%]

Exp[Subscript[ϕ, 1]];
Variables[%]


Say I have lots of variables used for construct an expression. I am new to MMA, so I am still trying to determine which way to put it, i.e. using subscripts? catenate?

But the main issue is that, Variables can't seem to give me all the variables I want except the direct case (first case above).

Only time it worked is in the first case. So if I want to use

Table[Exp[Subscript[ϕ, j]], {j, 1, 10}]
Variables[%]


to create a function, and do some calculation with it, I can't use Length[Variables[%]] to determine how many parameters I have.

Table[Subscript[η, ϕ, j], {j, 1, 10}];
Variables[%]  (*works fine*)

Table[Exp[Subscript[η, ϕ, j]], {j, 1, 10}];
Variables[%]  (*But this is what I want to use*)


What I am used to for the above (in Maple), is to express this using eta and subscript phi1, phi2, phi3, etc. I haven't figured out how exactly to achieve this in MMA 10 yet.

Is there a way to get Variables[%] to cope with this?

Thanks!

Variables[Level[expression, {-1}]]


you have to know that Subscript variables is not considered as pure variables in MMA. it is basically a built in function expression. in this case I would suggest you to used:

d = Table[Exp[Subscript[ϕ, j]], {j, 1, 10}];
Cases[d, Subscript[__, __], {1, -1}]

{Subscript[ϕ, 1], Subscript[ϕ, 2], Subscript[ϕ, 3], \
Subscript[ϕ, 4], Subscript[ϕ, 5], Subscript[ϕ, 6], \
Subscript[ϕ, 7], Subscript[ϕ, 8], Subscript[ϕ, 9], \
Subscript[ϕ, 10]}

• I think Variables[Level[expression, {-2}]] just did the trick! – Chen Stats Yu Oct 2 '14 at 1:19

There's an internal, undocumented utility that will do it for you:

IntegrategetAllVariables[Cos[t x] E^y, {}]
(*  {t, x, y}  *)


OP's example:

Table[Exp[Subscript[\[Eta], \[Phi], j]], {j, 1, 10}];
IntegrategetAllVariables[%, {}]


Examples showing some variation:

IntegrategetAllVariables[f[t x] E^y, {}]
(*  {y, f[t x]}    --- f is not identified as a function *)

SetAttributes[ff, NumericFunction]
IntegrategetAllVariables[ff[t x] E^y, {}]
(*  {t, x, y}      --- the attribute causes f to be treated as a function *)

IntegrategetAllVariables[ff[t x] E^y, {x}]
(*  {t, y}         --- the arguments in the list are omitted from output *)


The last example can be explained in the context of a definite integral with respect to x. The integral itself does not depend on x, even though the integrand does.

• Another possibility is ReduceFreeVariables – Carl Woll Mar 31 '19 at 22:01