Announcement

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

  • locating the coordinates (row,column) for a specific (string)

    Dear Statalist

    I would like to search a string "1" (stored as string) in the matrix transcribed to mata from stata. Moreover, I would like to search it row-wise and increment the column no. in the loop. The reason is that I would like to get the first row where "1" occurs (in any column).

    The following is my code. Can I request your help in understanding what is the mistake here and how to get the desired output?

    Code:
    mata
    x=st_sdata(.,.)
    for(i=1;i<=rows(x);i++){
    for(j=1;j<=cols(x);j++){
    if(x[i,j]=="1") break
    printf("i=%g\n",i)
    printf("j=%g\n",j)
    }
    }
    i
    j
    end

    Thanks
    Abhimanyu

  • #2
    Hi

    I would use -regexm- and matrix notation.

    First example data:
    Code:
    : rseed(123)
    : x = strofreal(runiformint(10,5,0,20))
    : x
             1    2    3    4    5
         +--------------------------+
       1 |  10   17    6    6    9  |
       2 |  15    8   18    1   17  |
       3 |  20   19   10    3    5  |
       4 |   1   18    9    0   16  |
       5 |  19   14    0    1   12  |
       6 |   7    0   17    5    8  |
       7 |   4   20    3   13   12  |
       8 |   0   18   20   13   16  |
       9 |  17    3   12   10    4  |
      10 |  11   17   15   17    7  |
         +--------------------------+
    Then the positions of ones can be found by -regexm-
    Code:
    : one_positions = regexm(x, "^1$")
    : one_positions
            1   2   3   4   5
         +---------------------+
       1 |  0   0   0   0   0  |
       2 |  0   0   0   1   0  |
       3 |  0   0   0   0   0  |
       4 |  1   0   0   0   0  |
       5 |  0   0   0   1   0  |
       6 |  0   0   0   0   0  |
       7 |  0   0   0   0   0  |
       8 |  0   0   0   0   0  |
       9 |  0   0   0   0   0  |
      10 |  0   0   0   0   0  |
         +---------------------+
    To get first row I utilize that undefined (dot) is plus infinity
    Code:
    : i = colmin((1::rows(x)) :/ (rowsum(one_positions) :> 0))
    : i
      2
    And to get column position
    Code:
    : j = rowmin((1..cols(x)) :/ (one_positions[i,.] :> 0))
    : j
      4
    In your code you need to break twice, eg like (note how I run through the j's):

    Code:
    : for(i=1;i<=rows(x);i++){
    >         for(j=1;j<cols(x);j++){
    >                 if(x[i,j]=="1") break
    >         }
    >         if(x[i,j]=="1") break
    > }
    : i
      2
    : j
      4
    Kind regards

    nhb

    Comment


    • #3
      Thanks very much indeed, Neils, both for the alternative method and improving the earlier code.
      Cheers
      Abhimanyu

      Comment

      Working...
      X