How to find the location of a value in a vector

There’s some discussion of this in this post:

I made a few edits to the functions @Bob_Carpenter suggested in that post, and I think the following should work:

int num_matches(vector x, real y) {
  int n = 0;
  for (i in 1:rows(x))
    if (x[i] == y)
      n += 1;
  return n;
}
  
int[] which_equal(vector x, real y) {
  int match_positions[num_matches(x, y)];
  int pos = 1;
  for (i in 1:size(x)) {
    if (x[i] == y) {
      match_positions[pos] = i;
      pos += 1;
    }
  }
  return match_positions;
}

To use it you would do something like this:

int ids[num_matches(x, y)] = which_equal(x, y);

and ids would then contain the indexes of the elements in x that equal y. If you know in advance that there can only be one value of x that equals y then you can simplify all this because num_matches wouldn’t be necessary.

1 Like