Evaluate function combining Float & Vector

Suppose I have a function of 3 variables:
f(x,y,z)= x + y + z
Suppose I have:

  • a variable s=1.4, which is a Float64
  • a vector a=[4.2;5.0] which is a 2-element Vector{Float64}.

How can I evaluate the function f at the arguments
x=s
y,z=a
f(s,a) doesn’t seem to work
Nor does f(s,Tuple(a))

Assuming f(s, a, a) doesn’t work?

Maybe an ntuple with splatting?

julia> a = [1, 2];

julia> (ntuple(t -> a, 2)...,)
([1, 2], [1, 2])
2 Likes

f(s, a...)

4 Likes

If this is performance critical I would suggest

f(s,ntuple(i->a[i],2)...)

Such that the length of the tuple and splatting is known at compile time. AFAIK spatting general vectors sometimes allocate something (at least I remember discussions here with this kind of issues)

Or define f(x,v::AbstractVector) = f(x,v[1],v[2])

4 Likes

thanks!
right now it’s not performance critical & sometimes a is a 2 element vector, sometimes it’s 5-elements etc…
But this will be very useful for me elsewhere & other users who come to this page w/ the same issue.

Does anyone have advice on a better way to name this issue? @mbauman

1 Like

Expand array into function arguments

If the vectors are always small and you can use SVectors, you can define:

f(s,v::SVector{N}) where N = f(s,ntuple(i->v[i],N)...)
2 Likes

OK, it turns out not to be so simple bc I in my case I need broadcasting & s is a 10-by-1 vector, a is a 10-by-1 vector consisting of 2-element subvectors…
It works if I do a comprehension though…

I couldn’t resist testing:

julia> using StaticArrays

julia> f(x,y,z) = @. x = x + y + z
f (generic function with 2 methods)

julia> g(s,x::SVector{N}) where N = f(s,ntuple(i->x[i],N)...)
g (generic function with 2 methods)

julia> x = SVector{2,Vector{Float64}}(rand(3),rand(3));

julia> s = rand(3);

julia> @btime g($s,$x)
  9.037 ns (0 allocations: 0 bytes)
3-element Vector{Float64}:
 3.861199086034205e6
 1.0012982079149153e7
 9.331970140004177e6


3 Likes