Stata The Stata listserver
[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

Re: st: [Mata] passing a function to mata


From   [email protected] (William Gould, Stata)
To   [email protected]
Subject   Re: st: [Mata] passing a function to mata
Date   Thu, 25 Aug 2005 13:34:33 -0500

Antoine Terracol <[email protected]> wants to pass 
a function to Mata.

He imagines a function 

        real scalar gaussher(funct)
        {
                ...
                ... calls funct(x) somehow
                ...
                return(...)
        }

where funct is the name of a function.

The way to proceed is

        real scalar gaussher(pointer(function) funct)
        {
                ...
                ... (*funct)(x) ...
                ...
                return(...)
        }

Although, if you prefer, we could omit the "pointer(function)" part 
(declarations are always optimal), and then our code would read.

        real scalar gaussher(funct)
        {
                ...
                ... (*funct)(x) ...
                ...
                return(...)
        }

In any case, we might define the function 

        function xsquared (real x)
        {
                return(x:^2)
        }

and then, to execute gaussher() using xquared(), we would type 

        : gaussher(&xsquared())

xsquared() is the function we are passing to guassher().  In our call, 
we put an & in front of the function name, to say that we do not want
to execute the function xsquared(); we merely wish to pass its identity
(well, address, to be precise).

In our gaussher() function, the corresponding argument we receive is
"pointer(function) funct".  That states that funct will be the address
of a function.  Asterisk is the operator that substitutes the thing 
itself for an address, so we execute the function by coding coding
(*funct)(x).

Try the following example:

        . mata
        --------------------------------- mata (type end to exit) -----
        : function gaussher(funct)
        > {
        >          return( (*funct)(2) )
        > }
 
        : function me(x) return(x+3)
 
        : gaussher(&me())
          5

        : end
        ---------------------------------------------------------------

For more information, see -help m2_ftof- on-line, or [M-2] ftof in the 
manual.


-- Bill
[email protected]
*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index