Returning a function multiple time to an array

You are creating a new X in every loop iteration, so what you see is only the X created for i=3, which has only one value in it. You want to create X once outside the loop:

julia> X = [];

julia> for i=0:3
           x=i*pi/2
           s=f(x,2)
           push!(X,s)
       end

julia> X
4-element Vector{Any}:
 2.0
 3.5707963267948966
 5.141592653589793
 6.71238898038469

As an aside, don’t use [] to create arrays - as you see above this creates a Vector{Any}, which is terrible for performance. In this case, you should use X = Float64[] to instantiate your array.

As a further aside, it is often helpful to allocate memory in advance rather than push!ing in a loop if you know the size of your result, i.e. X = Vector{Float64}(undef, 4) or X = zeros(4).

6 Likes