Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

st: Avoiding use of Mata external variables in large programs

From   "Lacy,Michael" <>
To   "''" <>
Subject   st: Avoiding use of Mata external variables in large programs
Date   Tue, 7 May 2013 17:41:55 +0000

I'm seeking advice about avoiding the use of Mata external variables in 
Mata/Stata adofile programs.  This use arises in passing intermediate
results among different Mata functions, as I illustrate below, but there
are occasions where this might arise. My concerns have to do with 
keeping Mata variables and their names as limited in scope as possible,
to avoid me or someone else accidentally clobbering them.

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(...)  // which uses E1 and get access to it by declaring E1 as external 

I think of having E1 visible at the "main" level Mata as undesirable.  Further, My E1 could 
step on a variable name used in Mata by me or someone else.

My thought for avoiding this are:

1) Use Stata's -tempname- to declare E1 
tempname E1
mata: `E1' = ...

2) Make a Mata function as the main program, so that E1 is within it:
MyMainMataProgram() {
  E1 = MyMata1()
  MyMata2(E1, ...)

Both options 1) and 2)  seem unattractive.  Can others comment on these options, 
including using "unhidden" externals as I suggested in my schematic, and/or suggest 
something else?  I understand that I could retain some intermediate results like E1 
as Stata scalars or matrices, but that is often clumsy or impractical.


Mike Lacy
Dept. of Sociology
Colorado State University
Fort Collins CO 80523-1784

*   For searches and help try:

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