Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
re: st: Errors "out of range" for a simple Mata function
From
Christopher Baum <[email protected]>
To
"[email protected]" <[email protected]>
Subject
re: st: Errors "out of range" for a simple Mata function
Date
Tue, 20 Nov 2012 02:01:32 +0000
<>
Ly Tran:
Nick Cox is correct in pointing out that you need to pass `generate' to your Mata function. But it is not necessary to use st_store() as he suggests. Your Mata code works with one small change:
capture program drop testsum
program testsum, rclass
syntax varlist(numeric) [if] [in], GENerate(string) [FLOAT]
qui generate `float' `generate' = .
mata: tsum( "`varlist'", "`generate'")
end
mata
void function tsum (string scalar varlist, string scalar newvar)
{
real matrix X, Z
st_view(X = .,., tokens(varlist))
st_view(Z =., ., newvar)
Z[.,.] = rowsum(X)
}
end
When an entire view matrix is the LHS of a statement, you must use the syntax shown, rather than the name of the view matrix, for the statement to update the view matrix (and the Stata variable(s)) and not create a new Mata object. In the help for st_view(), read the section "Cautions when using views 2: Assignment" to see this point illustrated. It is also mentioned in the Mata chapter of ITSP below.
. sysuse auto,clear
(1978 Automobile Data)
. testsum price mpg turn, gen(junk)
. egen junk2=rowtotal(price mpg turn)
. su junk*
Variable | Obs Mean Std. Dev. Min Max
-------------+--------------------------------------------------------
junk | 74 6226.203 2948.149 3354 15972
junk2 | 74 6226.203 2948.149 3354 15972
One other thing: if you allow [if] and [in] in your ado-file, you should -marksample touse- and pass `touse' to Mata so that it can limit the observations being used in the Mata routine. Again, example code in ITSP.
Kit
Kit Baum | Boston College Economics & DIW Berlin | http://ideas.repec.org/e/pba1.html
An Introduction to Stata Programming | http://www.stata-press.com/books/isp.html
An Introduction to Modern Econometrics Using Stata | http://www.stata-press.com/books/imeus.html
*
* For searches and help try:
* http://www.stata.com/help.cgi?search
* http://www.stata.com/support/faqs/resources/statalist-faq/
* http://www.ats.ucla.edu/stat/stata/