Announcement

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

  • finding the smallest non-zero value in a matrix

    Dear Statalist,

    I have a matrix A with zeros on the diagonal and non-zero, positive numbers off the diagonal. Can anyone suggest a way to identify the smallest non-zero (i.e., off-diagonal) number in A?

    I can find the largest number with:

    mata: st_matrix("max", max(st_matrix("A")))

    To find the smallest value, I thought I would use the mata function _diag() to replace the elements on the diagonal with a number so large it would not appear elsewhere:

    mata: A2=_diag(st_matrix("A"),9)
    mata: A2
    mata: st_matrix("min", min(A2))

    Unfortunately, my mata skills are minimal, and the code above does not even appear to make the matrix A2. Perhaps there is an easy way to do this without even using mata?

    Thanks,

    Jeremy


  • #2
    Here is one way. There is probably a better way. I would not overwrite the original: you might need it.

    Code:
    : x = (0,1,2\3,0,4\5,6,0)
    
    : _diag(x2=x, .)
    
    : x2
           1   2   3
        +-------------+
      1 |  .   1   2  |
      2 |  3   .   4  |
      3 |  5   6   .  |
        +-------------+
    
    : min(x2)
      1
    
    : x
           1   2   3
        +-------------+
      1 |  0   1   2  |
      2 |  3   0   4  |
      3 |  5   6   0  |
        +-------------+
    P.S. consider

    Code:
     
     1/max(1 :/ x)
    if the non-zeros are all positive. Precision problems are possible. Similar tricks based on

    Code:
     
    min(exp(log(x)))
    and similar problems.
    Last edited by Nick Cox; 04 Feb 2015, 18:12.

    Comment


    • #3
      Thank you, Nick. Your answer was clear and elegant as usual.

      Jeremy

      Comment

      Working...
      X