# st: RE: RE: Re: manipulating matrix elements

 From Steve Vaisey To statalist@hsphsun2.harvard.edu Subject st: RE: RE: Re: manipulating matrix elements Date Wed, 29 Mar 2006 12:43:31 -0500

Thanks everyone, for providing helpful answers to my question. All your solutions worked, but I'm going to go with Nick's mata program because it allows me to use "if," bootstrapping, etc. (Maybe the others' would too, but I wouldn't know how to make them into programs...)

One further question though. In the program you wrote, Nick, the entropy calculation isn't standardized. How could it be modified to add ln(number of cells) to the final value?

Thanks,

Steve

Date: Tue, 28 Mar 2006 23:24:29 +0100
From: "Nick Cox" <n.j.cox@durham.ac.uk>
Subject: st: RE: RE: Re: manipulating matrix elements

Another way to do it is with Mata. That way, zeros get ignored in the way you would like.
- ----------------------------------- myentropy.ado program myentropy, rclass
version 9 syntax varlist(min=2 max=2 numeric) [if] [in] [fweight aweight]
marksample touse qui count if `touse' if r(N) == 0 error 2000
tempname matname
tab `varlist' [`weight' `exp'] if `touse', matcell(`matname')
mat `matname' = `matname' / r(N)
mata: subroutine("`matname'")
di as txt "entropy" as res %10.4f r(entropy) return scalar entropy = r(entropy) end

mata:
void subroutine(string scalar matname)
{
real matrix X
real scalar H X = st_matrix(matname)
H = sum(X :* ln(X)) st_numscalar("r(entropy)", H)
}
end
- ---------------------------------
e.g.
sysuse auto, clear
myentropy for rep78

Nick n.j.cox@durham.ac.uk

```--
====================================================
Stephen Vaisey
National Science Foundation Graduate Research Fellow
Caroline H. and Thomas S. Royster, Jr. Fellow
Department of Sociology
University of North Carolina at Chapel Hill
200 Hamilton Hall (CB #3210)
Chapel Hill, NC 27599

*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/
```