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]

st: Avoiding use of Mata external variables in large programs

From (Rafal Raciborski, StataCorp)
Subject   st: Avoiding use of Mata external variables in large programs
Date   Wed, 08 May 2013 15:49:25 -0500

Michael Lacy <> 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'

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>

prog mycleanup
	syntax [anything]
	foreach m of local 0 {
		capture mata: mata drop `m'

--------------------------- 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

*   For searches and help try:

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