Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a function have multiple return values in Julia (vs. MATLAB)?

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?

like image 621
Echetlaeus Avatar asked Nov 23 '14 22:11

Echetlaeus


People also ask

How do you return multiple values 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:

How to return multiple values from a function in MATLAB?

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.

How do you write a function in Julia?

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.

Can a function return nothing 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.


1 Answers

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. [...]

like image 138
jub0bs Avatar answered Sep 27 '22 23:09

jub0bs