How to stack up multiple 3-dimension matrices into one?

For example, I could have 10 Matrices like the below (A) stored in 10 NetCDF files:

A = rand(5, 3, 2);

My goal is to read them all out and stack them up into a new matrix B with the size of size(B) = (5, 3, 20).

I tried the below:

B = fill(NaN, 5, 3, 0);
for i in 1:10
# read A out of a NetCDF file
B = vcat(B, A);
end

Unfortunately, I got the below error:
DimensionMismatch("mismatch in dimension 3 (expected 0 got 2)")

I wonder what is the best way to do so?

In Julia v1.7 you can use repeated ; to concatenate on higher dimensions:

[A; A] # first dimension
[A;; A] # second dimension
[A;;; A] # third dimension

Notice that vcat and hcat are the verbose versions of [A; A] and [A A].

2 Likes

Thanks! Unfortunately, that will give me the same error.

I think I’m able to figure it out now:
B = cat(B, A, dims=3);

You shouldn’t be rewriting the content of the variable B in a loop. Try to write it in terms of a reduce or mapreduce instead. It will be cleaner and more efficient. in general.

1 Like

This is a nitpick, but it may confuse some (maybe it has confused you as well): a matrix is a 2-dimensional array. 3d arrays are not matrices.

(I was going to add a reference, but, depressingly, in the first three pages of Google hits for “matrix”, there were zero results referring to linear algebra…)

2 Likes

Many thanks.

Would you mind elaborating on how to use reduce?

I’m able to find the documentation but can not make it work:
https://docs.julialang.org/en/v1/base/collections/#Base.reduce-Tuple{Any,%20Any}

Something like the below?
B = reduce(cat, [B, A], dims=3)?

You should use an anonymous function

reduce((x, y) -> cat(x, y; dims = 3), vec)
1 Like

It works.

Many thanks!

You could also do (example for 5 input arrays):

B = cat(A1, A2, A3, A4, A5, dims=3)

# or:
A = [A1, A2, A3, A4, A5]
B = cat(A..., dims=3)
1 Like