Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • column number in which the minimum value for each row is located

    Hi all,

    I would like to obtain a matrix c that stores instead of the minimum value for each row, the column number in which the minimum value for each row is located.
    For instance in the following matrix a

    100 200 500 300
    20 10 50 30
    3 5 2 1

    the command b=rowmin(a) will give that the minimum values for each row are

    100
    10
    1

    How could I obtain a matrix c that gives me the column number in which the minimum value for each row is located?

    1
    2
    4

    Thank you very much in advance for your help

    Best wishes,
    Maria





  • #2
    Welcome to Statalist!

    A question: what you you expect to be done if the minimum is not unique in a given row?

    Comment


    • #3
      See help mata minindex() for a function which finds the indices of the minina and how the function handles ties. The function is only for vectors so you will have to loop over columns.

      Comment


      • #4
        Also look at -help mf_st_matrix- since it looks like you are dealing with Stata matrix instead of Mata matrix, you need use -st_matrix()- to get the Stata matrix into Mata, then use -minindex()- as Chistophe suggested to get the result.

        Comment


        • #5
          Thank you very much for your help!

          minindex is giving exactly the vector that I need (see output attached) but I would like to store the printed results (vector j': column number/numbers in which the minimum value is located) in a matrix where each row will be the result obtained in each iteration. I will really appreciate your help.

          Code:
          for (i=1;i<=rows(a);i++) {
              minindex(a[i,],1,j,w)
              j'
              }
          Attached Files

          Comment


          • #6
            This solution only works if you have no ties
            Code:
            b = J(rows(a),1,.)
            for (i=1;i<=rows(a);i++) {
                b[i,1] = minindex(a[i,],1,j,w)
            
                }
            if you do have ties, one solution is to use a vector of pointers

            Code:
            b = J(rows(a),1,NULL)
            for (i=1;i<=rows(a);i++) {
                b[i,1] = &minindex(a[i,],1,j,w)
            
                }
            you refer to the result of the ith row by using the dereferencing operator

            Code:
            i=1
            *b[1,i]
            or you can just create a matrix with enough columns to contain the maximum number of ties (which you have to determine in advance)

            Comment

            Working...
            X