Returning a function multiple time to an array

i have this function that i’m trying to call it more than once and push the return value to an array

function f(x,y)
    
    return s=x+y
end
for i=0:3
    x=i*pi/2
    s=f(x,2)
    global X=[]
    push!(X,s)
end
X

but all i get is the last value which means for i=3 but i want all the values to be appended in the array X

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