How to concatenate a 2d array to a 3d array

Just trying to add an extra column to check1 (which has 4 rows) for both layers of dim 3, so I figured I could just concatenate it with the 4x2 matrix check2.

MWE:

Random.seed!(1)
check1 = rand(4,3,2)
[:, :, 1] =
0.236033    0.488613  0.251662
0.346517    0.210968  0.986666
0.312707    0.951916  0.555751
0.00790928  0.999905  0.437108

[:, :, 2] =
0.424718  0.251379   0.0769509
0.773223  0.0203749  0.640396
0.28119   0.287702   0.873544
0.209472  0.859512   0.278582

check2 = rand(4,2)
4×2 Array{Float64,2}:
0.751313   0.0856352
0.644883   0.553206
0.0778264  0.46335
0.848185   0.185821

check3 = cat(check1,check2,dims=(1,3))
ERROR: DimensionMismatch("mismatch in dimension 2 (expected 3 got 2)")

What I was expecting:

4×3×2 Array{Float64,3}:
[:, :, 1] =
0.236033    0.488613  0.251662    0.751313
0.346517    0.210968  0.986666    0.644883
0.312707    0.951916  0.555751    0.0778264
0.00790928  0.999905  0.437108    0.848185

[:, :, 2] =
0.424718  0.251379   0.0769509 0.0856352
0.773223  0.0203749  0.640396 0.553206
0.28119   0.287702   0.873544 0.46335
0.209472  0.859512   0.278582 0.185821

Edit: corrected 'expected check3’

1 Like

Put the two objects in the same shape, and then do a horizontal concatenate:

julia> hcat(check1, reshape(check2, 4, 1, 2))
4×4×2 Array{Float64,3}:
[:, :, 1] =
 0.236033    0.488613  0.251662  0.751313
 0.346517    0.210968  0.986666  0.644883
 0.312707    0.951916  0.555751  0.0778264
 0.00790928  0.999905  0.437108  0.848185

[:, :, 2] =
 0.424718  0.251379   0.0769509  0.0856352
 0.773223  0.0203749  0.640396   0.553206
 0.28119   0.287702   0.873544   0.46335
 0.209472  0.859512   0.278582   0.185821

This is not what you were expecting, but I do think you copy-pasted your expectations wrong, as the same column is used two times (and the other is not used).

3 Likes

That works, thanks.
Yep the original post was wrong. I’ll correct it.