{smcl} {bf:Mata course: Using views} {hline} {title:A statistical application} {p 4 4 2} Calculate {it:y} = ({it:X}'{it:X})^(-1)*{it:X}'{it:y} {p 4 4 2} for {it:y} = (mpg) {it:X} = (weight, foreign, 1) {p 4 4 2} Solution: {com}. sysuse auto, clear {txt}(1978 Automobile Data) {com}. gen one = 1 {txt} {com}. mata {txt}{hline 49} mata (type {cmd:end} to exit) {hline} {com}: st_view(X=., ., ("weight", "foreign", "one")) {res} {com}: st_view(y=., ., "mpg") {res} {com}: invsym(X'X)*X'y {res} {txt} 1 {c TLC}{hline 16}{c TRC} 1 {c |} {res}-.0065878864{txt} {c |} 2 {c |} {res}-1.650029106{txt} {c |} 3 {c |} {res} 41.67970233{txt} {c |} {c BLC}{hline 16}{c BRC} {com}: end {txt}{hline} {p 4 4 2} Notes: {p 8 12 2} 1. Using lots of views is not only okay, it is encouraged. {p 8 12 2} 2. What is bad about the code above is the calculation of {cmd:X'}. It would be better to use {cmd:cross()}. {p 12 12 2} Rather than code {cmd:invsym(X'X)*X'y} {p 12 12 2} code {cmd:invsym(cross(X,X))*cross(X,y)} {p 12 12 2} That not only uses less memory, it is faster. {p 12 12 2} See {bf:{help mf_cross:[M-5] cross()}}. {title:A data-management application} {p 4 4 2} You have a dataset containing variables stat72, stat73, ..., stat99. {p 4 4 2} They record a patient's status in 1972, 1973, ..., 1999. {p 4 4 2} You wish to add new variable firstyear {p 4 4 2} recording the first year in which a status variable takes on the value 1. {p 4 4 2} Solution: {com}. use ds1, clear {txt} {com}. gen byte firstyear = . {txt}(500 missing values generated) {com}. . mata: {txt}{hline 49} mata (type {cmd:end} to exit) {hline} {com}: 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" {res} {com}: st_view(s=., ., tokens(names)) {res} {com}: st_view(first=., ., "firstyear") {res} {com}: : for (i=1; i<=rows(s); i++) {c -(} > for (j=1; j<=cols(s); j++) {c -(} > if (s[i,j]==1) {c -(} > first[i] = j+71 > break > {c )-} > {c )-} > {c )-} {res} {com}: end {txt}{hline} {bf:{stata do ds1}} {title:Another example} {p 4 4 2} See {bf:{help mf_panelsetup:panelsetup()}}. {hline} {bf:{view talk.smcl:Top}}