Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Vectorizing a function with two inputs

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

Since g(x,y) is defined for two arguments but f(x) outputs Tuples, 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̂))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading