如何将矢量转换为Julia中的矢量矢量

时间:2016-06-06 10:35:15

标签: arrays julia

我有一个Vector x=[1.00, 1.50, 1.00, 2.30, 4.20, 1.00],还有一个n=[2, 1, 3]

我想将Vector x转换为Vector of Vector,如下所示:

x[1] = [1.00, 1.50] x[2] = 1.00 x[3] = [2.30, 4.20, 1.00]

x的每个向量中,维度由n确定。

实现这个的更快的方法是什么?谢谢!

2 个答案:

答案 0 :(得分:5)

虽然对速度不是很确定,但我们也可以使用理解(像往常一样):

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) ]

答案 1 :(得分:0)

另一种方法:

resp, err := http.Get("http://example.com/")
if err != nil {
    // handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)

// explore
// fmt.Println(string(body))

if bytes.Contains(body, []byte("I'm Feeling Lucky")) {
     fmt.Println("Correct Website")
}

输出:

x = [1.00, 1.50, 1.00, 2.30, 4.20, 1.00]
n = [2, 1, 3]

g = Array{Any}(length(n))

for i in 1:length(n)        
    o = 1 + sum(n[1:(i-1)])
    p = sum(n[1:i])
    g[i] = x[o:p]
end

g