Suppose I have a vector of functions, say f=[sin,cos]
and I want to apply this element by element to a vector of numbers, say v=[2pi/3, pi/3]
so that I get [sin(2pi/3), cos(pi/3)]
– is there an elegant syntax for this?
1 Like
A comprehension is pretty elegant:
julia> f = [sin, cos]
2-element Array{Function,1}:
sin
cos
julia> v = [1, 2]
2-element Array{Int64,1}:
1
2
julia> [ff(vv) for (ff, vv) in zip(f, v)]
2-element Array{Float64,1}:
0.8414709848078965
-0.4161468365471424
Wouldn’t you want to get out four elements like
f=[sin,cos]
v=[2pi/3, pi/3]
julia> [i(j) for i in f for j in v]
4-element Array{Float64,1}:
0.8660254037844387
0.8660254037844386
-0.4999999999999998
0.5000000000000001
?
(Not clear from OP I guess)
I would probably rely on an anonymous function that applies its first argument to its second argument, i.e.
(f,x) -> f(x)
.
This you can then map
map((f,x) -> f(x), [sin, cos], [2\pi/3, \pi/3])
or broadcast
((f,x) -> f(x)).([sin, cos], [2\pi/3, \pi/3])
or you can rely on list comprehesion as the others suggest
f = [sin, cos]
w = [π/2, π]
julia> map.(f, w)
2-element Array{Float64,1}:
1.0
-1.0
julia> w .|> f
2-element Array{Float64,1}:
1.0
-1.0
(by the way, if you want good performance, you might want to check out FunctionWrappers.jl.)
10 Likes
The opposite might be easier, since it’s built into Julia:
f = [sin, cos]
w = [π/2, π]
julia> map(|>, w, f)
2-element Array{Float64,1}:
1.0
-1.0
julia> (|>).(w, f)
2-element Array{Float64,1}:
1.0
-1.0
2 Likes
Thanks for excellent answers. I’ll take a look into the various options – have to finish some other things at work first :-o .