# Re: st: row number corresponding to a column maximum

 From Gabi Huiber To statalist@hsphsun2.harvard.edu Subject Re: st: row number corresponding to a column maximum Date Tue, 28 Jul 2009 17:40:04 -0400

```Thank you, Maarten. I already cobbled together something similar. It
can be saved as a .mo file, maybe it helps somebody:

// Mata function for getting value in col i
// on row that corresponds to max in col j
// (that is, the i neighbor of the max in j)
capture mata mata drop maxneighbor()
mata
real scalar maxneighbor(real matrix A, real scalar i, real scalar j)
{
real scalar k, r, max
r=rows(A)
max=colmax(A)[1,j]
k=1
while(A[k,j]<max) {
k=k+1
}
return(A[k,i])
}
end

Thanks again,

Gabi

On Tue, Jul 28, 2009 at 4:59 PM, Maarten buis<maartenbuis@yahoo.co.uk> wrote:
>
> --- Gabi Huiber wrote:
>> How do you make Stata return the row number that corresponds to the
>> maximum value in a given column, in Mata or Stata?
>
>
> *---------------- begin example -------------
> mata
> x = 1 \ 2 \ 3 \ 2 \ 3
>
> val = x[1,1]
> rownum = 1
> for(i = 2; i <= rows(x); i++){
>        if(x[i,1]==val){
>                rownum = rownum, i
>        }
>        if(x[i,1]>val) {
>                val = x[i,1]
>                rownum = i
>        }
> }
> val
> rownum
> end
> *------------------ end example ------------------
>
> Hope this helps,
> Maarten
>
> -----------------------------------------
> Maarten L. Buis
> Institut fuer Soziologie
> Universitaet Tuebingen
> Wilhelmstrasse 36
> 72074 Tuebingen
> Germany
>
> http://home.fsw.vu.nl/m.buis/
> -----------------------------------------
>
>
>
>
> *
> *   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/
>

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