In MATLAB, the following code returns m
and s
:
function [m,s] = stat(x)
n = length(x);
m = sum(x)/n;
s = sqrt(sum((x-m).^2/n));
end
If I run the commands
values = [12.7, 45.4, 98.9, 26.6, 53.1];
[ave,stdev] = stat(values)
I get the following results:
ave = 47.3400
stdev = 29.4124
How would I define my stat
function in Julia?
In Julia, one returns a tuple of values to simulate returning multiple values. However, tuples can be created and destructured without needing parentheses, thereby providing an illusion that multiple values are being returned, rather than a single tuple value. For example, the following function returns a pair of values:
This tutorial will discuss how to return multiple values from a function using the box brackets in MATLAB. If you want to return multiple values from a function, you have to define all of them inside a box bracket separated by a comma and assign them the required output within the function bounds.
The basic syntax for defining functions in Julia is: julia> function f (x,y) x + y end f (generic function with 1 method) This function accepts two arguments x and y and returns the value of the last expression evaluated, which is x + y. There is a second, more terse syntax for defining a function in Julia.
See Type Declarations for more on return types. For functions that do not need to return a value (functions used only for some side effects), the Julia convention is to return the value nothing: This is a convention in the sense that nothing is not a Julia keyword but a only singleton object of type Nothing.
How would I define my
stat
function in Julia?
function stat(x)
n = length(x)
m = sum(x)/n
s = sqrt(sum((x-m).^2/n))
return m, s
end
For more details, see the section entitled Multiple Return Values in the Julia documentation:
In Julia, one returns a tuple of values to simulate returning multiple values. [...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With