我应该如何将单例数组转换为标量?

How should I convert a singleton Array to a scalar?

假设我有一个名为 p:

Array 变量
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 是一个零维数组。

(与 相关,但在本例中,与操作无关。)

如果你想获取标量,但如果数组形状不正确则抛出错误,你可以 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

你应该使用 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