gpt4 book ai didi

julia - 如何最好地表示点列表

转载 作者:行者123 更新时间:2023-12-04 20:04:44 25 4
gpt4 key购买 nike

我在二维空间中有一组点,我将它们表示为 2 级数组:

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

这是一种有用的表示,因为它允许轻松访问点的 x 和 y 分量。例如。
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

定义这样一组点、访问组件和检查成员资格的正确朱利安方法是什么?

更新:正如@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))

最佳答案

I have a set of points in 2D space that I'm representing as a rank-2 array [...]



这需要一组对(具有两个元素的元组)。
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)})

关于julia - 如何最好地表示点列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27155176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com