Slice an array of vectors across the first dimension (as row() for a matrix)

If all you’re doing is extracting, using a loop is fine. So a simple Stan function to do this would be:

vector extract_each(vector[] x, int n) {
  int M = size(x);
  vector[M] y;
  for (m in 1:M) y[m] = x[m, n];
  return y;
}

That’s as efficiently as it can be done. A built-in wouldn’t be any faster. The inefficiency here is the memory non-locality (each array is independently allocated, so they’re not contiguous), not the loop. The problem is usually that you want to access both rows and columns efficiently, and that’s not really possible without paying the transpose cost.

1 Like