Retrieve all variables appearing in a symbolic expression

To extract all variables from a symbolic expression, including implicit ones, you may want to use the recursive approach:

  1. Start by using get_variables to get the top-level variables (e.g., u(x, y)).
  2. Extract the “ops” (e.g., u) with operation and its “args” (e.g., x and y) with arguments.
  3. 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
1 Like