I want to find the location of a value in a vector. E.g.,
In R
x <- c(1, 5, 9, 10)
y <- 5
which(x==y) would give me the answer 2. is there a corresponding function in Stan?
2 Likes
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
Thanks! I ended up doing something similar, but you reminded me that I can define such as function. I guess Stan doesn’t have any existing function for this.
1 Like
Glad you figured something out.
Not yet unfortunately.