*Tutorial 4 *Learning Mata by example *converting a string to a real *--------------Start Example 1 ----------------* clear mata //clear matrices from memory mata a=("1","2","3"\"4","5","6"\"7","8","9") a=strtoreal(a) //convert string to real b=strofreal(a) //convert real to string a b mata describe //move outside of the loop end *--------------End Example------------------* *converting a string to a real *--------------Start Example 2 ----------------* clear mata //clear matrices from memory mata a=("1","2","3"\"4","5","6"\"7","8","9") d=strtoreal(a[1,3]) //convert string to real a d mata describe //move outside of the loop. Also, note b still listed from previous exmaple end *--------------End Example------------------* *Stata commands inside Mata *--------------Start Example 3 ----------------* clear mata //clear matrices from memory sysuse auto, clear mata stata("regress mpg weight") a=st_matrix("e(b)") a b=st_numscalar("e(N)") b stata("local x = _b[weight]") stata(`"di "`x'""') x=st_local("x") x end *--------------End Example------------------* *getting a matrix into Stata *row max *--------------Start Example 4 ----------------* clear mata //clear matrices from memory sysuse auto, clear set more off mata a=st_data(.,("price", "weight")) a b=rowmax(a) b st_store(., st_addvar("float","max"),b) end list max in 1/10, sep(0) *--------------End Example------------------* help mf_st_addvar help mf_st_data help mf_st_store *getting a matrix into Stata using moremata *moremata needs to be installed first. To do this *type findit moremata on the stata command line *--------------Start Example 5 ----------------* clear mata //clear matrices from memory sysuse auto, clear set more off tempfile foo mata a=st_data(.,("price", "weight")) a b=rowmax(a) b mm_outsheet("`foo'",strofreal(b), mode="r") end insheet using `foo', clear tab list *--------------End Example------------------* *moremata has lots of good stuff. To see this after installation type help moremata *(to install moremata: type findit moremata and then click on the hyperlink and follow instructions) *getting a scalar into Stata *column sum *--------------Start Example 6 ----------------* clear mata //clear matrices from memory sysuse auto, clear set more off mata a=st_data(.,("price")) a c=J(rows(a),1,.) c[1]=colsum(a) st_store(., st_addvar("float","sum"),c) end list sum *--------------End Example------------------* **end tutorial 4