leon
December 16, 2021, 7:23pm
#1
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?

juliohm
December 16, 2021, 7:32pm
#2
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

leon
December 16, 2021, 7:34pm
#3
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);

juliohm
December 16, 2021, 7:37pm
#4
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

DNF
December 16, 2021, 7:40pm
#5

leon:

Matrices

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

leon
December 16, 2021, 7:50pm
#6
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

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