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

# st: Re: Re: Fwd: Linear indexing of matrices in Mata

 From "Joseph Coveney" To Subject st: Re: Re: Fwd: Linear indexing of matrices in Mata Date Wed, 25 Jul 2012 12:57:40 +0900

Joerg Luedicke wrote:

Say we have 5 matrices M1,...,M5. Further assume that we want to use a
subset of M2, M3, M4, M5 based on a selection in M1 (say, M1 :> 2).
Using your function we would type:

index_which(M2, (M1 :> 2))
index_which(M3, (M1 :> 2))
index_which(M4, (M1 :> 2))
index_which(M5, (M1 :> 2))

and so the expression is repeated four times, and evaluated four
times. In R, we would type the expression only once and use index
numbers thereafter:

index=which(M1>2)
M2[index]
M3[index]
M4[index]
M5[index]

--------------------------------------------------------------------------------

Thank you; I've got it now.

You don't really have to evaluate the selection each time in Stata, either.  For
example, you can store the selection just like you show for R,

Selection = (M1 :> 2)

and then use that.

I've illustrated it below in an example where the first matrix is used for
selection for all the matrices in an array of matrices, which are evaluated in a
loop.  (If the example seems busy or messy, it's because I've declared the
variables beforehand and explicitly typed them.)

Joseph Coveney

. version 11.2

.
. clear *

. set more off

.
. mata:
------------------------------------------------- mata (type end to exit) ------
: mata set matastrict on

:
: transmorphic rowvector index_which(transmorphic matrix Target,
>     real matrix Selector) return(select(vec(Target), vec(Selector))')

:
: void function demo() {
>
>     pointer(transmorphic matrix) vector MatrixSet // or associative array
>     MatrixSet = J(3, 1, NULL)
>     MatrixSet[1] = &(1, 3 \ 2, 4)
>     MatrixSet[2] = &(5, 7 \ 6, 8)
>     MatrixSet[3] = &("A", "C" \ "B", "D")
>
>     real matrix Selection
>     Selection = (*MatrixSet[1] :> 2)
>
>     real scalar index
>     for (index=1; index<=length(MatrixSet); index++) {
>         index_which(*MatrixSet[index], Selection)
>     }
> }

:
: demo()
1   2
+---------+
1 |  3   4  |
+---------+
1   2
+---------+
1 |  7   8  |
+---------+
1   2
+---------+
1 |  C   D  |
+---------+

:
: end
--------------------------------------------------------------------------------

.
. exit

end of do-file

*
*   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/