1
votes

I have a Vector x=[1.00, 1.50, 1.00, 2.30, 4.20, 1.00] and also another one n=[2, 1, 3].

I would like to transform my Vector x into a Vector of Vectors as follows:

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

where in each Vector of x, the dimension is determined by n.

What could be the faster way to implement this? Thanks!

2
A one-line solution using Iterators package (install with Pkg.add("Iterators"): map(t->x[(t[1]+1):t[2]],partition(cumsum([0;n]),2,1)) - Dan Getz

2 Answers

5
votes

Though not very sure about the speed, we can also use comprehension (as usual):

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]

In future versions (>= v0.5?), we may need copy() for each vector to make the obtained vector independent of the original x[:] (though not very sure...)

julia> Vector{Float64}[ copy( x[ off[i]+1 : off[i]+n[i] ] ) for i=1:length(n) ]
0
votes

Another approach:

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

Output:

3-element Array{Any,1}:
 [1.0,1.5]    
 [1.0]        
 [2.3,4.2,1.0]