Bookmark and Share

Notice: On March 31, it was announced that Statalist is moving from an email list to a forum. The old list will shut down at the end of May, and its replacement, is already up and running.

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

st: Re: "eval" in Mata?

From   "Joseph Coveney" <>
To   <>
Subject   st: Re: "eval" in Mata?
Date   Sat, 20 Oct 2012 12:45:45 +0900

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()

: end

. set linesize `linesize'

. exit

end of do-file

*   For searches and help try:

© Copyright 1996–2014 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   Site index