Reputation: 1801
I'm trying to vectorize the following functions:
function f(x)
z1 = 3*x
z2 = x^2
return z1,z2
end
function g(x,y)
z = 2*x + 3*y*im
return z
end
My goal, is to have one vector input as x
to a function f(x)
, then take the result of the function g(x,y)
and get a single vector output.
When I try to do the following:
x̂ = collect(range(0,10,step=0.01))
g.(f.(x̂))
I get the error:
MethodError: no method matching g(::Tuple{Float64, Float64})
I'm not sure exactly how to make this case work, I guess the fact that the function f
returns two values causes the issue, however, it should technically work because the function g
takes two inputs.
Upvotes: 2
Views: 147
Reputation: 5559
Since g(x,y)
is defined for two arguments but f(x)
outputs Tuple
s, what you want is to Splat
the function g
before feeding the tuples into it. Splatting means, given a function, return a new function that takes one argument and splats its argument into the original function.
This is achieved by Base.splat
or simply Splat
in the upcoming Julia releases.
function f(x)
z1 = 3*x
z2 = x^2
return z1,z2
end
function g(x,y)
z = 2*x + 3*y*im
return z
end
x̂ = range(0,10,step=0.01)
Base.splat(g).(f.(x̂))
# Or Julia 1.9
Splat(g).(f.(x̂))
Upvotes: 4