Bookmark and Share

Notice: On March 31, it was announced that Statalist is moving from an email list to a forum. The old list will shut down on April 23, and its replacement, is already up and running.

[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 <>
To   "" <>
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'")

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)

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 Baum   |   Boston College Economics & DIW Berlin   |
                             An Introduction to Stata Programming  |
  An Introduction to Modern Econometrics Using Stata  |

*   For searches and help try:

© Copyright 1996–2016 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   Site index