4
votes

I am trying to return an array of different sized arrays in a Julia function. In the function, the arrays will be initialized and, in a loop, they will have elements, that are other arrays, pushed to end of the array at each iteration. But I am getting the following error:

MethodError: no method matching push!(::Type{Array{Array{Float64,1},1}}, ::Array{Float64,1})

I am initializing an array of arrays:

x = Array{Array{Float64,1},1}

But when a push! other array, I get the error:

push!(x, y)

In python I would just append the new arrays to a list and return the list, how can I accomplish it in Julia?

1

1 Answers

4
votes

Your statement:

julia> x = Array{Array{Float64,1},1}
Array{Array{Float64,1},1}

assigns to x name of the type.

In order to create an instance of this type add () after it:

julia> x = Array{Array{Float64,1},1}()
0-element Array{Array{Float64,1},1}

and now you can push! to it:

julia> push!(x, [2.5, 3.5])
1-element Array{Array{Float64,1},1}:
 [2.5, 3.5]

Note that you could have initiated x with an empty vector accepting vectors of Float64 in the following way:

julia> x = Vector{Float64}[]
0-element Array{Array{Float64,1},1}

We use two features here:

  1. Vector{Float64} is a shorthand for Array{Float64, 1}.
  2. If you create an empty vector using [] syntax you can prepend a type of its elements in front of it just like I did in the example.