How do I add a dimension to an array? (opposite of `squeeze`)

Another easy way other than reshaping to an exact shape, is to use cat and ndims together. This has the added benefit that you can specify "how many extra (singleton) dimensions you would like to add". e.g.

a = [1 2 3; 2 3 4];
cat(ndims(a) + 0, a)  # add zero singleton dimensions (i.e. stays the same)
cat(ndims(a) + 1, a)  # add one singleton dimension
cat(ndims(a) + 2, a)  # add two singleton dimensions

etc.


UPDATE (julia 1.3). The syntax for cat has changed in julia 1.3 from cat(dims, A...) to cat(A...; dims=dims).

Therefore the above example would become:

a = [1 2 3; 2 3 4];
cat(a; dims = ndims(a) + 0 )
cat(a; dims = ndims(a) + 1 )
cat(a; dims = ndims(a) + 2 )

etc.

Obviously, like Dan points out below, this has the advantage that it's nice and clean, but it comes at the cost of allocation, so if speed is your top priority and you know what you're doing, then in-place reshape operations will be faster and are to be preferred.


Some time before the Julia 1.0 release a reshape(x, Val{N}) overload was added which for N > ndim(x) results in the adding of right most singleton dimensions.

So the following works:

julia> add_dim(x::Array{T, N}) where {T,N} = reshape(x, Val(N+1))
add_dim (generic function with 1 method)

julia> add_dim([3;4])
2×1 Array{Int64,2}:
 3
 4

julia> add_dim([3 30;4 40])
2×2×1 Array{Int64,3}:
[:, :, 1] =
 3  30
 4  40

julia> add_dim(rand(4,3,2))
4×3×2×1 Array{Float64,4}:
[:, :, 1, 1] =
 0.0737563  0.224937  0.6996
 0.523615   0.181508  0.903252
 0.224004   0.583018  0.400629
 0.882174   0.30746   0.176758

[:, :, 2, 1] =
 0.694545  0.164272   0.537413
 0.221654  0.202876   0.219014
 0.418148  0.0637024  0.951688
 0.254818  0.624516   0.935076

Try this

function extend_dims(A,which_dim)
       s = [size(A)...]
       insert!(s,which_dim,1)
       return reshape(A, s...)
       end

the variable extend_dim specifies which dimension to extend

Thus

extend_dims(randn(3,3),1)

will produce a 1 x 3 x 3 array and so on.

I find this utility helpful when passing data into convolutional neural networks.


You can do this with reshape.

You could define a method for this:

add_dim(x::Array) = reshape(x, (size(x)...,1))

julia> add_dim([3;4])
2×1 Array{Int64,2}:
 3
 4

julia> add_dim([3;4])
2×1 Array{Int64,2}:
 3
 4

julia> add_dim([3 30;4 40])
2×2×1 Array{Int64,3}:
[:, :, 1] =
 3  30
 4  40

julia> add_dim(rand(4,3,2))
4×3×2×1 Array{Float64,4}:
[:, :, 1, 1] =
 0.483307  0.826342   0.570934
 0.134225  0.596728   0.332433
 0.597895  0.298937   0.897801
 0.926638  0.0872589  0.454238

[:, :, 2, 1] =
 0.531954  0.239571  0.381628
 0.589884  0.666565  0.676586
 0.842381  0.474274  0.366049
 0.409838  0.567561  0.509187

Tags:

Julia