An error from stacking a new array with an initialization array (empty)

Here is my code:

A = [];
for ...
A = vcat(A, b);
end

I’m getting the below error. Before A is assigned any values, it is an empty array, and the program is complaining that:
number of columns of each array must match

size(A) = (0,)
size(b) = (26, 29)

Clearly, this is a bad habit I brought here from Matlab, so how do Julian folks get around this issue? Many thanks!

Maybe you want to push! into A? Note that growing arrays like that is not very performant.

1 Like

Many thanks for the reply!

So I should do push!(A, b)? Unfortunately, it does not work either. How do I specify the fact that I want the item being pushed to be appended vertically?

can you provide a simple example of the code?

The problem is that you can’t vcat a matrix and a vector. And even if your A were a matrix, you still can’t vcat a 26x29 matrix to a 0x0 matrix (for a vertical concatenation, the number of rows must match).

You could create a 0x29 matrix and then use vcat, but it should be easier to avoid this entirely using reduce:

julia> my_matrices = [[1 2; 3 4], [5 6; 7 8], [9 10; 11 12]]
3-element Vector{Matrix{Int64}}:
 [1 2; 3 4]
 [5 6; 7 8]
 [9 10; 11 12]

julia> reduce(vcat, my_matrices)
6×2 Matrix{Int64}:
  1   2
  3   4
  5   6
  7   8
  9  10
 11  12

reduce combines elements of a collection pairwise, and vcat does vertical concatenation, so reduce(vcat, ...) combines all the matrices in the collection by vertical concatenation. Julia actually has a special implementation (still in Julia, just written carefully) that makes that particular combination of operations more efficient than a naive approach. If you want to see how it works, you can do: @edit reduce(vcat, my_matrices)

1 Like

Actually, it did not work either.

Here is my code:

using MAT
# Read the bathymetric values out of the mat file:
F1 = matopen("/test.mat");
A = read(F1, "A");
b = read(F1, "b");
close(F1);
A = reduce(vcat, [A, b])

Here is a link to download the “test.mat” file storing my data:

Looks like it will work if I define my A as the below, instead of using A=;

A = Array{Float64}(undef, 0, 29);