Echetlaeus
Echetlaeus

Reputation: 343

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?

Upvotes: 11

Views: 24013

Answers (1)

jub0bs
jub0bs

Reputation: 66214

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

Upvotes: 19

Related Questions