Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: check if a vector is a vector of numbers

I'd like to check if my vector / array is made of numbers.

I've tried:

if isa(x, Array{Number})
  println("yes")
end

But it doesn't seem to work...

like image 347
Dominique Makowski Avatar asked Jan 27 '23 12:01

Dominique Makowski


1 Answers

You have two scenarios here.

Scenario 1. You want to check if type of a vector allows only numbers. Then write:

eltype(x) <: Number

Scenario 2. You want to check if actually all elements of a vector are numbers. Then write:

all(isa.(x, Number))

The second is less efficient because it has to check the whole array. The reason why it might be sometimes needed is that you can have e.g.:

x = Any[1, 2, 3]

which contains only numbers, but type of the vector in general allows it to contain other things than numbers (so it will fail scenario 1 but pass scenario 2).

like image 90
Bogumił Kamiński Avatar answered Feb 08 '23 16:02

Bogumił Kamiński