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: Mata void functions and pointers

From (Jeff Pitblado, StataCorp LP)
Subject   Re: st: Mata void functions and pointers
Date   Thu, 17 May 2012 17:41:38 -0500

Matthew Baker <> is working with pointers in 
Mata.  Originally he wrote:

> I have a problem in which I am trying to populate the elements of
> a pointer with the results of a function. The problem is, the function
> is void and returns its results through an argument, which makes
> getting results into a pointer nontransparent. As a simple example,
> consider the following:
> (example omitted)

Brendan Halpin <> replied with a suggestion for Matthew's
specific, but it did not address Mathew's general need, so Mathew gave us more

> I should have been more clear! I would certainly prefer to use a
> vector to collect the elements, but the objects I'm collecting are of
> unknown dimension which is not known in advance, so perhaps I should
> have used an example like:
> /* Begin example */
> clear all
> mata
> void example(A,B,Ab) Ab=J(A+round(3*runiform(1,1)),B,1)
> P=J(3,1,NULL)
> for (i=1;i<=3;i++) {
> 	example(i,i,Ab=.)
> 	Ab
> 	P[i]=&Ab
> 				   }
> /* display results */
> for (i=1;i<=3;i++) *P[i]
> end
> /* end example */
> I have thought about trying to readjust the dimensions of the vector
> every time it is a little different, but this seems kind of clumsy and
> I was hoping for a better alternative.

Mathew can preallocate each element of the P vector with an address to it's
own copy of a default Mata object, then pass that object to his 'example()'
function.  Here is how that would work with Mathew's example above:

***** BEGIN:
clear all
void example(A,B,Ab) Ab=J(A+round(3*runiform(1,1)),B,1)
for (i=1;i<=3;i++) {
	P[i] = &J(0,0,.)		// PREALLOCATION

/* display results */

for (i=1;i<=3;i++) *P[i]
***** END:

*   For searches and help try:

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