如何最好地表示点列表

时间:2014-11-26 17:17:14

标签: julia

我在2D空间中有一组点,我将其表示为排名2数组:

points = [0 0; 0 1; 1 0]

这是一个有用的表示,因为它允许轻松访问点的x和y分量。 E.g。

plot(x=points[:,1], y=points[:,2])

但是,有时最好将points视为一个列表/一组点而不是一个矩阵。例如,我需要检查某个点(例如[0 1])是否是points的元素。直接版本不起作用:

[0 1] in points  # is false

相反,我必须手动将points扩展为点列表:

[0 1] in [points[i,:] for i in 1:size(points)[1]]  # is true

定义这样一组点,访问组件和检查成员身份的正确 julian 方式是什么?


更新:正如@Jubobs建议的那样,我继续定义了我自己的类型。事实证明,我实际上需要一个向量,所以我继续称它为Vec2而不是Point

immutable Vec2{T<:Real}
    x :: T
    y :: T
end
Vec2{T<:Real}(x::T, y::T) = Vec2{T}(x, y)
Vec2(x::Real, y::Real) = Vec2(promote(x,y)...)

convert{T<:Real}(::Type{Vec2{T}}, p::Vec2) =
    Vec2(convert(T,p.x), convert(T,p.y))
convert{Tp<:Real, T<:Real, S<:Real}(::Type{Vec2{Tp}}, t::(T,S)) =
    Vec2(convert(Tp, t[1]), convert(Tp, t[2]))

promote_rule{T<:Real, S<:Real}(::Type{Vec2{T}}, ::Type{Vec2{S}}) =
    Vec2{promote_type(T,S)}

+(l::Vec2, r::Vec2) = Vec2(l.x+r.x, l.y+r.y)
-(l::Vec2, r::Vec2) = Vec2(l.x-r.x, l.y-r.y)
*(a::Real, p::Vec2) = Vec2(a*p.x, a*p.y)
*(p::Vec2, a::Real) = Vec2(a*p.x, a*p.y)
/(p::Vec2, a::Real) = Vec2(a/p.x, a/p.y)
dot(a::Vec2, b::Vec2) = a.x*b.x + a.y*b.y
zero{T<:Real}(p::Vec2{T}) = Vec2{T}(zero(T),zero(T))
zero{T<:Real}(::Type{Vec2{T}}) = Vec2{T}(zero(T),zero(T))

1 个答案:

答案 0 :(得分:4)

  

我在2D空间中有一组点,我代表的是排名为2的数组[...]

这需要(带有两个元素的元组)。

julia> myset = Set( [(0,0), (0,1), (1,0)] ) # define a set of tuples
Set{(Int64,Int64)}({(0,0),(1,0),(0,1)})

julia> in((0,0),myset)             # testing for membership is easy
true

julia> x = map (p -> p[1], myset)  # access to x values is easy with 'map'
3-element Array{Any,1}:
 0
 1
 0

julia> y = map (p -> p[2], myset)  # same thing with y values
3-element Array{Any,1}:
 0
 0
 1

julia> push!(myset,(3,2))          # adding an element to the set
Set{(Int64,Int64)}({(0,0),(1,0),(3,2),(0,1)})

julia> pop!(myset,(3,2))           # removing an element from the set
(3,2)

julia> myset
Set{(Int64,Int64)}({(0,0),(1,0),(0,1)})
相关问题