Search code examples
arraysjuliascalar

How should I convert a singleton Array to a scalar?


Let's say I have an Array variable called p:

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

How should I convert it to scalar? p may also be 2-dimensional:

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

(Note: the double transpose trick to increase dimentionality might not work in future versions of Julia)

Through appropriate manipulation, I can make p of any dimension, but how should I reduce it to a scalar?


One viable approach is p=p[1], but that will not throw any error if p has more than one element in p; so, that's no good to me. I could build my own function (with checking),

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

but it seems like it must be reinventing the wheel.

What does not work is squeeze, which simply peels off dimensions until p is a zero-dimensional array.

(Related to Julia: convert 1x1 array from inner product to number but, in this case, operation-agnostic.)


Solution

  • You should use only, which was introduced in 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