Create a vector of SVectors

I have 3 independent vectors x,y,z of length N, and with to turn them into N 3-SVectors. I wonder if there’s a better way to do this:

    using StaticArrays
    x = rand(10) # dummy example
    y = rand(10) # dummy example
    z = rand(10) # dummy example

    positions = map((x,y,z) -> SVector(x,y,z), x, y, z) # better way to create this?

That’s good. Could also do map(SVector, x, y, z) or SVector.(x, y, z).

2 Likes

Oh yes, of course! I tried more complicated things with broadcast, but this was right there. Thanks. Out of curiosity, is there some penalty in mapping with an anonymous function, i.e.

map((x,y,z) -> SVector(x,y,z), x, y, z)

vs

SVector.(x,y,z)

(not worried about this case, but more to know the general pattern isn’t a bad habit – extraneous anonymous function calls would have some penalty in R, for example)

Nope, it’s all good. Calling SVector.(x, y, z) actually just does (roughly):

broadcast((x, y, z) -> SVector(x, y, z), x, y, z)

creating an anonymous function and calling it on each element of x, y, and z. Anonymous functions in Julia are fast (just as fast as any other function), and they get optimized an inlined just as well.

Thanks – that was my concern, not knowing if they might be inlined by the compiler.

In general, Julia is very aggressive in inlining. There are some cases where it still messes up (in both directions), but for the most part the inliner is pretty good. (The biggest exception I know of is LLVM calls).

1 Like