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
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
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.
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
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)
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