Mata course: Using views

A statistical application

Calculate

y = (X'X)^(-1)*X'y

for

y = (mpg)

X = (weight, foreign, 1)

Solution:

. sysuse auto, clear
(1978 Automobile Data)

. gen one = 1

. mata

mata (type end to exit)

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

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

: invsym(X'X)*X'y
1
+
+
1 | -.0065878864 |
2 | -1.650029106 |
3 | 41.67970233 |
+
+

: end

Notes:

1.
Using lots of views is not only okay, it is encouraged.

2.
What is bad about the code above is the calculation of X'.
It would be better to use cross().

Rather than code

invsym(X'X)*X'y

code

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

That not only uses less memory, it is faster.

See [M-5] cross().

A data-management application

You have a dataset containing variables

stat72, stat73, ..., stat99.

They record a patient's status in 1972, 1973, ..., 1999.

You wish to add new variable

firstyear

recording the first year
in which a status variable takes on the value 1.

Solution:

. use ds1, clear

. gen byte firstyear = .
(500 missing values generated)

.
. mata:

mata (type end to exit)

: names = "s72 s73 s74 s75 s76 s77 s78 s79
s80 s81 s82 s83 s84 s85 s86 s87 s88 s89
s90 s91 s92 s93 s94 s95 s96 s97 s98 s99"

: st_view(s=., ., tokens(names))

: st_view(first=., ., "firstyear")

:
: for (i=1; i<=rows(s); i++) {
> for (j=1; j<=cols(s); j++) {
> if (s[i,j]==1) {
> first[i] = j+71
> break
> }
> }
> }

: end

do ds1

Another example

See
panelsetup().

Top