Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass function arguments into Julia non-interactively

Tags:

julia

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
like image 760
CodeGeek123 Avatar asked Dec 30 '15 17:12

CodeGeek123


2 Answers

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
like image 78
Tasos Papastylianou Avatar answered Oct 03 '22 05:10

Tasos Papastylianou


You can try running like so:

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

like image 44
sushant Avatar answered Oct 03 '22 06:10

sushant