Passing function arguments to Julia is not interactive

I have a Julia function in a file. Say it below. Now I want to pass arguments to this function. I tried to do

julia filename.jl randmatstat(5) 

but it gives an error: "(" the token is unexpected. "I’m not sure what the solution is. I am also a bit torn if there is a main function / how to write a complete solution using Julia. is the starting / starting point of the Julia program?

 function randmatstat(t) n = 5 v = zeros(t) w = zeros(t) for i = 1:t a = randn(n,n) b = randn(n,n) c = randn(n,n) d = randn(n,n) P = [abcd] Q = [ab; cd] v[i] = trace((P.'*P)^4) w[i] = trace((Q.'*Q)^4) end std(v)/mean(v), std(w)/mean(w) end 
+7
source share
3 answers

Julia has no β€œentry point" as such. When you call julia myscript.jl from the terminal, you are essentially asking julia to execute the script and exit. So it should be a script. If everything you have in your script is a function definition, then this will not do much unless you later call this function from your script.

As with arguments, if you call julia myscript.jl 1 2 3 4 , all other arguments (i.e., 1, 2, 3, and 4 in this case) become an array of strings with the special name ARGS . You can use this special variable to access input arguments.

eg. if you have a julia script that just says:

 # in julia mytest.jl show(ARGS) 

Then calling this from the linux terminal will give the following result:

 <bashprompt> $ julia mytest.jl 1 two "three and four" UTF8String["1","two","three and four"] 

EDIT: So, from what I understand from your program, you probably want to do something like this (note: in julia, a function must be defined before it is called).

 # in file myscript.jl function randmatstat(t) n = 5 v = zeros(t) w = zeros(t) for i = 1:t a = randn(n,n) b = randn(n,n) c = randn(n,n) d = randn(n,n) P = [abcd] Q = [ab; cd] v[i] = trace((P.'*P)^4) w[i] = trace((Q.'*Q)^4) end std(v)/mean(v), std(w)/mean(w) end t = parse(Int64, ARGS[1]) (a,b) = randmatstat(t) print("a is $a, and b is $b\n") 

And then call it from your linux terminal as follows:

 julia myscript.jl 5 
+2
source

You can try to do this:

julia -L filename.jl -E 'randmatstat(5)'

+5
source

Add the following to your Julia file:

 ### original file function randmatstat... ... end ### new stuff if length(ARGS)>0 ret = eval(parse(join(ARGS," "))) end println(ret) 

Now you can run:

 julia filename.jl "randmatstat(5)" 

As I tried initially. Pay attention to the added extra quotes to make sure that the bracket does not ruin the command.

Explanation: The ARGS variable is defined by Julia to store parameters for the command that launches the file. Since Julia is an interpreter, we can join use these parameters for the string, parse it as Julia code, run it and print the result (the code matches this description).

+3
source

All Articles