我有一个向量 x=[1.00, 1.50, 1.00, 2.30, 4.20, 1.00]
和另一个 n=[2, 1, 3]
。
我想将我的向量 x
转换为向量的向量,如下所示:
x[1] = [1.00, 1.50]
x[2] = 1.00
x[3] = [2.30, 4.20, 1.00]
其中,在x
的每个向量中,维度由n
确定。
什么是更快的实现方法?谢谢!
最佳答案
虽然不太确定速度,但我们也可以使用理解(像往常一样):
julia> x = [1.00, 1.50, 1.00, 2.30, 4.20, 1.00]
julia> n = [2, 1, 3]
julia> off = [ 0 ; cumsum(n) ] # offset indices
4-element Array{Int64,1}:
0
2
3
6
julia> Vector{Float64}[ x[ off[i]+1 : off[i]+n[i] ] for i=1:length(n) ]
3-element Array{Array{Float64,1},1}:
[1.0,1.5]
[1.0]
[2.3,4.2,1.0]
在未来版本(>= v0.5?)中,我们可能需要对每个向量进行copy()
,以使获得的向量独立于原始x[:]
>(虽然不太确定...)
julia> Vector{Float64}[ copy( x[ off[i]+1 : off[i]+n[i] ] ) for i=1:length(n) ]
关于arrays - 如何在 Julia 中将向量转换为向量的向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37655219/