Adding an additional dimension to an array

A less tricky thing I usually do to achieve this is:

julia> reshape(a, 1, :)
1×4 Array{Int64,2}:
 1  2  3  4

julia> reshape(a, :, 1)
4×1 Array{Int64,2}:
 1
 2
 3
 4

(it also seems to involve less typing)

Finally a common case requiring transforming a vector to a column matrix can be done:

julia> hcat(a)
4×1 Array{Int64,2}:
 1
 2
 3
 4

EDIT also if you add trailing dimensions you can simply use ::

julia> a = [1,2,3,4]
4-element Array{Int64,1}:
 1
 2
 3
 4

julia> a[:,:]
4×1 Array{Int64,2}:
 1
 2
 3
 4

julia> a[:,:,:]
4×1×1 Array{Int64,3}:
[:, :, 1] =
 1
 2
 3
 4

The trick is so use [CartesianIndex()] to create the additional axes:

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

And:

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

If you want to get closer to numpy's syntax, you can define:

const newaxis = [CartesianIndex()]

And just use newaxis.

Tags:

Julia