15

I can never remember how to do this this.

How can go

  • from a Vector (size (n1)) to a Column Matrix (size (n1,1))?
  • or from a Matrix (size (n1,n2)) to a Array{T,3} (size (n1,n2,1))?
  • or from a Array{T,3} (size (n1,n2,n3)) to a Array{T,4} (size (n1,n2,n3, 1))?
  • and so forth.

I want to know to take Array and use it to define a new Array with an extra singleton trailing dimension. I.e. the opposite of squeeze

0

4 Answers 4

22

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

3 Comments

widen is a confusing name for this operation because it already means something very different. Some people might read that code expecting it to be applied to each element of the array, as in widen.(A).
@tholy, ok. changed to add_dim. though not 100% happy with that either. Do you have a suggestion for the name? I know TensorFlow uses expand_dims(x, insert_at_ind) but that has a second argument; rather than just using trailing.
another name possibility: rpad(M,3) will make Array M into a 3-dim Array by adding length 1 dimensions on the right (lpad similarly on the left). it overloads methods for strings, but sort of similar action. Definition could be something like: Base.rpad(m::AbstractArray,n::Integer) = reshape(m,size(m)...,[1 for i=1:n-ndims(m)]...)
4

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.

5 Comments

This solution looks clean, but note reshape methods are 40x times faster on a trivial benchmark with almost no allocation.
Yeah, that makes sense; reshape just returns a "view" into the initial object (albeit not visibly so in terms of its returned type). I agree that if a view rather than a new array is the intended behaviour then a reshape-based approach would be preferable.
@chunjiw the syntax of the cat command has changed (not altogether surprising, julia kept changing syntax like underwear back then). I'll update with the new syntax.
Is there a way to insert a (singleton) dimension on the left instead of on the right?
@becko I don't think it's possible with this method. I would use reshape for that.
4

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.

1 Comment

I found this to be much more useful than the accepted answer. Thank you!
3

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

2 Comments

Is reshape(x, Val{N}) documented? I can't find it.
May have worked in the past, but is not working anymore (as of Julia v1.8)

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.