I am new to Julia programming and not an expert. 

While working on a project which involves the translation of Matlab code to 
Julia I had the idea to write a feval(f, x1=NaN) function in Julia to 
evaluate a single expression or an array of two or more expressions by 
using just one function. 

This is the code of the feval(f, x1=NaN) function:
function feval(f,x1 = NaN)
 if isnan(x1) == false
 global x = x1

 end

 if typeof(f) == Array{Expr,1}

 n = size(f,1)

 F = zeros(n,1)

 for i=1:n

 F[i] = eval(f[i])

 end

 elseif typeof(f) == Expr

 F = 0

 F = eval(f)

 else

 println("f is a ", typeof(f))

 error("f is nor an expression nor a single array of expressions.")

 end

 return F

 end


  

You can use this function with a single expression or with an array of 
expressions, x = 3.5 : 

 

julia> f1 = :(3*x - 2*x + 5)

:(+(-(*(3,x),*(2,x)),5))


 julia> f2 = :(4*x - 3*x/2)

:(-(*(4,x),/(*(3,x),2)))


 julia> f = [f1;f2]

2-element Array{Expr,1}:

:(+(-(*(3,x),*(2,x)),5))

:(-(*(4,x),/(*(3,x),2)))

 

 

julia> x = 3.5

3.5

 

 

Results:

julia> res_f1 = feval(f1)

8.5


 julia> res_f2 = feval(f2)

8.75


 julia> res_f = feval(f)

2x1 Array{Float64,2}:

8.5

8.75

 

 

Further, you can deliver the optional input value for x with the function 
call:

 

julia> res_f1 = feval(f1, 5.25)

10.25

 

Note that this changes the global variable x:

julia> x

5.25

 

 

In general: Is my appraoch a good or bad idea? Or are there better options 
to consider (types, macros etc.)?

 

Many thanks for your support.

 

Regards,

Dominik

Reply via email to