I'm trying to program up a minimum distance estimator for a structural model that attempts to match some model consistent calculations with some IV regression coefficients by varying 2 parameters. Essentially I want it to run such that:
  1. Guess 2 parameter values
  2. Using the guessed parameter values construct some model consistent values for each observation
  3. Create a binary variable based on the model consistent values, split at the median determining "high" and "low".
  4. Run an IV regression using the original data (that wasn't constructed by the model) but with an interaction term for "high" from step 3.
  5. Check L2 norm between the coefficients from the regression and the means of the "high" and "low" group.
  6. Rinse and repeat until step 5 is minimized.
From the reading I've done I get the impression I need to use the optimize function in mata though I'm unclear how. Below are the general steps of the code. Step 5 is what I need to minimize and step 1 contains the parameters I need to guess. I'm guessing the below needs to be defined in a program, but any guidance in how to do this in conjunction with utilising mata and the optimize function would be appreciated.
Code:
*1. Choose parameter values
gen k = *guess1_1*
gen scale = *guess1_2*

*2. Calculate model consistent elasticities
** relevant code which generates variable T for each observation**

*3. Cut by median & calculate model measures
egen median_T = median(T)
gen High = T > median_T

qui sum T if High == 0
gen model_low = r(mean)
qui sum T if High == 1
gen model_high = r(mean)

*4A. Calculate interaction terms for IV
gen lnxXHigh = lnx * High
gen zXHigh = z*High

*4B. Calculate empirical measures
qui ivreghdfe lnY High (lnx lnxXHigh = z zXHigh) if a(c y ym) cluster(c)

gen empirical_low = _b[lnx]
gen empirical_high = _b[lnx] + _b[lnxXHigh]


*5. Euclidean distance
gen euc_distance = sqrt((empirical_low - model_low)^2 +(empirical_high-model_high)^2)
Note: cross posted https://stackoverflow.com/questions/...ing-stata-mata