Finding row of approximate values in array

I have a row vector ‘a’ with a given coordinate (x, y, z) and I need to obtain the row in a coordinates array (B) with the coordinates are closest to the row vector ‘a’. I’ve been using a function that I found on the web:

matchrow(a,B) = findfirst(i->all(j->a[j] == B[i,j],1:size(B,2)),1:size(B,1))

but it doesn’t work for approximates (for a given tolerance). Is there a way of doing that?

Try using isapprox instead of ==.

1 Like

I already tried isapprox but don’t know where to use it in the matchrow function.

You’ve written a[j] == B[i,j] for the comparison, but == is just a function that returns true/false, and you just need to put isapprox in its place. There’s a built-in infix isapprox operator which uses default tolerances, and if rtol=sqrt(eps), atol=0 suffices for your purposes, you could write a[j] ≈ B[i,j]. Otherwise, replace the comparison with isapprox(a[j], B[i,j], atol=???, rtol=???).

1 Like

matchrow(a,B) = findfirst(i->all(j -> isapprox(a[j], B[i, j], atol = 1E-5), 1:size(B,2)), 1:size(B,1))

1 Like

Thanks a lot!!! That worked!!! I was stuck there trying to figure it out.

Thanks!! I migrating to Julia and still trying to figure it out.

Thus, may I suggest to use something (for me) much more clear and efficient like an explicit loop e.g.

function matchrow(a, B::AbstractMatrix; kw...)
    r = 1
    while r ≤ size(B, 1)
        c = 1
        while c ≤ size(B, 2) && isapprox(a, B[r, c], kw...)
            c += 1
        end
        c > size(B, 2) && return r
        r += 1
    end
    return nothing
end