Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a record exists in a Julia array

Tags:

julia

Say we have a matrix:

A = [1.0 2.0 3.0; 4.0 5.0 6.0] #2×3 Matrix{Float64}

and a record:

b = [1.0 2.0 3.0] #1×3 Matrix{Float64}

what is the most efficient way to check if record b exists in matrix A in Julia?

Doing b in A returns false.

And writing a nested for-loop when we may have a large matrix (many dimensions and many rows) to check seems inefficient.

like image 997
learningMachine Avatar asked Oct 27 '25 12:10

learningMachine


2 Answers

For a 2D matrix like your example, the check is simple.

vec(b) in eachrow(A)
true

For large nD arrays, one can use

vec(b) in eachslice(A, dims=1)
true
like image 187
AboAmmar Avatar answered Oct 29 '25 05:10

AboAmmar


If the rows in the matrix are unsorted I would just do:

findfirst(==(vec(b)), eachrow(A))

If the rows are sorted (which is recommended when you do the search many times) I would consider using searchsorted over a vector of views of array rows.

like image 30
Przemyslaw Szufel Avatar answered Oct 29 '25 06:10

Przemyslaw Szufel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!