Add row to 2D array in a loop

Hi,

my aim is to add a new row to a 2D array in a for-loop.

If I execute

A = Array{Int64}(undef, 0, 2)
A = [A; [1 2]]
A = [A; [2 3]]
println(A)

I receive [1 2; 2 3] that is correct. But if I run it in a for loop:

C = Array{Int64}(undef, 0, 2)

for i = 1:5
global C = [C; [i, i+1]]
end
println©

I get

ERROR: LoadError: ArgumentError: number of columns of each array must match (got (2, 1))
Stacktrace:
[1] _typed_vcat(::Type{Int64}, ::Tuple{Array{Int64,2},Array{Int64,1}}) at .\abstractarray.jl:1439
[2] typed_vcat at .\abstractarray.jl:1453 [inlined]
[3] vcat(::Array{Int64,2}, ::Array{Int64,1}) at D:\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.5\SparseArrays\src\sparsevector.jl:1077
[4] top-level scope at C:\Users\M\Desktop\tsssspp.jl:11
[5] include(::String) at .\client.jl:457
[6] top-level scope at REPL[48]:1
in expression starting at C:\Users\M\Desktop\tsssspp.jl:10

I do not understand the problem.

In your first example, you are concatenating row vectors like [1 2], which works as expected. In the second example, you are concatenating a regular vector like [i, i+1]. Note the comma in there which means this is an Array{T,1} (a vector), not an Array{T,2} (a row of a matrix). If you get rid of that comma, the row concatenation should work.

julia> C = Array{Int64}(undef, 0, 2)
0×2 Array{Int64,2}

julia> for i = 1:5
           global C = [C; [i i+1]]
       end

julia> C
5×2 Array{Int64,2}:
 1  2
 2  3
 3  4
 4  5
 5  6

By the way, it’s easier to read your code if you put it into a code block by surrounding the code with triple backtics ``` on both sides.

1 Like

You may be interested in