Nested array slicing

2019-02-27 12:16发布

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条回答
淡お忘
2楼-- · 2019-02-27 13:17

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

查看更多
登录 后发表回答