Index of element with lowest non-negative value

I need to be able to find the index of the element within a 1d array that has the lowest non-negative value (so excluding all negative numbers). I know one way I finding it, namely using:

minVal = Inf;
index = 0;
for i in 1:length(arr)
    if arr[i] >= 0 && arr[i] < minVal
        minVal = arr[i];
        index = i;

I wouldn’t suppose there’s some simpler, higher-performance way of doing this?

You can always add @inbounds to the for loop for an easy gain

1 Like

Unfortunately there is no method of argmin / argmax with a filter function as first element.
Maybe it would be good to add it?
Otherwise, I also could not see a “nicer” version as a loop. Performance-wise a loop is perfectly fine.

1 Like

Allowing custom comparison operators in argmin (findmin) would allow a simple solution, since it could just use a comparison operator that always prefers non-negative values. This is WIP that seems stalled at the moment, cf


You can chain comparison operators like this:

if 0 <= arr[i] < minVal