Question

I would like to perform calculations in Mata returning a scalar result. I would then like to access that result in a macro in Stata. For example, I type:

mata: st_numscalar("dog", sum(range(1,4,1)))

Then I type (in Stata):

di `dog'

and I then get (nothing):

When I expected to get:

10

Thinking that perhaps the macro dog needs to exist first, I prefix the above commands with:

scalar dog = 0

but no dice.

Then, thinking that scalars are weird, and why not simply use a good old local:

mata: st_local("dog", sum(range(1,4,1)))

But this just gives grief (whether or not a local named "dog" with a numeric value is created beforehand or not).

What am I missing?

Was it helpful?

Solution

Two key points:

Scalars are scalars and macros are macros. But a scalar can have a temporary name, which is where you can get confused.

Macros are strictly strings. Numeric scalars can only hold numbers. (There are string scalars too.)

. mata : st_numscalar("frog", 42)
. di frog
42

That's a scalar with a permanent name. But watch out: if you had a variable called frog, that interpretation would trump the scalar interpretation.

. tempname toad
. mata : st_numscalar("`toad'", 24)
. di `toad'
24

That's a scalar with a temporary name.

. mata : st_local("newt", "1000")
. di `newt'
1000

That's a local macro, which holds the string "1000".

You can do things like this.

. di `newt' + `toad'
1024

But that is because two things are happening here. Stata is first interpreting the references to the local macro and the scalar and substituting their contents. So display then sees

. di 1000 + 24 

and does the calculation. But you could insist on a string interpretation.

. di "`newt'`toad'"
1000__000000

which underlines that you have to keep straight the difference between the name of something and its contents. Here the string

"`toad'" 

is the name of the scalar, which is a temporary name.

Also consider this:

. local anothernewt = 1000
. di `anothernewt'
1000
. di "`anothernewt'"
1000

Stata lets you specify a numeric interpretation or a string interpretation. Sure, the results look similar, but in principle they are different. The question is whether that bites you (not in this example).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top