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]
st: Avoiding use of Mata external variables in large programs
From
[email protected] (Rafal Raciborski, StataCorp)
To
[email protected]
Subject
st: Avoiding use of Mata external variables in large programs
Date
Wed, 08 May 2013 15:49:25 -0500
Michael Lacy <[email protected]> is seeking advice about avoiding the
use of Mata external variables in Mata/Stata adofile programs:
> My general approach in using Mata is what I presume as typical, i.e. to use
> a Stata program as the main program, and call Mata functions within it.
> I find it convenient to use Mata external variables to retain Mata results
> until the next Mata function needs them. Schematically, we might have
> something like:
>
> prog MyStataProg
> <some Stata commands>
> mata: E1 = MyMata1(...)
> <some more Stata stuff>
> mata: MyMata2(...) // gets access to E1 by declaring E1 as external
> end
An improved version Michael mentions uses temporary names for Mata objects:
> tempname E1
> mata: `E1' = ...
Below I sketch an outline Michael can follow to avoid using externals.
This method assumes Michael knows in advance how many temporary names Mata
will use. I comment on the code below.
--------------------------- begin mymain.ado ---------------------------
prog mymain
version 12
tempname m1 m2 // need two temporary names for Mata
capture noi mysub `m1' `m2' `0'
local rc =_rc
mycleanup `m1' `m2'
exit `rc'
end
prog mysub
gettoken a1 0 : 0 // note `a1' and `m1' refer to the same tempname
gettoken a2 0 : 0 // note `a2' and `m2' refer to the same tempname
syntax ...
<some Stata stuff>
mata: `a1' = mymata1(...)
mata: `a2' = mymata1(...)
<some Stata stuff>
mata: mymata2(`a1',`a2'...)
<some Stata stuff>
end
prog mycleanup
syntax [anything]
foreach m of local 0 {
capture mata: mata drop `m'
}
end
exit
--------------------------- end mymain.ado ---------------------------
It is possible that -mysub- will error out or the user will press the break
key before -mysub- finishes. If this happens, the `m1' and `m2' Mata objects
will not automatically be dropped from Mata memory and, considering they can
point to large matrices, we need to clean up. This is why we capture the call
to -mysub- and call -mycleanup- to drop these Mata objects from memory.
-- Rafal
[email protected]
*
* 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/