# Hi! Suppose I want to code a function that returns a \`SVector\` but each component

**URL:** <https://discourse.julialang.org/t/hi-suppose-i-want-to-code-a-function-that-returns-a-svector-but-each-component/54372>\
**Category:** General Usage\
**Created:** [February 1, 2021, 1:19pm UTC](https://discourse.julialang.org/t/hi-suppose-i-want-to-code-a-function-that-returns-a-svector-but-each-component/54372 "2021-02-01T13:19:59Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![BridgeBot](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bridgebot/32/21491_2.png) [@BridgeBot](https://discourse.julialang.org/u/BridgeBot)\
**Post date:** [February 1, 2021, 1:19pm UTC](https://discourse.julialang.org/t/hi-suppose-i-want-to-code-a-function-that-returns-a-svector-but-each-component/54372/1 "2021-02-01T13:19:59Z")

</div>

Hi! Suppose I want to code a function that returns a `SVector` but each component is computed inside the function without knowing the size. Should I create a `MVector` and then cast that to a `SVector`? This is what I am thinking:

```julia
function test(::Val{D}) where {D}
    mv = @MVector zeros(D)

    for i in 1:D
        mv[i] = i + 1
    end

    sv = convert(SVector, mv)
    return sv
end

```

Then:

```julia
test(Val{4}())

```

does not allocate and is type stable. But I don’t know if this is the correct approach. Thanks!

Note that the original poster on Slack cannot see your response here on Discourse. Consider _transcribing the appropriate answer back to Slack_, or pinging the poster here on Discourse so they can _follow this thread_.  
[(Original message :slack:)](https://julialang.slack.com/archives/C6A044SQH/p1612185518345700?thread_ts=1612185518.345700&cid=C6A044SQH) [(More Info)](https://github.com/JuliaCommunity/SlackBridge)

---

<div class="post-metadata">

**Author:** ![rvignolo](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rvignolo/32/33498_2.png) [@rvignolo](https://discourse.julialang.org/u/rvignolo)\
**Post date:** [February 1, 2021, 1:22pm UTC](https://discourse.julialang.org/t/hi-suppose-i-want-to-code-a-function-that-returns-a-svector-but-each-component/54372/2 "2021-02-01T13:22:45Z")

</div>

It seems that the function was not translated correctly from Slack:

```julia
function test(::Val{D}) where {D}
    mv = @MVector zeros(D)
    for i in 1:D
        mv[i] = i + 1
    end
    sv = convert(SVector, mv)
    return sv
end

```

Then:

```julia
test(Val{4}())

```

---

<div class="post-metadata">

**Author:** ![logankilpatrick](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/logankilpatrick/32/38123_2.png) [@logankilpatrick](https://discourse.julialang.org/u/logankilpatrick)\
**Post date:** [February 1, 2021, 2:13pm UTC](https://discourse.julialang.org/t/hi-suppose-i-want-to-code-a-function-that-returns-a-svector-but-each-component/54372/3 "2021-02-01T14:13:05Z")

</div>

Fixed 🙂

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [February 1, 2021, 2:36pm UTC](https://discourse.julialang.org/t/hi-suppose-i-want-to-code-a-function-that-returns-a-svector-but-each-component/54372/4 "2021-02-01T14:36:37Z")

</div>

This is shorter, simpler, and probably faster:

```julia
test2(n::Val) = SVector(ntuple(i -> float(i + 1), n))

```

The key is that an `SVector` can be constructed from a tuple, and a `tuple` can be constructed efficiently using `ntuple` with a `Val` argument so that the size is known at compile time.

---

<div class="post-metadata">

**Author:** ![rvignolo](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rvignolo/32/33498_2.png) [@rvignolo](https://discourse.julialang.org/u/rvignolo)\
**Post date:** [February 1, 2021, 2:50pm UTC](https://discourse.julialang.org/t/hi-suppose-i-want-to-code-a-function-that-returns-a-svector-but-each-component/54372/5 "2021-02-01T14:50:05Z")

</div>

Hi @stevengj, thanks for your reply!

I have a more complicated case, where each value in the vector depends on more complicated expressions. This is the actual function that I am coding:

```julia
@inline function drift(u, p::LMMP{false,D,D,true,Terminal}, t) where {D}
    @unpack Tenors, τ, ρ = p
    σ = p.σ(t)

    du = @MVector zeros(eltype(u), D)

    @inbounds begin
        # 'i' ranges from 2 to D-1 because L₁ and LN have μ = 0
        for i in 2:D-1
            if t ≤ Tenors[i]
                for j in i+1:D
                    du[i] += (ρ[i,j] * τ[j] * σ[j] * u[j]) / (1 + τ[j] * u[j])
                end
                du[i] *= (-σ[i] * u[i])
            end
        end
    end

    return convert(SVector, m)
end

```

Should I also implement the tuple strategy?

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [February 1, 2021, 4:26pm UTC](https://discourse.julialang.org/t/hi-suppose-i-want-to-code-a-function-that-returns-a-svector-but-each-component/54372/6 "2021-02-01T16:26:48Z")

</div>

You could do

```julia
return SVector(ntuple(Val{D}()) do i
    du = zero(eltype(u))
    if t ≤ Tenors[i]
        ... same as above...
    end
    du
end)

```

---

<div class="post-metadata">

**Author:** ![rvignolo](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rvignolo/32/33498_2.png) [@rvignolo](https://discourse.julialang.org/u/rvignolo)\
**Post date:** [February 1, 2021, 4:41pm UTC](https://discourse.julialang.org/t/hi-suppose-i-want-to-code-a-function-that-returns-a-svector-but-each-component/54372/7 "2021-02-01T16:41:15Z")

</div>

This is great, thank you so much! I will try it!

---

<div class="post-metadata">

**Author:** ![rvignolo](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rvignolo/32/33498_2.png) [@rvignolo](https://discourse.julialang.org/u/rvignolo)\
**Post date:** [February 1, 2021, 7:59pm UTC](https://discourse.julialang.org/t/hi-suppose-i-want-to-code-a-function-that-returns-a-svector-but-each-component/54372/8 "2021-02-01T19:59:32Z")

</div>

I have tested both and using `MVector` is faster… This is a MWE:

```julia
using BenchmarkTools
using StaticArrays
using UnPack

N = 10
τ = @SVector [0.25 for i in 1:N]
Tenors = vcat(zero(eltype(τ)), cumsum(τ))
σ(t) = @SVector ones(10)
ρ = @SMatrix rand(N,N)
u = @SVector ones(N)
p = (τ = τ, Tenors = Tenors, σ = σ, ρ = ρ)
t = 0.1
val = Val{N}()

@inline function driftlmm1(u, p, t, ::Val{D}) where {D}
    @unpack Tenors, τ, ρ = p
    σ = p.σ(t)

    du = @MVector zeros(eltype(u), D)

    @inbounds begin
        # 'i' ranges from 2 to D-1 because L₁ and LD have μ = 0
        for i in 2:D-1
            if t ≤ Tenors[i]
                for j in i+1:D
                    du[i] += (ρ[i,j] * τ[j] * σ[j] * u[j]) / (1 + τ[j] * u[j])
                end
                du[i] *= (-σ[i] * u[i])
            end
        end
    end

    return convert(SVector, du)
end

@btime driftlmm1($u, $p, $t, $val)
# 152.777 ns (0 allocations: 0 bytes)

@inline function driftlmm2(u, p, t, ::Val{D}) where {D}
    @unpack Tenors, τ, ρ = p
    σ = p.σ(t)

    @inbounds begin
        return SVector(ntuple(Val{D}()) do i
            du = zero(eltype(u))
            if t ≤ Tenors[i]
                for j in i+1:D
                    du += (ρ[i,j] * τ[j] * σ[j] * u[j]) / (1 + τ[j] * u[j])
                end
                du *= (-σ[i] * u[i])
            end
            du
        end)
    end
end

@btime driftlmm2($u, $p, $t, $val)
# 178.298 ns (0 allocations: 0 bytes)

```

Any ideas?

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [February 1, 2021, 9:14pm UTC](https://discourse.julialang.org/t/hi-suppose-i-want-to-code-a-function-that-returns-a-svector-but-each-component/54372/9 "2021-02-01T21:14:45Z")

</div>

> [@rvignolo](#):
>
> Any ideas?

I’m not sure if the `@inbounds` propagates to the inside of the `do` block.

---

<div class="post-metadata">

**Author:** ![rvignolo](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rvignolo/32/33498_2.png) [@rvignolo](https://discourse.julialang.org/u/rvignolo)\
**Post date:** [February 2, 2021, 12:14am UTC](https://discourse.julialang.org/t/hi-suppose-i-want-to-code-a-function-that-returns-a-svector-but-each-component/54372/10 "2021-02-02T00:14:23Z")

</div>

I have removed `@inbounds` and `@inline` in both cases and the one using `MVector` is still faster.

Any way, the method that you show me is great.

I was wondering if there is a faster way!
