Call a function within the same file

I’m writing a short function and try to call it in a same file as follows.

a = 1.0:3.0
tfs(a)

function tfs(x)
 n = length(x)
 m = sum(x)/n
 s = sqrt(sum((x-m).^2/n))
 return m, s
end

Of course, I got an error.

ERROR: LoadError: UndefVarError: tfs not defined
 in include_from_node1(::String) at ./loading.jl:488
while loading /home/chobbes/Documents/git/smsa/test14.jl, in expression starting on line 2

I know there must be something naively wrong. Can anyone give me a hint? Thanks!!

Put the function above the call?

OMG…That works!! I know this must be the dumbest question even in ‘First steps’…

Btw, if I define a function in a file and want to call it in terminal, what am I supposed to do to make sure that the terminal can ‘see’ that function? Thanks!!

include the file…

1 Like

Thanks!!

A quick question - why do I see the results every time I run the code? Seems that I’m not printing them…

julia> include("/home/chobbes/Documents/git/smsa/test14.jl")
(2.0,0.816496580927726)

The return value of the evaluation is printed (That’s what the P in REPL for). In this case, the result of the last expression in the included file.

Thanks very much. I see it now.

I’m sorry, but still have another question:

If I only need the function to return m, but not s, what shall I do? Is there anything like ~ in Matlab? For example, [m, ~] = tfs(x) in Matlab. Thanks!!

You can either just index into the result, e.g. tfs(x)[1] or use m, _ = tfs(x), where _ is just some identifier right now, but might do the same thing as ~ in the future.

There is currently no way of only returning m, but you can do

m, s = tfs(x)

see http://docs.julialang.org/en/release-0.5/manual/functions/#multiple-return-values

To signify that I won’t be using a variable I use _

m, _ = tfs(x)

pfitzseb and vchuravy - Thanks very much!!

Is there a way to determine how many output arguments a function needs to return depending on the number of output arguments being supplied at the call of the function? In Matlab, nargout is used and I noted that Julia doesn’t offer such a thing as indicated in the difference doc: http://docs.julialang.org/en/latest/manual/noteworthy-differences/#noteworthy-differences-from-matlab

In Julia, multiple values are returned and assigned as tuples, e.g. (a, b) = (1, 2) or a, b = 1, 2. MATLAB’s nargout, which is often used in MATLAB to do optional work based on the number of returned values, does not exist in Julia. Instead, users can use optional and keyword arguments to achieve similar capabilities.

So I wonder what the ‘optional and keyword arguments’ are? And is there any workaround at all to achieve what nargout does in Matlab? Thanks!!