Hello everyone,

I want to use the function ‘diag_matrix’ to create a diagonal matrix by indexing one row from a matrix, for example, I have a matrix

```
matrix[n,p] X;
```

and I want to create n diagonal matrix (with a dimension of p*p) that uses each row of the matrix X as diagonal entries for computing such as for i in (1:n)

```
diag_matrix(X [i,]) ;
```

but it seems the stan did not allow the above syntax. Anyway to solve this? Thanks!

You can use the `row(matrix, int) => row_vector`

which extracts a row from a matrix.

Thanks! so for my case, can I use ‘diag_matrix (row(X, i))’ to extract for all the ith (for i in 1:n) row to make diagonal matrices?

There’s no difference between `row(X, i)`

and `X[i,]`

, I think. Looking at the error message `diag_matrix`

wants a column vector and not a row vector. This seems like an arbitrary limitation; most functions in Stan can handle both. Anyway, the transpose operator `'`

turns a row into a column and vice versa.

```
matrix[p,p] y = diag_matrix(X[i,]');
```

2 Likes