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]

Re: st: Creating new variables in mata.

From   "Thomas, Anthony" <>
Subject   Re: st: Creating new variables in mata.
Date   Wed, 19 Feb 2014 12:50:12 -0500

It sounds like what you want to do is group a lot of similar variables
together in a way that is easy to reference in loops later. The usual
way to do this is to create an array, and then loop over the elements
of the array. If you are not familiar with pointers/ arrays and their
use in Mata, I would suggest searching some of the Stata literature on
pointers ("help pointer"). I'm certainly no expert on pointers or
complicated data structures in Mata so take this with some caution.
But the basic principle is as follows:


// create a matrix to store pointers - NULL is just a special pointer
that points to nothing

store = J(1, 2, NULL)

// create some example matrices

A = J(10, 10, 1)
B = J(10, 10, 2)

// store the address of those matrices in the array

store[1] = &A
store[2] = &B


// "store" now contains the addresses of A and B, to access the [1,
1]th element of A say -

(*store[1])[1, 1]
(*store[2])[2, 5]

// * retrieves the value stored at an address


saying (*store[1]) tells mata to "retrieve the values stored at the
memory address given in the first element of 'store'", the [i, j]
works as expected.

Hope that helps,


On Wed, Feb 19, 2014 at 10:22 AM, Amadou DIALLO <> wrote:
> Hi,
> Maybe this has been already answered, but I can't find it.
> What is the equivalent of the stata code below in mata?
> forv i = 1/10 {
>    cap drop var`i'
>    g var`i' = ...
> }
> I've read Bill's "mata matters: macros" and creating new variables,
> but I can't find how to parse the "i".
> Thanks.
> --
> Amadou B. DIALLO, PhD.
> Senior Economist, AfDB.
> +21671101789
> *
> *   For searches and help try:
> *
> *
> *
*   For searches and help try:

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