program define outmat
  version 7

  gettoken mat   0: 0
  gettoken usage 0: 0
  gettoken file  0: 0 , parse(", ")

  syntax , [MATname(str) REPLACE]

  tokenize `file', parse(".")
  if "`2'"~="." { local file `file'.do }

  if "`usage'" ~= "using" { error 198 }
  if "`file'"==""        { error 198 }
  if "`matname'"=="" { local matname `mat' }

  confirm name `matname'

  tempname it
  mat `it'=`mat'

  local n = rowsof(`it')
  local k = colsof(`it')

  local lnsize : set linesize
  local more   : set more

  qui log
  local waslog = r(filename)
  if "`waslog'"~="" { cap log close }

  di as text _n "Please never mind to what we shall be doing now." _n "The output will be redirected to " as res "`file'" as text "." _n

  set linesize 255
  qui log using `file', `replace' text
  set more off

  di as inp "mat `matname' = J(`n',`k',0)"
  local m=2
  forvalues i=1/`n' {
    forvalues j=1/`k' {
       di as inp "mat `matname'[`i',`j'] = " %24.0g `it'[`i',`j']
       local m=`m'+1
    }
  }
  local rn : rowfullname `it'
  di as inp "mat rowname `matname' = `rn'"
  local cn : colfullname `it'
  di as inp "mat colname `matname' = `cn'"

  di as inp "exit"
  qui log close

  set linesize `lnsize'
  set more `more'
  if "`waslog'"~="." { qui log using `"`waslog'"', append }

  di as text _n "Run " as res "`file'" as text " to restore your matrix " as res "`matname'" as text "."
end