Can an array have new elements added to it on the fly?

I’m writing a Runge-Kutta-Fehlberg solver (and yes I know that ODE.jl has one already, this is something I’m doing to learn more about both Julia and the method) and as the step sizes are adaptive it is not clear from the beginning how many x values there are going to be that I need to store in an array. So I’m wondering, is there a way to add new elements to an array on the fly (expanding the array, not merely redefining the value of existing elements in the array)? My apologies if I’m not clear, but I’m not entirely sure how else to explain this. See I don’t want to define a massive x array of zeros and then redefine each element using something like x[i+1] = x[i] + sh; in a loop, as I’ll end up with an array that will likely still have a heap of zeros left in it (as I don’t know exactly how many elements my vector will end up having as the method is adaptive). Likewise, I don’t want to underestimate the size of x I need as I’ll get an index out of bounds error when i gets sufficiently large.

you’re looking for push!(x, x[end]+sh).

3 Likes

How do I initialize x? Can I define the first element like x = 0?

x=Int[] (or Float64[] if you want floating point numbers. You should skim some portions of Julia Documentation · The Julia Language which has lots of useful info.

2 Likes

x = [0.0]

defines an array with the single element 0.0.

But you should check out some of the tutorials listed at Get started with Julia

1 Like