How to pass parameter list to a function in Julia

2019-03-01 04:54发布

I am newbie in Julia language, and the tutorial is not very deep yet and I didn't understand what is the best way to pass a parameter list of a function. My function looks like this:

function dxdt(x)
    return a*x**2 + b*x - c
end

where x is the variable (2D array) and a,c, and d are parameters. As I understand it is not recommended to work with global variables in Julia. So what is the right way to do it?

标签: julia
5条回答
冷血范
2楼-- · 2019-03-01 05:09

What you want to do really is passing an instance of a data structure (composite data type) to your function. to do this, first design your data type:

type MyType
  x::Vector
  a
  b
  c
end

and implement dxtd function:

function dxdt(val::MyType)
  return val.a*val.x^2 + val.b*val.x + val.c
end

then some where in your code you make an instance of MyType like this:

myinstance = MyType([],0.0,0.0,0.0)

you can update myinstance

myinstance.x = [1.0,2.8,9.0]
myinstance.a = 5

and at the end when myinstance get ready for dxxt

dxdt(myinstance)
查看更多
forever°为你锁心
3楼-- · 2019-03-01 05:12

To me it sounds like you're looking for anonymous functions. For example:

function dxdt_parametric(x, a, b, c)
   a*x^2 + b*x + c
end

a = 1
b = 2
c = 1

julia> dxdt = x->dxdt_parametric(x, a, b, c)
(anonymous function)

julia> dxdt(3.2)
17.64
查看更多
Juvenile、少年°
4楼-- · 2019-03-01 05:22

this is a thing:

function dxdt(x, a, b, c)
   a*x^2 + b*x + c
   end

or the compact definition:

dxdt(x, a, b, c) = a*x^2 + b*x + c

see also argument passing in functions in the docs.

查看更多
我想做一个坏孩纸
5楼-- · 2019-03-01 05:25

The idiomatic solution would be to create a type to hold the parameters and use multiple dispatch to call the correct version of the function.

Here's what I might do

type Params
    a::TypeOfA
    b::TypeOfB
    c::TypeOfC
end

function dxdt(x, p::Params)
    p.a*x^2 + p.b*x + p.c
end

Sometimes if a type has many fields, I define a helper function _unpack (or whatever you want to name it) that looks like this:

_unpack(p::Params) = (p.a, p.b, p.c)

And then I could change the implementation of dxdt to be

function dxdt(x, p::Params)
    a, b, c = _unpack(p)
    a*x^2 + b*x + c
end
查看更多
劫难
6楼-- · 2019-03-01 05:27

You may use the power of functional language (function as a first-class object and closures):

julia> compose_dxdt = (a,b,c) -> (x) -> a*x^2 + b*x + c #creates function with 3 parameters (a,b,c) which returns the function of x
(anonymous function)

julia> f1 = compose_dxdt(1,1,1) #f1 is a function with the associated values of a=1, b=1, c=1
(anonymous function)

julia> f1(1) 
3

julia> f1(2)
7

julia> f2 = compose_dxdt(2,2,2) #f1 is a function with the associated values of a=2, b=2, c=2
(anonymous function)

julia> f2(1)
6

julia> f2(2)
14
查看更多
登录 后发表回答