*! version 1.0.2  13jan2006  by Marc-Andreas Muendler: muendler@ucsd.edu
program define matmerge
  version 8.2
  syntax newvarname , Matrix(string) [ ASRow ASCol ]
  local matname = subinstr("`1'",`","',"",.)
  local cols = colsof(`matname')
  local rows = rowsof(`matname')
  tempname newmat
  * local newmat "newmat"
  if "`asrow'"=="" & "`ascol'"=="" {
    disp as err "row or column merge must be specified"
    exit 100
    }
  if "`ifrow'"~="" & "`ifcol'"~="" {
    disp as err "simultaneous row and column merge not allowed"
    exit 101
    }
  capture local chk = rowsof(`matrix')
  if _rc~=0 {
    mat `matrix' = `matname'
    exit
    }
  if "`matrix'"=="`matname'" {
    if "`asrow'"~="" {
      mat `matrix' = `matrix' \ `matname'
      }
    if "`ascol'"~="" {
      mat `matrix' = `matrix' , `matname'
      }
    exit
    }
  local colsold = colsof(`matrix')
  local rowsold = rowsof(`matrix')

  /* Row Merge */
  if "`asrow'"~="" {
    local rownames : rowfullnames `matname'
    local rowno = rowsof(`matname')
    local colvars : colfullnames `matrix'
    forvalues i = 1/`rowno' {
      mat `matrix' = `matrix' , J(1,`colsold',.)
      local newrow = rowsof(`matrix')
      tokenize `rownames'
      matname `matrix' ``i'', rows(`newrow') explicit
      tokenize `colvars'
      forvalues colj = 1/`colsold' {
        mat `matrix'[`newrow',`colj'] = `matname'[`i',colnumb(`matname',"``colj''")]
        if `matrix'[`newrow',`colj']==. {
          mat `matrix'[`newrow',`colj'] = .
          }
        }
      }
    }

  /* Col Merge */
  if "`ascol'"~="" {
    local colnames : colfullnames `matname'
    local colno = colsof(`matname')
    local rowvars : rowfullnames `matrix'
    forvalues j = 1/`colno' {
      mat `matrix' = `matrix' , J(`rowsold',1,.)
      local newcol = colsof(`matrix')
      tokenize `colnames'
      matname `matrix' ``j'', columns(`newcol') explicit
      tokenize `rowvars'
      forvalues rowi = 1/`rowsold' {
        mat `matrix'[`rowi',`newcol'] = `matname'[rownumb(`matname',"``rowi''"),`j']
        if `matrix'[`rowi',`newcol']==. {
          mat `matrix'[`rowi',`newcol'] = .
          }
        }
      }
    }

end