A twist to this problem is that it is customary
in entropy calculations to define 0 ln 0 as 0.
However, Stata doesn't know that and will
return missing instead. So, it is necessary
to trap 0 within some expression as
scalar x = x + cond(p = 0, 0, p * ln(p))
Nick
n.j.cox@durham.ac.uk
Michael Blasnik
-findit matmap- will lead you to the matmap package which can perform
arbitrary elementwise operations on matrices, but since you
want the sum of
the calculation across all elements, I think you should just
do the looping
yourself. Here's one approach (untested):
scalar x=0
tab var1 var2, matcell(Cell)
matrix P = Cell/r(N)
local rows=rowsof(P)
local cols=colsof(P)
forvalues i=1(1)`rows' {
forvalues j=1(1)`cols' {
scalar p=P[`i',`j']
scalar x=x+p*ln(p)
}
}
scalar x=x+ln(`rows'*`cols')
di x