How to feval?

246 views
Skip to first unread message

J Luis

unread,
Oct 22, 2015, 8:57:31 AM10/22/15
to julia-users
Hi,

I need to convert this piece of Matlab code

          [ps, orig_path] = feval(str2func(test), out_path);

where 'test' is the name of a function and 'out_path' it unique input argument. I have read and re-read the eval function and for once it's clear for me how it works (sorry, I find this sentence highly cryptic "Evaluate an expression in the given module and return the result" ) but worst, I don't see anywhere how it could call a function with input arguments.

How can I achieve the same result in Julia?
 
Thanks.

Kristoffer Carlsson

unread,
Oct 22, 2015, 9:10:44 AM10/22/15
to julia-users
Maybe

julia> eval(Symbol("sin"))(5.0)
-0.9589242746631385

Not sure if this is the best solution.

J Luis

unread,
Oct 22, 2015, 9:20:33 AM10/22/15
to julia-users
Thanks, at least it's a place to start.

Alex Ames

unread,
Oct 22, 2015, 12:34:13 PM10/22/15
to julia-users
You could define your own feval:

feval(fn_str, args...) = eval(parse(fn_str))(args...)

This has the advantage of accepting anonymous functions and multiple arguments if necessary:
julia> feval("sin",5.0)
-0.9589242746631385

julia> fn_str = "a_plus_b(a,b) = a + b"
"a_plus_b(a,b) = a + b"

julia> feval(fn_str,2,3)
5

Stefan Karpinski

unread,
Oct 22, 2015, 1:16:05 PM10/22/15
to Julia Users
This will not be fast. It's also wildly insecure if the string come from an external source. I'd strongly recommend figuring out a different approach to what you're doing, but it's hard to provide guidance without more context.

J Luis

unread,
Oct 22, 2015, 1:30:04 PM10/22/15
to julia-users
Speed is not critical here. I am porting this script

   http://gmt.soest.hawaii.edu/projects/gmt-matlab-octave-api/repository/changes/trunk/src/gmtest.m

that will call the test scripts that live, as for example, here

    http://gmt.soest.hawaii.edu/projects/gmt/repository/show/branches/5.2.0/doc/scripts/ml

and compare the produced output with the reference PS file that is also in the testing dirs.

If it works, as I hope and will test later. It's good enough for me but off course faster alternatives are always wellcome.

Thanks

J Luis

unread,
Oct 22, 2015, 2:56:27 PM10/22/15
to julia-users
Anyway, unfortunately none of the above solutions work for files. If the file is called "GMT_insert.jl", and is in the path, I get variations around (+ file extension - file extension) of

ERROR: UndefVarError: GMT_insert not defined

Stefan Karpinski

unread,
Oct 22, 2015, 4:08:46 PM10/22/15
to Julia Users
Julia doesn't identify functions and files the way Matlab does. You can just load the file by name.
Reply all
Reply to author
Forward
0 new messages