首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何创建矩阵数学中可以使用的点类型

如何创建矩阵数学中可以使用的点类型
EN

Stack Overflow用户
提问于 2017-07-17 03:56:09
回答 1查看 307关注 0票数 2

我想创建一个包含Point2D成员xy的复合类型,这很容易。但我希望它能参与非Point2D的正常数学函数,例如,Point2D(1,2) + [1,1]应该会产生一个值的Vector{Int64} [2,3]

我创建了基于convertpromote_rule朱莉娅的转换()什么时候使用?promote_rule函数,但是后来意识到我的类型需要是convert编辑的一个子类型。但是,当我试图从VectorVector{T}或任何类型的ArrayAbstractArray中进行子类型以使我的类型参与转换时,我就得到了ERROR: invalid subtyping in definition of Point2D。如果作为一个实验,我将我的类型设置为Number的一个子类型,就像在type Point2D{T} <: Number中一样,那么至少文件没有错误地加载,但是当然,当我尝试Point2D(1,2) + [1,1]时,我得到了ERROR: no promotion exists for GridCalc.Point2D{Int64} and Int64

我还试着把我的Point2D变成mutable struct,但它也不会“拿走”<: Vector{T}

以下是代码:

代码语言:javascript
复制
type Point2D{T}  # Fails when I add <: Vector{T}, etc.
    x::T
    y::T
end

# Convert a Point2D to a vector of the same type
convert{T1, T2<:Vector{T1}}(::Type{T2}, p::Point2D{T1}) = [p.x, p.y]

# Choose Vector when given the option
promote_rule{T1<:Real, T2<:Point2D{T1}, T3<:Vector{T1}}(::Type{T2}, ::Type{T3}) = T3

问题:

  1. 这是让Point2D像2向量一样参与数学函数的正确方法吗?
  2. 如何使我的Point2D成为Vector{T}的一个子类型
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-17 04:45:34

这样做的方法是子类型AbstractVector{T}。在朱莉娅中,您只能使用子类型抽象类型;Vector{T}是一个具体类型。您还必须实现一些必需的方法。有关更多细节,请参见接口章节

代码语言:javascript
复制
julia> type Point2D{T} <: AbstractVector{T}
           x::T
           y::T
       end
       Base.getindex(p::Point2D, i::Int) = getfield(p, i)
       Base.size(::Point2D) = (2,)

julia> Point2D(1,2)
2-element Point2D{Int64}:
 1
 2

julia> [1 2; 3 4; 5 6] * Point2D(1,2)
3-element Array{Int64,1}:
  5
 11
 17

您还可以查看(和/或使用) JuliaGeometry组织GeometryTypes.jl的点定义和周围方法。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45135765

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档