Convert Symbolic expression to a function

Greetings. I am trying to convert the a very simple example of the following

using SymbolicUtils
@syms x
f = 2*x

the f into a function that would evaluate at a concrete number of x, so ideally it’s a function that has

f(2) = 4

do anyone have experience doing it? thank you.

Check out Symbolics.build_function

3 Likes

If your expressions are polynomials you can check out MultivariatePolynomials.

At the end some meta programming helped.

eqn_str = "2*x1"
expression = Meta.parse(eqn_str)
eqn_f = @eval begin
    f(x1) = $expression
end

and we would have
eon_f(4) equals 8.

Have a look at this talk: JuliaCon 2019 | Keynote: Professor Steven G. Johnson It should convince you why the solution that you suggest is not a good idea :slight_smile: Instead I recommend you to use what was suggested:

it does exactly what you want:

julia> using Symbolics

julia> @syms x
(x,)

julia> expression = 2*x
2x

julia> fexp=build_function(expression,x)
:(function (x,)
      #= /Users/felixger/.julia/packages/SymbolicUtils/kZD5O/src/code.jl:282 =#
      #= /Users/felixger/.julia/packages/SymbolicUtils/kZD5O/src/code.jl:283 =#
      (*)(2, x)
  end)

julia> f = eval(fexp)
#1 (generic function with 1 method)

julia> f(2)
4
2 Likes

The call to eval can be avoided with

julia> f=build_function(expression,x, expression=Val{false})
RuntimeGeneratedFunction(#=in Symbolics=#, #=using Symbolics=#, :((x,)->begin
          #= /home/fredrikb/.julia/packages/SymbolicUtils/v2ZkM/src/code.jl:349 =#
          #= /home/fredrikb/.julia/packages/SymbolicUtils/v2ZkM/src/code.jl:350 =#
          #= /home/fredrikb/.julia/packages/SymbolicUtils/v2ZkM/src/code.jl:351 =#
          (*)(2, x)
      end))

julia> f(2)
4
2 Likes