Ignoring `NaN` with `findmax()`

Suppose I have the following array:

a=[NaN, 1,2,3]

If I use findmax(a), I obtain (NaN, 1). How can I use findmax() ignoring all NaN values? I tried findmax(filter(!isnan, a)) but it returns (3.0,3) when I want (3.0,4).

Thank you!

1 Like

One bandaid fix is to first set them to -Inf (or Inf if you are doing findmin).

a[ isnan.(a)] .= -Inf

1 Like

Thanks! Worked perfectly!!

I expected

findmax(Iterators.filter(!isnan, a))

to work but it appers to be broken because of

2 Likes

I would do:

julia> findmax(a[.!isnan.(a)])
(3.0, 3)
3 Likes

Ahhhh gooood! Another good option! Thanks! But I want (3.0, 4) and not (3.0,3) as I specified :wink:

Ah ok… Right, it doesn’t work :frowning:

MappedArrays.jl is good for this too:

julia> m = mappedarray(x -> isfinite(x) ? x : -Inf, a);

julia> findmax(m)
(3.0, 4)
3 Likes

Ok! Didn’t know about this package! :slight_smile:

See also Define pairs(A) = enumerate(A) · Issue #34851 · JuliaLang/julia · GitHub

1 Like