Wolf
Wolf

Reputation: 505

Adding an additional dimension to an array

Note: This question/answer is copied from the Julia Slack channel.

If I have an arbitrary Julia Array, how can I add another dimension.

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

The desired output would be e.g.:

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

Or:

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

Upvotes: 7

Views: 1174

Answers (2)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69949

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

Upvotes: 6

Wolf
Wolf

Reputation: 505

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.

Upvotes: 3

Related Questions