How do I check if a variable is an array of numbers

How do I check if a variable x is a subtype of an array of numbers

x = [1.1, 1.2, 1.3]

julia> typeof(x) == Array{Float64, 1} 
true

julia> typeof(x) == Array{Number, 1}
false

julia> typeof(x) <: Array{Number, 1}
false

julia> isa(x,Array{Number, 1})
false
julia> x = rand(3)
3-element Vector{Float64}:
 0.17437593361404558
 0.7714656320412703
 0.340420132628811

julia> x isa Array{<:Number,1}
true


see: Vector{Int} <: Vector{Real} is false??? · JuliaNotes.jl

5 Likes

Thank you.

I found that this works as well

if typeof(kernel) <: Array{T, 1} where T<:Number
2 Likes

If you’re coming from matlab, you should probably know that you don’t want to be doing these checks in functions. Instead, use dispatch and broadcasting to make things just work with arrays.

6 Likes

I need to determine if a variable is a Number or an array of Number. It must be able to reject a string or reject an array of strings

Would this work:

test(x) =  x isa Union{<:Number, Array{<:Number,1}}

The idiomatic way of doing this is writing two functions. In its simplest form, that looks like this:

function myfunc(a::Int)
   # code for handling a single Int
end

function myfunc(a::Vector{Int})
    # code handling a vector containing only Ints
end

Now, when you call myfunc(myvar), julia will choose the correct method based on the type of myvar and since only two methods (one taking a single Int and the other taking a Vector{Int}) exists, it won’t accept anything other than those two - it’ll throw an error when you pass it e.g. a String.


It should be noted however that mixing scalars and vectors like this in your code is probably not a good idea - may I ask what you’re trying to code up?

5 Likes

I think it’s a rare case where you as the programmer do not know if you have a scalar or an array, I don’t think that ever happens to me, at least. Can you describe how this comes about?

I would claim that the idiomatic solution is not to write a method for scalar and one for Array, but to only write one for scalar and then call that with a broadcasting dot when you want to use it on an array.

3 Likes