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
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
Comment