How does one add rows to a Julia array?

I have an empty array A:

A = Array{Float64}(undef, 0, 2)

and a vector that I want to add:

m = rand(2)

I try to do this:

A = [A;m]
ArgumentError: number of columns of each array must match (got (2, 1))

Thanks.

4 Likes

Your first array is 2-dimensional. Try this

julia> A = Array{Float64}(undef, 2)
2-element Array{Float64,1}:
 6.9016019742975e-310
 6.9016002397421e-310

julia> m = rand(2)
2-element Array{Float64,1}:
 0.6212512011951012
 0.949613146540832 

julia> A = [A;m]
4-element Array{Float64,1}:
 6.9016019742975e-310
 6.9016002397421e-310
 0.6212512011951012  
 0.949613146540832 
1 Like

Thank you so much for your help.
What I really want is an nx2 array (Add rows to array “A”)

[A; m'] works. The point is that thing you append must be a row vector (formed by m' or transpose(m)) or in any case a matrix with the same number of columns. A one-dimensional array like m, in contrast, is treated by Julia as a “column vector” (one column).

3 Likes

In the docs: Concatenation

Concatenation need to create new a array and it’s very inefficiently! because the vcat function is used

julia> @which [A;m']
vcat(A::Union{Array{T,1}, ...

Multidimensional arrays in Julia are stored in column-major order. A good discussion is

I guess you could also allocate a large array if you know the maximum possible size, and crop afterwards.