【问题标题】:How should I convert a singleton Array to a scalar?我应该如何将单例数组转换为标量?
【发布时间】:2015-05-23 10:34:36
【问题描述】:

假设我有一个名为 pArray 变量:

julia> p = [5]
julia> typeof(p)
Array{Int64,1}

我应该如何将其转换为标量? p也可能是二维的:

julia> p = [1]'' 
julia> typeof(p)
Array{Int64,2}

(注意:增加维度的双转置技巧might not work in future versions of Julia

通过适当的操作,我可以制作任何维度的p,但我应该如何将其减少为标量?


一种可行的方法是p=p[1],但如果pp 中有多个元素,则不会引发任何错误;所以,这对我没有好处。 我可以构建自己的函数(通过检查),

function scalar(x)
    assert(length(x) == 1)
    x[1]
end

但它似乎必须重新发明轮子。

不起作用的是squeeze,它只是剥离维度直到p 是一个零维数组。

(与 Julia: convert 1x1 array from inner product to number 相关,但在这种情况下,与操作无关。)

【问题讨论】:

    标签: arrays julia scalar


    【解决方案1】:

    如果您想获取标量但如果数组的形状错误则抛出错误,您可以reshape:

    julia> p1 = [4]; p2 = [5]''; p0 = []; p3 = [6,7];
    
    julia> reshape(p1, 1)[1]
    4
    
    julia> reshape(p2, 1)[1]
    5
    
    julia> reshape(p0, 1)[1]
    ERROR: DimensionMismatch("new dimensions (1,) must be consistent with array size 0")
     in reshape at array.jl:122
     in reshape at abstractarray.jl:183
    
    julia> reshape(p3, 1)[1]
    ERROR: DimensionMismatch("new dimensions (1,) must be consistent with array size 2")
     in reshape at array.jl:122
     in reshape at abstractarray.jl:183
    

    【讨论】:

      【解决方案2】:

      你应该使用only,它是在 Julia v1.4 中引入的

      julia> only([])
      ERROR: ArgumentError: Collection is empty, must contain exactly 1 element
      Stacktrace:
        [1] only(x::Vector{Any})
          @ Base.Iterators ./iterators.jl:1323
        [...]
      
      julia> only([1])
      1
      
      julia> only([1 for i in 1:1, j in 1:1, k in 1:1]) # multidimensional ok
      1
      

      【讨论】:

        猜你喜欢
        • 2016-05-11
        • 1970-01-01
        • 2019-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-15
        相关资源
        最近更新 更多