Free last part of a vector

I have allocated a long vector, and filled it to nearly the end.
I don’t need the last few, remaining elements. That memory can be freed.

Is there a way to ‘chop off’ the last part of the vector – without creating a view, or copying to a new vector (by slicing, x[1:i]) ?

(Context is, I’m simulating a Poisson process within a fixed time interval:

using Distributions

function gen_Poisson_spikes(rate, duration)
    N_distr = Poisson(rate * duration)
    max_N = cquantile(N_distr, 1e-14)  # Cannot take a much smaller chance than ~1e-15:
                                       # https://github.com/JuliaStats/Rmath-julia/blob/master/src/qpois.c#L86
    spikes = Vector{Float64}(undef, max_N)
    ISI_distr = Exponential(inv(rate))
    i = 0
    t = zero(duration)
    while t ≤ duration
        i += 1
        spikes[i] = (t += rand(ISI_distr))
    end
    spikes[1:i]
end

For rate = 100 Hz and duration = 10 minutes, the typical N ≈ 60000, and max_N (at p < 1e-14) is 61855.
i.e. we don’t need the last ~1855, uninitialized elements of spikes.
)

try to check if the resize!() function is right for you

1 Like