如何向数组添加维度? (与“挤压"相反) [英] How do I add a dimension to an array? (opposite of `squeeze`)
本文介绍了如何向数组添加维度? (与“挤压"相反)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我永远不记得该怎么做.
I can never remember how to do this this.
怎么走
- 从向量(大小为
(n1)
)到列矩阵(大小为(n1,1)
)? - 还是从矩阵(大小为
(n1,n2)
)到数组{T,3}(大小为(n1,n2,1)
)? - 还是从数组{T,3}(大小
(n1,n2,n3)
)到数组{T,4}(大小(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发布之前的某个时间,添加了reshape(x, Val{N})
重载,对于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屋!
查看全文