Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.)

like image 735
Lyndon White Avatar asked Mar 20 '15 04:03

Lyndon White


People also ask

Can only convert an array of size 1 to a python scalar?

Only Size 1 Arrays Can Be Converted To Python Scalars Error is a typical error that appears as a TypeError form in the terminal. This error's main cause is passing an array to a parameter that accepts a scalar value. In various numpy methods, acceptable parameters are only a scalar value.

What is scalar array in Python?

Array scalars have the same attributes and methods as ndarrays . [1] This allows one to treat items of an array partly on the same footing as arrays, smoothing out rough edges that result when mixing scalar and array operations. Array scalars live in a hierarchy (see the Figure below) of data types.

Is a number NumPy?

The isnumeric() function of the NumPy library returns True if there are only numeric characters in the string, otherwise, this function will return False. This function calls unicode. isnumeric in an element-wise manner.


1 Answers

If you want to get the scalar but throw an error if the array is the wrong shape, you could 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
like image 67
DSM Avatar answered Nov 12 '22 13:11

DSM