To extract all variables from a symbolic expression, including implicit ones, you may want to use the recursive approach:
- Start by using
get_variablesto get the top-level variables (e.g.,u(x, y)). - Extract the “ops” (e.g.,
u) withoperationand its “args” (e.g.,xandy) witharguments. - Recursively apply this process to both the ops and its args to collect all the components.
using Symbolics
using Symbolics: get_variables, isterm, operation, arguments
function all_vars(expr)
vars = get_variables(expr)
res = Set(vars)
for v in vars
if isterm(v)
res = union(res, all_vars(operation(v)))
for arg in arguments(v)
res = union(res, all_vars(arg))
end
end
end
return res
end
julia> @variables x, y, u(x, y);
julia> all_vars(u)
Set{Any} with 4 elements:
u
u(x, y)
y
x