# Concatenating matrices with an empty matrix

Hi,

I wish to construct a matrix whose blocks depend on (a lot of) conditions. Since I don’t know the final size of my A matrix at the beginning or the first block to start with, I intend to delare it empty and then add (append, push, concatenate, …) new rows from another B matrix. I checked other posts but couldn’t find a satisfying easy way to proceed. Do you have suggestions about the way to declare A or to concatenate starting an empty matrix ? Or do you see a complete different ways to achieve the same result ?

``````# OBJECTIVE
A=... # "A" defined somehow
B=some_matrix
C=some_other_matrix
if condition1   A=vcat(A,B)   end
if condition2   A=vcat(A,C)   end
# A should be the size of B, C or [B,C]

# TRIAL 1
A=[]
B=rand(5,2)
# next lines are indepedent from one another
append!(A;B)    # not working
A=vcat(A,B)     # not working
A=[A,B]         # not a matrix

# TRIAL 2
A=Array{Float64,2}
B=rand(5,2)
# next lines are indepedent from one another
append!(A;B)    # not working
A=vcat(A,B)     # first row not expected
A=[A,B]         # not a matrix
``````

This works, but your “empty” initial array needs to have the right number of columns and the right element type if you want to append. This works, for example:

``````A = Matrix{Int}(undef, 0, 2)  # 0x2 array of Int
B = rand(5, 2)
A = [A; B] # equivalent to A = vcat(A, B)
``````

However, note that building up a large matrix this way has suboptimal efficiency because each `[A; B]` or `vcat(A, B)` call allocates a new array. (`append!` only works for 1d arrays.)

You can use ElasticArrays.jl to instead make a matrix that can grow or shrink in-place, but only in the last dimension. So to use it you will need to re-think your logic in terms of appending columns, not rows. (At the very end you can transpose it, of course, but usually you can rearrange your algebra to work with the column-oriented matrix instead.)

Thank you. I didn’t think that giving the right number of columns would make the difference.
I will have a look to ElasticArrays.jl too.