How to add dimension to an array? (opposite to "compression")

I will never remember how to do this.

How to go

  • from a vector (size (n1)) to a column matrix (size (n1,1))?
  • or from a matrix (size (n1,n2)) to an array {T, 3} (size (n1,n2,1))?
  • or from the array {T, 3} (size (n1,n2,n3)) to the array {T, 4} (size (n1,n2,n3, 1))?
  • etc.

I want to know to take an Array and use it to define a new array with an extra single linear finite size. That is the oppositesqueeze

+4
source share
2 answers

, , cat ndims . , " (singleton) , ". .

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

.

+1

reshape.

:

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
+8

Source: https://habr.com/ru/post/1670150/


All Articles