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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With