How to subset a three-dimensional matrix?

I have a specific question regarding subsetting a matrix in a loop. In Matlab, I can define a matrix like X(N,K,T), where N is the number of observations, K is the number of features, T is the number of periods.

Now I need a for loop over time T, for example when t = 1, I want to use X(N,K,1), when t = T, I want X(N,K,T).

So can I define this three-dimensional matrix in Rstan? I read over the reference manual and did not find related info. Or are there any other alternative ways to achieve this? Thanks!!

Yes, you can do this in multiple ways. In Stan, there is a matrix type which is M x N and allows for matrix algebra, and then there are arrays which multi-dimensional collections of any type.

Here are different ways you can do this…

  1. There’s a T-array of N x K matrices

    matrix[N, K] X[T];

    this means that X[t] is a matrix and X[t, n] = X[t][n] is a row vector.

  2. There’s a N x K x T array of reals.

    real X[N, K, T];

    X[n] gets you a K x T real array, X[n, k] gets you a T-length real array, X[n, k, t] gets you a single real.

If you’re asking whether or not arrays of real is better than matrix, I’m pretty sure that’s covered in the manual.

Thanks! Then X[N,K,t] should be what I want! I will read the manual more carefully. By the way, is it legal to use the subsetted array to do usual matrix multiplications? Thanks


In the Stan language, an array is not the same as a matrix.

If that’s what you want to do, I’d declare it as… matrix[N, K] X[T]; if you want each matrix to be N x K.