KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I'm looking for a utility that would take an expression and extract all variables in that expression. Following five examples cover pretty much all of my variable patterns a,Subscript[a,....],Subscript[a,...][...],a[...],a[...][...] Here are two test cases. expr1 = -Log[Subscript[\[Mu], 2][]] Subscript[\[Mu], 2][] - Log[Subscript[\[Mu], 2][2]] Subscript[\[Mu], 2][2] + Log[Subscript[\[Beta], 1, 2][]] Subscript[\[Beta], 1, 2][] + Log[2] Subscript[\[Beta], 1, 2][1] + Log[Subscript[\[Beta], 1, 2][1]] Subscript[\[Beta], 1, 2][1] + Log[2] Subscript[\[Beta], 1, 2][2] + Log[Subscript[\[Beta], 1, 2][2]] Subscript[\[Beta], 1, 2][2] + Log[Subscript[\[Beta], 2, 3][]] Subscript[\[Beta], 2, 3][] + Log[Subscript[\[Beta], 2, 3][2]] Subscript[\[Beta], 2, 3][2] + Log[2] Subscript[\[Beta], 2, 3][3] + Log[Subscript[\[Beta], 2, 3][3]] Subscript[\[Beta], 2, 3][3]; expr2 = Log[\[Beta][{1, 2}][{}]] \[Beta][{1, 2}][{}] + Log[2] \[Beta][{1, 2}][{1}] + Log[\[Beta][{1, 2}][{1}]] \[Beta][{1, 2}][{1}] + Log[2] \[Beta][{1, 2}][{2}] + Log[\[Beta][{1, 2}][{2}]] \[Beta][{1, 2}][{2}] + Log[\[Beta][{2, 3}][{}]] \[Beta][{2, 3}][{}] + Log[\[Beta][{2, 3}][{2}]] \[Beta][{2, 3}][{2}] + Log[2] \[Beta][{2, 3}][{3}] + Log[\[Beta][{2, 3}][{3}]] \[Beta][{2, 3}][{3}] - Log[\[Mu][{2}][{}]] \[Mu][{2}][{}] - Log[\[Mu][{2}][{2}]] \[Mu][{2}][{2}] On[Assert]; Assert[Union@extractVariables@expr1 === Union[Variables[expr1][[9 ;;]]]] Assert[Union@extractVariables@expr2 === Union[Variables[expr2][[9 ;;]]]] Here's MrWizard's solution extractVariables[formula_] := ( pat = _Symbol[___][___] | Subscript[_Symbol, __][___] | Subscript[_Symbol, __] | _Symbol; Union@Cases[formula, pat, -1] );
Tags (comma-separated)
Save Edits
Cancel