Finding the Index Inside a Vector Satisfying a Condition

Finding the index inside a vector satisfying a condition

Use which and take the first element of the result:

which(b > 0.65)[1]
#[1] 3

Get all positions of elements in STL vector that are greater than a value

Loop std::find_if, starting from where you stopped last time.

Sample (see it work):

std::vector<size_t> results;

auto it = std::find_if(std::begin(v), std::end(v), [](int i){return i > 5;});
while (it != std::end(v)) {
results.emplace_back(std::distance(std::begin(v), it));
it = std::find_if(std::next(it), std::end(v), [](int i){return i > 5;});
}

First we set up the iterator with the first result. If it's not found, the while loop never executes. Otherwise, the index position is stored (std::distance is basically a more generic it - std::begin(v)), and the search continues onward.

Find position of first value greater than X in a vector


# Randomly generate a suitable vector
set.seed(0)
v <- sample(50:150, size = 50, replace = TRUE)

min(which(v > 100))

Get first n indexes fulfilling a condition in r

The rank function is what you are looking for:

which(rank(x2)<=3 & x2<3)
#[1] 2 3 7

Find the minimum and maximum indices of a list given a condition

Filter the zipped list with its indixes and take the min and the max:

>>> list_A = [0,0,0,1.0,2.0,3.0,2.0,1.0,0,0,0]
>>> filtered_lst = [(x,y) for x,y in enumerate(list_A) if y > 0]
>>> max(filtered_lst)
(7, 1.0)
>>> min(filtered_lst)
(3, 1.0)

If you just need the index, unpack the returned value:

>>> maX,_ =  max(filtered_lst)
>>> maX
7


Related Topics



Leave a reply



Submit