Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.

# st: Linear indexing of matrices in Mata

 From Joerg Luedicke To statalist@hsphsun2.harvard.edu Subject st: Linear indexing of matrices in Mata Date Sat, 21 Jul 2012 14:22:48 -0400

```Hi everybody,

I am using Stata 11.2.

If we want to select an element of a matrix, Mata requires two
indexing subscripts, for example:

*--Mata code--
m=(1,3\2,4)
m[1,2]
*-----------------

extracts the element in row 1, 2nd column of matrix m. However, as far
as I read the manual and searched online, Mata does not seem to have a
concept of linear indexing, i.e. referring to an element of a matrix
by a single position number. Linear indexing usually counts down the
1st column, then the 2nd, and so on, just as if you would stack all
colums resulting in a vector.  In R, for example (and similar in
Matlab), if we type:

*--R code--
m=matrix(c(1,2,3,4), nrow = 2)
m[3]
*-------------

we can extract the same element as we did before in Mata, but in Mata
we had to use two subscripts instead of just one. So my first question
would be: is my impression correct that there is no linear indexing
for matrices in Mata?

If yes, the second question would be how to best circumvent this?
Consider the following problem: suppose we have two matrices, m1 and
m2 with the same dimensions. Now we want to check a certain condition
in m1 and if true, record the position index. Then we want to select
elements in m2 that are corresponding to the recorded positions. For
example, if we type in R

*--R code--
m1=matrix(c(1,2,3,4), nrow = 2)
m2=matrix(c(5,6,7,8), nrow = 2)
index=which(m1>2)
m2[index]
*-------------

then m1 looks like

[,1] [,2]
[1,]    1    3
[2,]    2    4

and m2 looks like

[,1] [,2]
[1,]    5    7
[2,]    6    8

Then, with the which() function we create a vector of integers that
denote the position in the matrix m1 - for which the element is
greater than 2 - by a single number. In this example, these are matrix
positions 3 and 4 (coinciding with the values in that matrix).
Finally, we can use the indices to index elements, as -m2[index]-
yields

[1] 7 8

i.e., the elements of m2 with the linear indices 3 and 4.

So, the basic problem is how to refer to elements of a matrix, based
on a selection of elements in another matrix. The above example
demonstrates how this could be done in R. Any ideas about solutions in
Mata?

Joerg
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/
```