Nested array slicing

后端 未结 1 1067
我寻月下人不归
我寻月下人不归 2021-01-22 11:54

Let\'s say I have an array of vectors:

\"\"\" simple line equation \"\"\"
function getline(a::Array{Float64,1},b::Array{Float64,1})
    line = Vector[]
    for i         


        
相关标签:
1条回答
  • 2021-01-22 12:38

    You can broadcast getindex:

    xs = getindex.(vv, 1)
    ys = getindex.(vv, 2)
    

    Edit 3:

    Alternatively, use list comprehensions:

    xs = [v[1] for v in vv]
    ys = [v[2] for v in vv]
    

    Edit:

    For performance reasons, you should use StaticArrays to represent 2D points. E.g.:

    getline(a,b) = [(1-i)a+(i*b) for i=0:0.1:1] 
    
    p1 = SVector(1.,2.)
    p2 = SVector(3.,4.)
    
    vv = getline(p1,p2)
    

    Broadcasting getindex and list comprehensions will still work, but you can also reinterpret the vector as a 2×11 matrix:

    to_matrix{T<:SVector}(a::Vector{T}) = reinterpret(eltype(T), a, (size(T,1), length(a)))
    
    m = to_matrix(vv)
    

    Note that this does not copy the data. You can simply use m directly or define, e.g.,

    xs = @view m[1,:]
    ys = @view m[2,:]
    

    Edit 2:

    Btw., not restricting the type of the arguments of the getline function has many advantages and is preferred in general. The version above will work for any type that implements multiplication with a scalar and addition, e.g., a possible implementation of immutable Point ... end (making it fully generic will require a bit more work, though).

    0 讨论(0)
提交回复
热议问题