Bookmark and Share

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   Nick Cox <[email protected]>
To   [email protected]
Subject   Re: st: Errors "out of range" for a simple Mata function
Date   Mon, 19 Nov 2012 17:45:41 +0000

You don't define the local macro -newvar- before you use it. Thus your
Mata call reduces to

mata : tsum("`varlist'", "")

I guess you meant to write

mata: tsum( "`varlist'", "`generate''")

Learning Mata is fine. In the case of row sums, -egen-'s -rowtotal()-
function is already available. At least that allows a check of your
program.

st_view(Z =., ., newvar)
Z = rowsum(X)

is wrong for what you want. Use -st_store()- instead.

Incidentally, your program allows -if- and -in- but ignores them.
Presumably that is on the agenda.

Also -float- is the default default [repetition intended] numeric type anyway

Nick

On Mon, Nov 19, 2012 at 5:05 PM, Ly Tran <[email protected]> wrote:

> I am trying to write a simple Mata function, mostly to learn about the
> functions themselves, but run into a problem that I fail to solve.
> The function creates a new variable that is the row sum of several
> existing variables.
> Here it is:
> capture program drop testsum
> program testsum, rclass
> syntax varlist(numeric) [if] [in], GENerate(string) [FLOAT]
> qui generate `float' `generate' = .
> mata: tsum( "`varlist'", "`newvar'")
> 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
> testsum AUD JPY, gen(test)
> The error is tsum(): 3301 subscript invalid
> <istmt>: - function returned error
>
> I figured that for some reason, after the line st_view (Z = .,.,
> newvar), somehow the cols(Z) returns 0, and I think that's where the
> error comes in.
> When I avoid using mata function but embed this piece of mata code in
> the program (minus the line that declares matrices), it runs just fine
> and returns what it is supposed to.
> Can anybody please help me with this? Any idea how this can be fixed
> would be much appreciated.
*
*   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/


© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index