Accessing arguments of a symbolic expression using SymbolicUtils.jl

Hi everyone, I have a question about the arguments of a symbolic expression in the case it is constructed from array variables.

Suppose I have an symbolic array and I use it to construct a symbolic expression:

@parameters z[1:3]
expr = toexpr(z[1] + z[2])

I’d like to verify that z[1] is the arguments of expr and z[3] is not. I did this by looping over the arguments and calling isequal:

for arg in  expr.args 
     println("z[1] in expression: ", isequal(z[1], arg))
     println("z[3] in expression: ", isequal(z[1], arg))
end

but the output is always false. When I look at the arguments, I see

In: expr.args
Out: 3-element Vector{Any}:
 + (generic function with 741 methods)
 :((getindex)(z, 1))
 :((getindex)(z, 2))

I understand that the arguments are of the form :((get index)(z, i)) since I am working with variables from a symbolic array, but I’m not sure how to relate them to the form z[i]. Is there a different way I should initialize the symbolic expression? I read the docs here and it seemed like forwarding the state st could be promising, but I’m not sure how to use this functionality and I couldn’t find any examples. If there are examples or documentation I missed, it would be great if someone could point me in the right direction!

Thanks so much!

With the latest package versions, the @parameters macro doesn’t seem to exist (any more). I can write this:

using Symbolics, SymbolicUtils.Code
@variables z[1:3]
expr = toexpr(z[1] + z[2])

println("z[1] in expression: ", in(toexpr(z[1]), expr.args))
println("z[3] in expression: ", in(toexpr(z[3]), expr.args))

The output is

z[1] in expression: true
z[3] in expression: false
3 Likes

Thanks so much! I really appreciate it.

May be of interest if you are unaware, but it is possible to call arguments(z[1] + z[2]) to get [z[1], z[2]].

Also of note is operation(z[1] + z[2]), which will return (+)

2 Likes