I have a 3d array, and would like to copy the bottom "slice", i.e. final row of all columns and dim3, and then paste it on the bottom of the original 3d array. For some reason Julia considers my "slice" as 2d array rather than a 3 d array and will not allow concatenating. Have tried several things, no luck. Thx. J MWE here.
If I start with this:
3×2×2 Array{Int64,3}:
[:, :, 1] =
1 4
2 5
3 6
[:, :, 2] =
1 4
2 5
3 6
I want to end up with this:
3×2×2 Array{Int64,3}:
[:, :, 1] =
1 4
2 5
3 6
3 6
[:, :, 2] =
1 4
2 5
3 6
3 6
a, b = [1;2;3], [4;5;6]
c = hcat(a,b)
d = cat(c,c,dims=3)
size(d)
e = d[3,:,:]
f = hcat(d,3)
ERROR: DimensionMismatch("mismatch in dimension 1 (expected 3 got 1)")
This is the way to do it:
julia> mat = reshape(repeat(1:6, 2), 3, 2, 2)
3×2×2 Array{Int64,3}:
[:, :, 1] =
1 4
2 5
3 6
[:, :, 2] =
1 4
2 5
3 6
julia> [mat; mat[3:3, :, :]]
4×2×2 Array{Int64,3}:
[:, :, 1] =
1 4
2 5
3 6
3 6
[:, :, 2] =
1 4
2 5
3 6
3 6
Note that using 3 drops one dimension but using 3:3 retains it.
On the other hand if you had a 2D array and wanted to add a dimension to it in the front that would have size equal to 1 then you can do:
julia> mat2 = mat[3, :, :]
2×2 Array{Int64,2}:
3 3
6 6
julia> reshape(mat2, 1, size(mat2)...)
1×2×2 Array{Int64,3}:
[:, :, 1] =
3 6
[:, :, 2] =
3 6
and then you can concatenate such a matrix with other 3D matrices.
A small remark to add to the nice solution by Bogumil Kaminski:
cat(mat, mat[3:3,:,:]; dims=1) # concatenates as: [mat; mat[3:3, :, :]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With