Picking indices from matrix using arrays

Hi,

I am a little stuck trying to vectorise something.

I am modelling the probability of players winning points in a tennis match. Originally, I had the following setup:

int s_id[num_matches]; // server ids vector[num_players] s; // serving ability

I could then pick out the ones specific to a match using:

Now, I want to make the model time-dependent. This is the new setup:

int s_id[num_matches]; // server ids int period[num_matches]; // the current period matrix[num_periods, num_players] s; // serving ability

I would like to vectorise the new statement. I tried:

but it returns a matrix. I really only want to pick out the vector corresponding to the indices (i, j), where i is given by one integer array and j by another. Is there a way to do this in vectorised form?

Thanks a lot,
Martin

2 Likes

Afraid there’s no good way to bind two variables in a matrix like this. We should make a method because it’s been coming up a lot. When you have to integer arrays a and b and a matric c, then c[a, b] is a matrix defined so that c[a, b][i, j] == c[a[i], b[j]]. So you need to use a loop.

{
  int s_period_id[num_matches];
  for (i in 1:num_matches) s_period_id[i] = s[period[i], s_id[i]];
  spw ~ binomial_logit(spt, s_period_id);
}

The parens make sure you are defining s_period_id as a local variable.

What we want is a way to do matrix multi-indexing, so that something like bind_indexes(c, a, b) is defined so that it returns a vector with elements bind_indexes(c, a, b)[i] == c[a[i], b[i]].

2 Likes