0
votes

This question is in continuation of this, but since it can be answered without knowledge of my previous question, I thought posting a new question was the way to do it (I'm sorry if this is not the case). In the previous question I was told that putting Mata code at the end of my .ado-file would make the local var2 usable within the Stata code. A minimal example is the following:

program define hello
args var1
local sum_var=`var1'+`var2'
disp `sum_var'
end

mata
void cens_func(todo, x, y, g, H)
{
y = (x-1)^2
}

S = optimize_init()
optimize_init_evaluator(S, &cens_func())
optimize_init_which(S, "min")
optimize_init_params(S, 2)
temp=optimize(S)
st_local("var2",strofreal(temp))
end

which unfortunately does not run. I am getting an invalid syntax error. Running this in a .do-file with the Mata code first, causes no errors. What am I missing here? Thanks in advance.

3

3 Answers

1
votes

Specifically, you don't define var2 so that alone should cause the first assignment of a local to fail as Stata will see a hanging plus sign.

There is any case no chance of this working if only because the Mata function is never called by the Stata code.

Generally, reports such as "does not run" or even "syntax error" are not really informative as they give no real clue to others on what is happening. Stata is not at fault here as it provides debugging tools so that with set trace on you can see which line is failing.

Running this as a do-file just defines a program; it doesn't certify that it is legal or even correct.

On this evidence, you should try writing some simpler programs before you have a realistic prospect of getting this to work. Even copying some of the example programs from the manual will help.

1
votes

I will refer back to my answer yesterday. Mata will create a new local, or change an existing local, but you can't use a local before it has been created. Nothing to do with Mata changes that.

On calling Mata from Stata, see help m1_ado.

Thus in your code, you would need a Mata call before you tried to use var2 as your Mata function creates var2.

1
votes

I do this quite a bit:

program define... 
  tempvar var2
  gen `var2' = <<whatever>>
  mata: myroutine("`var2'")
end

mata:
void myroutine(string scalar inputvar)
{
  real vector v
  st_view(v,.,inputvar)
  <<use v somehow>>
}
end

You call also use st_store to write a new Stata variable. My code just reads it into Mata.