Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
st: RE: Re: "eval" in Mata?
From 
 
Sun Yutao <[email protected]> 
To 
 
<[email protected]> 
Subject 
 
st: RE: Re: "eval" in Mata? 
Date 
 
Sat, 20 Oct 2012 12:50:39 +0200 
Ah,
Thanks Joseph, that's a smart way of doing this!
-----Original Message-----
From: [email protected] [mailto:[email protected]] On Behalf Of Joseph Coveney
Sent: Saturday, October 20, 2012 5:46 AM
To: [email protected]
Subject: st: Re: "eval" in Mata?
Sun Yutao wrote:
I'm just wondering if there is an "eval()" function in Mata. It should take a string and execute that as if it was actual Mata command.
--------------------------------------------------------------------------------
I'm not sure how well an eval() function would fit in to the concept and purpose of Mata, but Bill Gould would be the authority on this.  If you desperately need a way of evaluating a string expression as a Mata statement inside another Mata function, then there are probably work-arounds that take advantage of Stata . . . something like that below, perhaps, which assumes that the Mata expression returns a result of some kind.  (The helper function is needed so that the global Mata variable, A, is no longer in use by the time -eval()- wants to clean up after itself.  With just a little extra Mata code, you can create and use a Stata local macro as the name of the global Mata variable if you're worried that A might already exist and be in-use elsewhere in Mata when
-eval()- is called.)
Joseph Coveney
. 
. version 11.2
. 
. clear *
. set more off
. set seed `=date("2012-10-20", "YMD")'
. local linesize `c(linesize)'
. set linesize 80
. 
. mata:
------------------------------------------------- mata (type end to exit) ------
: mata set matastrict on
: 
: transmorphic function evaluator(string scalar mata_statement) {
>         stata("mata: A = " + mata_statement)
>         external A
>         return(A)
> }
: 
: transmorphic function eval(string scalar mata_statement) {
>         transmorphic result
>         result = evaluator(mata_statement)
>         stata("mata: mata drop A")
>         return(result)
> }
: 
: void function test() {
>         string scalar test_result
>         test_result = strofreal(eval("runiform(1, 1)"))
>         printf("%14s\n", test_result)
> }
: 
: test()
      .8388072
: 
: end
--------------------------------------------------------------------------------
. 
. set linesize `linesize'
. 
. exit
end of do-file
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/faqs/resources/statalist-faq/
*   http://www.ats.ucla.edu/stat/stata/
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/faqs/resources/statalist-faq/
*   http://www.ats.ucla.edu/stat/stata/