gpt4 book ai didi

arrays - 如何在 Julia 中将向量转换为向量的向量

转载 作者:行者123 更新时间:2023-12-02 21:02:22 25 4
gpt4 key购买 nike

我有一个向量 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com