Bookmark and Share

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


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

st: RE: MATA function that gives the TRUE indices of a logical object


From   Nick Cox <[email protected]>
To   "'[email protected]'" <[email protected]>
Subject   st: RE: MATA function that gives the TRUE indices of a logical object
Date   Mon, 7 Feb 2011 16:12:55 +0000

I am not aware of anything built-in to Mata [sic; not MATA]. 

Here is something rough:

mata: 

real matrix which(real matrix x, scalar s) { 
	
	real scalar i, j 
	real matrix out 
	out = J(0,2,.) 
	
	for(i = 1; i <= rows(x); i++) { 
		for (j = 1; j <= cols(x); j++) { 
			if (x[i,j] == s) out = out \ (i,j)
		}
	}
	
	return(out)
} 

end

This just does what your example does, modulo some convention about row first or column first. Testing for equality with some non-integer value is a whole heap more problematic. 

Nick 
[email protected] 

[email protected]

I have the following question on a function which a want to use in MATA. I think
it's best illustrated with an example. In the R-language you have the which()
function, which works as follows. Suppose you have a matrix Z:

0 0 0
1 0 0
0 1 0
9 9 1
9 9 9
9 9 9

then using which(Z==9, arr.ind = T)
finds entries with Z=9 and returns an array with coordinates as follows:

row col
4 1
5 1
6 1
4 2
5 2
6 2
5 3
6 3

Does a similar function exist in MATA?


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


© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index