【问题标题】:Julia: converting any vector of type to vector of realJulia:将任何类型的向量转换为实数的向量
【发布时间】:2016-01-03 21:01:58
【问题描述】:

我定义类型

type mytype
    e1:: Real
    e2:: Real
end

我想要一个 mytype 的向量:

Vmtype = Array{mytype}(10)

当我向朱莉娅要 10 个 e1 时。我收到一个错误 vmtype[1:2].e1 错误:类型数组没有字段 e1

如何访问 Vector Vmtype[1:10]

【问题讨论】:

    标签: vector types type-conversion julia any


    【解决方案1】:

    首先,您必须填写Vmtype 的值。您正在做的是创建一个mytype 类型的“空”数组。

    Vmtype = Array{mytype}(10)
    e1s = collect(1:10)
    e2s = collect(91:100)
    
    for i in 1:10
        Vmtype[i] = mytype(e1s[i], e2s[i])
    end
    

    然后您可以访问这些字段

    Vmtype[1].e1
    

    请注意,一件事是mytype 类型的对象,另一件事是具有mytype 类型元素的数组。见http://docs.julialang.org/en/latest/manual/types/#man-parametric-types

    编辑:

    要使用Vmtype 的 e1 创建另一个数组,您可以使用

    Ae1 = map(x -> x.e1, Vmtype)
    

    那么你可以在plot((1:10), Ae1)中使用Ae1

    【讨论】:

    • 我想知道是否可以以某种方式重载 . 运算符以使其与 Arrays 一起使用。
    • 感谢修正amrods。但是,当我键入 Vmtype[1:2].e1 时,我仍然收到一条错误消息。有什么方法可以访问整个 Vector Vmtype[1:10].e1。我想要做的是运行 plot((1:10),Vmtype[1:10].e1)?
    • 问题是Vmtype没有任何字段;它的 元素e1e2 字段。你可以做的是用Vmtype的元素的e1值填充另一个数组,检查编辑。
    猜你喜欢
    • 2021-04-29
    • 2016-09-25
    • 2021-01-01
    • 2018-03-31
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多