*! version 1.0.2  02feb2005  by Marc-Andreas Muendler: muendler@ucsd.edu
program define matkeep
  version 7
  syntax newvarname , Matrix(string) [ IFRow(string) IFCol(string) OVERwrite ]
  local matname = subinstr("`1'",`","',"",.)
  local cols = colsof(`matname')
  local rows = rowsof(`matname')
  tempname newmat
  * local newmat "newmat"
  if "`ifrow'"=="" & "`ifcol'"=="" {
    disp as err "row or column list required"
    exit 100
    }
  if "`ifrow'"~="" & "`ifcol'"~="" {
    disp as err "simultaneous row and column lists not allowed"
    exit 101
    }

  /* Row Keep */
  if "`ifrow'"~="" {
  local totrows :  word count `ifrow'
  tokenize `ifrow'
  local rownames : rowfullnames `matname'
  mat `newmat' = `matname'[1,1..`cols']  /* keep first row for build-up */
  local pickrow = 0
  foreach rowname in `rownames' {
    local pickrow = `pickrow' + 1
    forvalues i = 1/`totrows' {
      if "`rowname'"=="``i''" {  /* add row by row */
        mat `newmat' = `newmat' \ `matname'[`pickrow',1..`cols']
        }
      }
    }
  if rowsof(`newmat') > 1 {
    mat `newmat' = `newmat'[2..`totrows'+1,1..`cols']  /* remove first row */
    }
  else {
    disp as err "specified row(s) not found"
    exit 111
    }
  }

  /* Col Keep */
  if "`ifcol'"~="" {
  local totcols :  word count `ifcol'
  tokenize `ifcol'
  local colnames : colfullnames `matname'
  mat `newmat' = `matname'[1..`rows',1]  /* keep first column for build-up */
  local pickcol = 0
  foreach colname in `colnames' {
    local pickcol = `pickcol' + 1
    forvalues i = 1/`totcols' {
      if "`colname'"=="``i''" {  /* add column by column */
        mat `newmat' = `newmat' , `matname'[1..`rows',`pickcol']
        }
      }
    }
  if colsof(`newmat') > 1 {
    mat `newmat' = `newmat'[1..`rows',2..`totcols'+1]  /* remove first column */
    }
  else {
    disp as err "specified column(s) not found"
    exit 111
    }
  }

  /* Finalize */
  if "`matrix'"=="`matname'" {
    mat drop `matname'
    mat `matname' = `newmat'
    }
  else {
    capture local check = colsof(`matrix')
    if _rc==0 & "`overwrite'"=="" {
       disp as err "no; matrix " in yellow "`matrix'" in red " would be lost"
       exit 4
       }
    mat `matrix' = `newmat'
    }
end