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

Lyn*_*ite 13 arrays scalar julia

假设我有一个Array名为的变量p:

julia> p = [5]
julia> typeof(p)
Array{Int64,1}
Run Code Online (Sandbox Code Playgroud)

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

julia> p = [1]'' 
julia> typeof(p)
Array{Int64,2}
Run Code Online (Sandbox Code Playgroud)

(注意:增加维度的双转置技巧可能在Julia的未来版本中不起作用)

通过适当的操作,我可以制作p任何尺寸,但我应该如何将其缩小为标量?


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

function scalar(x)
    assert(length(x) == 1)
    x[1]
end
Run Code Online (Sandbox Code Playgroud)

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

什么是行不通的squeeze,它只是剥离尺寸直到p是一个零维数组.

(与Julia相关:将1x1数组从内积转换为数字,但在这种情况下,与操作无关.)

DSM*_*DSM 8

如果你想获得标量但是如果数组形状错误则抛出错误,你可以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
Run Code Online (Sandbox Code Playgroud)


Bal*_*Ben 5

您应该使用onlyJulia 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
Run Code Online (Sandbox Code Playgroud)