10
votes

I have a Julia function in a file. Let's say it is the below. Now I want to pass arguments into this function. I tried doing

julia filename.jl randmatstat(5) 

but this gives an error that '(' token is unexpected. Not sure what the solution would be. I am also a little torn on if there is a main function / how to write a full solution using Julia. For example what is the starting / entry point of a 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 = [a b c d]
        Q = [a b; c d]
        v[i] = trace((P.'*P)^4)
        w[i] = trace((Q.'*Q)^4)
    end
    std(v)/mean(v), std(w)/mean(w)
end
3

3 Answers

5
votes

You can try running like so:

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

5
votes

Julia doesn't have an "entry point" as such. When you call julia myscript.jl from the terminal, you're essentially asking julia to execute the script and exit. As such, it needs to be a script. If all you have in your script is a function definition, then it won't do much unless you later call that function from your script.

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

e.g. if you have a julia script which simply says:

# in julia mytest.jl
show(ARGS)

Then calling this from the linux terminal will give this 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, the function needs to be defined before it's 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 = [a b c d]
        Q = [a b; c d]
        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 this from your linux terminal like so:

julia myscript.jl 5
3
votes

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 attempted originally. Note the additional quotes added to make sure the parenthesis don't mess up the command.

Explanation: The ARGS variable is defined by Julia to hold the parameters to the command running the file. Since Julia is an interpreter, we can join these parameters to a string, parse it as Julia code, run it and print the result (the code corresponds to this description).