Extracting variables from an expression
Assuming you don't have any built-in symbols in that list, you could simply do:
DeleteDuplicates@Cases[Leff, _Symbol, Infinity]
(* {da, ma, dm, mc, La, h, R} *)
If you do have symbols from built-in contexts or packages, you can simply pick out only those that are in the Global`
context with:
With[{globalQ = Context@# === "Global`" &},
DeleteDuplicates@Cases[Leff, _Symbol?globalQ, Infinity]
]
If you have a different default working context (e.g. local to notebook/cell or in a package), change the pattern test to the following, instead of globalQ
:
currentContextQ = Context@# === $Context &
Using an undocumented function:
Reduce`FreeVariables[(mc dm^2 + mc/12*(h^2 + 3 R^2) + ma da^2 + ma/12 La^2)/
(mc dm + ma da)]
{da, dm, h, La, ma, mc, R}
The below code for getAllVariables
was lifted without attribution from some StackOverflow post.
headlist = {Or, And, Equal, Unequal, Less, LessEqual, Greater,
GreaterEqual, Inequality};
getAllVariables[f_?NumericQ] := Sequence[]
getAllVariables[{}] := Sequence[]
getAllVariables[t_] /; MemberQ[headlist, t] := Sequence[]
getAllVariables[ll_List] :=
Flatten[Union[Map[getAllVariables[#] &, ll]]]
getAllVariables[Derivative[n_Integer][f_][arg__]] :=
getAllVariables[{arg}]
getAllVariables[f_Symbol[arg__]] :=
Module[{fvars},
If[MemberQ[Attributes[f], NumericFunction] || MemberQ[headlist, f],
fvars = getAllVariables[{arg}],(*else*)fvars = f[arg]];
fvars]
getAllVariables[other_] := other
Example:
Leff = (mc dm^2 + mc/12*(h^2 + 3 R^2) + ma da^2 + ma/12 La^2)/(mc dm +
ma da)
getAllVariables[Leff]
(* Out[254]= {da, ma, dm, mc, ma, da, ma, La, mc, dm, mc, h, R} *)