如何向数组添加维度?(与“挤压"相反) [英] How do I add a dimension to an array? (opposite of `squeeze`)

查看:19
本文介绍了如何向数组添加维度?(与“挤压"相反)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我永远不记得如何做到这一点.

I can never remember how to do this this.

怎么走

  • 从向量(大小(n1))到列矩阵(大小(n1,1))?
  • 或从矩阵(大小 (n1,n2)) 到数组{T,3}(大小 (n1,n2,1))?
  • 或从 Array{T,3} (size (n1,n2,n3)) 到 Array{T,4} (size (n1,n2,n3, 1))?
  • 等等.
  • 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.

我想知道使用 Array 并使用它来定义一个具有额外单例尾随维度的新 Array.IE.squeeze

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

推荐答案

在 Julia 1.0 发布之前的一段时间,为 N 添加了 reshape(x, Val{N}) 重载>ndim(x) 导致添加最右边的单例维度.

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.

所以下面的工作:

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

这篇关于如何向数组添加维度?(与“挤压"相反)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆