Retrieve all variables appearing in a symbolic expression

I would like to get all the variables involved in an expression, even the implicit ones. For example, if you do

using Symbolics
@variables x y u(x, y)
println(Symbolics.get_variables(u))

You get 1-element Vector{SymbolicUtils.BasicSymbolic}: u(x, y). However, i would like to get as a result a 3-element Vector with u, x and y.

Is there a way to retreive all variables involved in u? (namely, also x and y)

Thanks!

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

Nice, thanks!

1 Like