Nested array slicing

老子叫甜甜 提交于 2019-12-20 03:02: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=0:0.1:1
        vector = (1-i)a+(i*b)
        push!(line, vector)
    end
    return line
end

This function returns an array of vectors containing x-y positions

Vector[11]
 > Float64[2]
 > Float64[2]
 > Float64[2]
 > Float64[2]
  .
  .
  .

Now I want to seprate all x and y coordinates of these vectors to plot them with plotyjs.

I have already tested some approaches with no success! What is a correct way in Julia to achive this?


回答1:


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



来源:https://stackoverflow.com/questions/41183481/nested-array-slicing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!