Function calling @SVector with locally defined range returns UndefVarError

Since @SVector is a macro and macros are evaluated at parse time (and n is not available at parse time), you get this error. It would only work if you used a parse-time constant range like 1:3.

But there are numerous alternatives available, including

julia> @SVector [i for i in 1:3] # works with the literal 3, but not a variable
3-element SVector{3, Int64} with indices SOneTo(3):
 1
 2
 3

julia> SVector{3}(i for i in 1:3)
3-element SVector{3, Int64} with indices SOneTo(3):
 1
 2
 3

julia> SVector{3}(1:3)
3-element SVector{3, Int64} with indices SOneTo(3):
 1
 2
 3

Note that the function f(n) = SVector{n}(1:n) is not type stable because the length n is a run time value (not compile time constant). So you are likely to see very poor performance if you use this function. You want the length to be brought into the type domain so that it is a compile-time constant. You might want to re-think exactly how you’re using this.

1 Like