Following codes use nl to fit a quadratic regression and using mata to do calculation:
In mata, I directly set value of `y'. But the problem is that, if I remove the line replace `y'=y1 (this line set values again), the nl command wil fail. I'm curious about why I can't directly change values in mata.
Code:
clear
set obs 1000
gen x=2*(runiform()-0.5)
gen y=0.6*x^2+0.3+rnormal()
gen y1=.
mata: mata clear
mata:
function squad(string scalar xvar, string scalar yvar, string scalar mat, string scalar touse){
coeff=st_matrix(mat)
a=coeff[1,1]
b=coeff[1,2]
st_view(x=., ., xvar, touse)
st_view(y1=., ., "y1", touse) //use this variable to track tempvar
_y=a :* x :^2 :+b
y1[.]=_y
st_view(y=., ., yvar, touse)
y[.]=_y //directly modify temporary var.
}
end
cap program drop nlquadrege
program define nlquadrege
version 17
syntax varlist(min=2 max=2) [aw fw iw] if, at(name)
local y : word 1 of `varlist'
local x : word 2 of `varlist'
marksample touse
mata : squad("`x'","`y'", "`at'", "`touse'")
replace `y'=y1 //If remove this line, there will be error.
end
nl quadrege @ y x , parameters(a b) initial(a 1 b 1) log trace

Comment