Announcement

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

  • If statement in inverse distance weight matrix

    Hi,

    Now I'm making an inverse distance weight matrix between observations using the Mata function.

    In Stata, the code is
    -------------------------------------------------
    clear mata

    mata:
    id = st_data(., "DHSCLUST") // this is a location at cluster level.
    location = st_data(., ("LONGNUM", "LATNUM")) // this is GIS - longitude and latitude
    N = st_nobs()
    M = J(N, N, 0)
    for (i=1; i<=N; i++) {
    for (j=1; j<i; j++) {
    delta = location[i,.] - location[j,.]
    M[i,j] = M[j,i] = 1/sqrt(delta*delta')
    }
    }
    M
    st_matrix("weightmatrix_women", M)
    end
    -----------------------------------------------------
    Main problem is a number of observations share the same location. As a result, LONGNUM and LATNUM of many obs are identical. This results in empty cell (as 1/sqrt(delta*delta') can't be calculated) in the generated matrix.



    To solve this problem, I added if statement.

    The code is

    clear mata
    mata:

    id = st_data(., "DHSCLUST") // this is a location at cluster level.
    location = st_data(., ("LONGNUM", "LATNUM")) // this is GIS - longitude and latitude
    N = st_nobs()
    M = J(N, N, 0)
    for (i=1; i<=N; i++) {
    for (j=1; j<i; j++) {
    delta = location[i,.] - location[j,.]
    if (delta != 0) {
    M[i,j] = M[j,i] = 1/sqrt(delta*delta') ;
    }
    else {
    M[i,j]=M[j,i] == 0 ;;
    }
    }
    }
    M
    st_matrix("weightmatrix_women", M)

    end

    _______________________________________

    However, the result is same. Anyone knows how to sort this out please?

    Kind regards,

    Kim

  • #2
    Your delta is a matrix, whereas "0" is a scalar quantity, so (delta != 0) will always be true. If you want to check whether a matrix contains all zeros, you need to compare it to a matrix of the same dimension.

    Try this:
    Code:
    mata
    delta = (0,0)
    delta
    "zero scalar"
    delta !=  0
    //
    "zero matrix"
    delta !=  (0,0)
    end
    Also, comparing floating point values for equality is always potentially a source of error. While it might not bite you here, it's safer to compare a floating point absolute value to some small value, e.g. abs(x) <= 1e-10.

    In an unrelated matter, I'd also note that your use of ";" is strange (if likely harmless): The ";" in Mata is used to separate multiple statements on a line, but your code as displayed here only has one statement per line.

    Comment


    • #3
      Dear Mike,

      Thank you very much for your reply! It is really helpful. Now it is clear!

      Kind regards,

      Kim

      Comment

      Working...
      X