7

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

1
  • 1
    I did not see what was written on Slack, but I have shared what I typically do in this case, as it is indeed common. Commented Oct 3, 2019 at 11:54

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.