Mata course: Construction

Where to put Mata code

Consider the Mata code

: st_view(X=., ., ("weight", "foreign", "one"))

: st_view(y=., ., "mpg")

: invsym(cross(X,X))*cross(X,y)

What do we do with it?

1. Put it a do-file

myfile.do ---
clear
sysuse auto
mata:
st_view(X=., ., ("weight", "foreign", "one"))
st_view(y=., ., "mpg")
invsym(cross(X,X))*cross(X,y)
end

myfile.do ---

2. Put it in an ado-file

myreg.ado ---
program myreg
version 9
syntax varlist [if] [in]
marksample touse
tempvar one
qui gen byte one=1

mata: myreg("`varlist' one", "`touse'")
end

version 9
mata:
function myreg(string scalar varnames, string scalar touse)
{
string rowvector vars, rhsvars
string scalar lhsvar
real matrix X
real colvector y

vars = tokens(varnames)
lhsvar = vars[1]
rhsvars = vars[|2\.|]
st_view(X, ., rhsvars, touse)
st_view(y, ., lhsvar, touse)
invsym(cross(X,X))*cross(X,y)
}
end

myreg.ado ---

Also see hsearch.ado.

Put it in a .mo file

makemyreg.do ---
clear
version 9
mata:
function myreg(string scalar varnames, string scalar touse)
{
string rowvector vars, rhsvars
string scalar lhsvar
real matrix X
real colvector y

vars = tokens(varnames)
lhsvar = vars[1]
rhsvars = vars[|2\.|]
st_view(X, ., rhsvars, touse)
st_view(y, ., lhsvar, touse)
invsym(cross(X,X))*cross(X,y)
}
mata mosave myreg(), replace
end

makemyreg.do ---

myreg.ado ---
program myreg
version 9
syntax varlist [if] [in]
marksample touse
tempvar one
qui gen byte one=1

mata: myreg("`varlist' one", "`touse'")
end

myreg.ado ---

4. Put it in a .mlib library

addmyreg.do ---
clear
version 9
mata:
function myreg(string scalar varnames, string scalar touse)
{
string rowvector vars, rhsvars
string scalar lhsvar
real matrix X
real colvector y

vars = tokens(varnames)
lhsvar = vars[1]
rhsvars = vars[|2\.|]
st_view(X, ., rhsvars, touse)
st_view(y, ., lhsvar, touse)
invsym(cross(X,X))*cross(X,y)
}
mata mlib create lmylib, replace
mata mlib add lmylib myreg()
end

addmyreg.do ---

myreg.ado ---
program myreg
version 9
syntax varlist [if] [in]
marksample touse
tempvar one
qui gen byte one=1

mata: myreg("`varlist' one", "`touse'")
end

myreg.ado ---

Top