Thanks Kit. Sorry that I wasn't clear enough in the previous post, but
your answer is exactly what I wanted.
Le
On 10/1/07, Kit Baum <[email protected]> wrote:
> Le said
>
> I am trying to program a Mata function with optional arguments. For
> example, I want to: (1) read the data y and x (2) create a matrix
> equals x and J(rows(x),1,1) (constant) (3) create a matrix x'*y
>
> void myfunction(string scalar depvar, | string scalar varlist)
> {
> st_view(y=.,.,depvar,.)
> st_view(x=.,.,varlist,.)
>
> x=x,J(rows(x),1,1)
>
> x'*y
> }
>
> The program will work fine if i specify the varlist
> myfunction("y","x")
>
> However, it won't work if I don't specify the varlist because
> "st_view(x=.,.,varlist,.)" requires an argument. How should I solve
> this problem?
>
>
> But what should the function do if a varlist is not provided? Should
> it just create a vector of 1s? If so you want to make the st_view of
> x conditional on whether a varlist was provided, and likewise
> generate x = J(rows(y),1,1). I believe this is doing the right thing:
>
> mata: mata clear
> mata:
> real matrix myf(string scalar depvar, | string scalar varlist)
> {
> st_view(y=.,.,depvar)
> if (args()==1) {
> x = J(rows(y),1,1)
> }
> else {
> st_view(x=.,.,varlist)
> x = x,J(rows(x),1,1)
> }
> return(x'*y)
> }
> end
>
>
> See [M-2] optargs.
>
> Kit
>
>
> Kit Baum, Boston College Economics and DIW Berlin
> http://ideas.repec.org/e/pba1.html
> An Introduction to Modern Econometrics Using Stata:
> http://www.stata-press.com/books/imeus.html
>
>
> *
> * For searches and help try:
> * http://www.stata.com/support/faqs/res/findit.html
> * http://www.stata.com/support/statalist/faq
> * http://www.ats.ucla.edu/stat/stata/
>
--
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Le Wang, Ph.D.
Minnesota Population Center
University of Minnesota
(o) 612-624-5818
*
* For searches and help try:
* http://www.stata.com/support/faqs/res/findit.html
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/