Mata Course:  Basics
-------------


1.  How to enter and exit Mata


	.
	. mata
	--------------------------------------- mata (type end to exit) -------------
	: end
	-------------


	.
	. mata
	--------------------------------------- mata (type end to exit) -------------
	: end
	-------------


	. mata
	--------------------------------------- mata (type end to exit) -------------
	:


    We will stay in Mata


2.  Treatment of expressions


	: 2+2              <- type an expression, see the result
	  4

	: x = 2 + 2        <- or assign an expression

	: x                <- x is an expression ...
	  4                   type an expression, see the result


3.  Errors


	: 2,,3
	invalid expression
	r(3000);

	: y
	            <istmt>:  3499  y not found
	r(3499);

    Return code 3000 means "I don't understand".

    All other return codes mean, "I understood you alright, but I can't".


4.  Types


4.1  Types:  Real


	: 2 + 3
	  5


4.2  Types:  Complex


	: 1+2i + 4-1i
	  5 + 1i

	: 1+2i - 2i
	  1

	: 2.5e+3i
	  2500i


4.3  Types:  String


	: "Alpha" + "Beta"
	  AlphaBeta


4.4  Types:  errors


	: 2 + "alpha"
	            <istmt>:  3250  type mismatch
	r(3250);


"I understood you alright, but I can't."


5.  Vectors


5.1  Vectors:  Row


	: x = (1,2)

	: x
	       1   2
	    +---------+
	  1 |  1   2  |
	    +---------+

	: x + (3,4)
	       1   2
	    +---------+
	  1 |  4   6  |
	    +---------+

	: y = (3,4)

	: z = (x,y)              <- comma is an operator

	: z
	       1   2   3   4
	    +-----------------+
	  1 |  1   2   3   4  |
	    +-----------------+


5.2  Vectors:  Column


	: a = (1\2)

	: a
	       1
	    +-----+
	  1 |  1  |
	  2 |  2  |
	    +-----+

	: b = (3\4)

	: c = (a\b)           <- backslash is an operator

	: c
	       1
	    +-----+
	  1 |  1  |
	  2 |  2  |
	  3 |  3  |
	  4 |  4  |
	    +-----+


6.  Matrices


	: A = (1,2 \ 3,4)

	: A
	       1   2
	    +---------+
	  1 |  1   2  |
	  2 |  3   4  |
	    +---------+

	: x\y                      x and y are row vectors
	       1   2
	    +---------+
	  1 |  1   2  |
	  2 |  3   4  |
	    +---------+

	: a,b                      a and b are column vectors
	       1   2
	    +---------+
	  1 |  1   3  |
	  2 |  2   4  |
	    +---------+

	: Z = (1+1i, 2+3i \ 3-2i, -1-1i)

	: Z
	             1         2
	    +---------------------+
	  1 |   1 + 1i    2 + 3i  |
	  2 |   3 - 2i   -1 - 1i  |
	    +---------------------+

	: S = ("1st element", "2nd" \ "third", "fourth")

	: S
	                 1             2
	    +-----------------------------+
	  1 |  1st element           2nd  |
	  2 |        third        fourth  |
	    +-----------------------------+


7.  Functions


	: sqrt(4)                real result
	  2

	: sqrt(-4)               missing real result
	  .

	: findout = sqrt(-4)

	: findout                still missing
	  .


7.1  Functions:  Complex


	: sqrt(-4+0i)            CICO:  Complex In, Complex Out
	  2i

	: areal = -4

	: acomplex = -4 + 0i

	: sqrt(areal)
	  .

	: sqrt(acomplex)
	  2i

	: sqrt(C(areal))         C() means "cast to complex"
	  2i

	: sqrt(-4+2i)
	  .485868272 + 2.05817103i


7.2  Functions:  Matrix


	: X = (76, 53, 48 \ 53, 88, 46 \ 48, 46, 63)

	: Xi = invsym(X)

	: Xi
	[symmetric]
	                  1              2              3
	    +----------------------------------------------+
	  1 |   .0298458083                                |
	  2 |  -.0098470272    .0216268926                 |
	  3 |  -.0155497706   -.0082885675    .0337724301  |
	    +----------------------------------------------+

	: Xi*X
	                  1              2              3
	    +----------------------------------------------+
	  1 |             1   -8.67362e-17   -8.50015e-17  |
	  2 |  -1.38778e-16              1   -1.02349e-16  |
	  3 |             0    1.11022e-16              1  |
	    +----------------------------------------------+


7.3  Functions:  Element-by-element (generalized scalar)


	: M = (1,2 \ 3,4 \ 5,6)

	: M
	       1   2
	    +---------+
	  1 |  1   2  |
	  2 |  3   4  |
	  3 |  5   6  |
	    +---------+

	: S = sqrt(M)                // element-by-element

	: S
	                 1             2
	    +-----------------------------+
	  1 |            1   1.414213562  |
	  2 |  1.732050808             2  |
	  3 |  2.236067977   2.449489743  |
	    +-----------------------------+

	: S[1,2]*S[1,2]
	  2


8.  Colon operators


	: A = (1,2 \ 3,4)

	: B = (5,6 \ 7,8)

	: A*B
	        1    2
	    +-----------+
	  1 |  19   22  |
	  2 |  43   50  |
	    +-----------+

	: A:*B
	        1    2
	    +-----------+
	  1 |   5   12  |
	  2 |  21   32  |
	    +-----------+

    Colon may be placed in front of any dyadic (binary) operator.


9.  Programs


	: function add(a, b)
	> {
	>         return(a+b)
	> }

	: add(1,2)
	  3

	: add(1+2i, 4-1i)
	  5 + 1i

	: add(x, y)
	       1   2
	    +---------+
	  1 |  4   6  |
	    +---------+

	: add(A, A)
	       1   2
	    +---------+
	  1 |  2   4  |
	  2 |  6   8  |
	    +---------+

	: add("Alpha", "Beta")
	  AlphaBeta


    Functions can be polymorphic (type free),


    or not,

	: real matrix id(real scalar n)
	> {
	>         real scalar     i
	>         real matrix     res
	>
	>         res = J(n, n, 0)
	>         for (i=1; i<=n; i++) {
	>                 res[i,i] = 1
	>         }
	>         return(res)
	> }

	: I3 = id(3)

	: I3
	[symmetric]
	       1   2   3
	    +-------------+
	  1 |  1          |
	  2 |  0   1      |
	  3 |  0   0   1  |
	    +-------------+

	: id("this")
	              id():  3253  nonreal found where real required
                   <istmt>:     -  function returned error
	r(3253);

	: end
	-------------


10.  Built-in functions


    Mata has a function called pi().


    To see the source code associated with Mata function xyz(),
    in Stata, type

	. viewsource pi.mata
      +------------------------------------------------------+
      | *! version 1.0.0  15oct2004                          |
      | version 9.0                                          |
      | mata:                                                |
      |                                                      |
      | real scalar pi() return(3.141592653589793238462643)  |
      |                                                      |
      | end                                                  |
      +------------------------------------------------------+

    You do not need to look at source to use function:

	.
	. mata
	--------------------------------------- mata (type end to exit) -------------
	: pi()
	  3.141592654

	: printf("%17.0g\n", pi())
	 3.14159265358979

	: end
	-------------


    Mata has builtin functions
    sinh(),
    cosh(),
    and
    tanh():

	.
	. viewsource sinh.mata
      +------------------------------------------------------------------+
      | *! version 1.0.0  15oct2004                                      |
      | version 9.0                                                      |
      | mata:                                                            |
      |                                                                  |
      | numeric matrix sinh(numeric matrix u) return((exp(u)-exp(-u)):/2) |
      |                                                                  |
      | end                                                              |
      +------------------------------------------------------------------+

	.
	. viewsource cosh.mata
      +------------------------------------------------------------------+
      | *! version 1.0.0  15oct2004                                      |
      | version 9.0                                                      |
      | mata:                                                            |
      |                                                                  |
      | numeric matrix cosh(numeric matrix u) return((exp(u)+exp(-u)):/2) |
      |                                                                  |
      | end                                                              |
      +------------------------------------------------------------------+


	.
	. viewsource tanh.mata
      +------------------------------------------------------------------+
      | *! version 1.0.0  15oct2004                                      |
      | version 9.0                                                      |
      | mata:                                                            |
      |                                                                  |
      | numeric matrix tanh(numeric matrix u)                            |
      | {                                                                |
      |         numeric matrix  eu, emu                                  |
      |                                                                  |
      |         eu = exp(u)                                              |
      |         emu = exp(-u)                                            |
      |         return( (eu-emu):/(eu+emu) )                             |
      | }                                                                |
      |                                                                  |
      | end                                                              |
      +------------------------------------------------------------------+


Mata has built-in funcdtion _solvelower():

        . viewsource _solvelower.mata
      +------------------------------------------------------------------------+
      | *! version 1.0.4  25jan2005                                            |
      | version 9.0                                                            |
      |                                                                        |
      | mata:                                                                  |
      |                                                                        |
      | real scalar _solvelower(                                               |
      |                 numeric matrix A, numeric matrix b,                    |
      |                |real scalar usertol, numeric scalar userd)             |
      |  {                                                                     |
      |          real scalar             tol, rank, a_t, b_t, d_t              |
      |          real scalar             n, m, i, im1, complex_case            |
      |          numeric rowvector       sum                                   |
      |          numeric scalar          zero, d                               |
      |                                                                        |
      |          d  = userd                                                    |
      |                                                                        |
      |          if ((n=rows(A))!=cols(A)) _error(3205)                        |
      |          if (n != rows(b))         _error(3200)                        |
      |          if (isview(b))            _error(3104)                        |
      |          m = cols(b)                                                   |
      |          rank = n                                                      |
      |                                                                        |
      |          a_t = iscomplex(A)                                            |
      |          b_t = iscomplex(b)                                            |
      |          d_t = d<. ? iscomplex(d) : 0                                  |
      |                                                                        |
      |          complex_case = a_t | b_t | d_t                                |
      |                                                                        |
      |          if (complex_case) {                                           |
      |                  if (!a_t) A = C(A)                                    |
      |                  if (!b_t) b = C(b)                                    |
      |                  if (d<. & !d_t) d = C(d)                              |
      |                  zero = 0i                                             |
      |          }                                                             |
      |          else zero = 0                                                 |
      |                                                                        |
      |          if (n==0 | m==0) return(0)                                    |
      |                                                                        |
      |          tol = solve_tol(A, usertol)                                   |
      |                                                                        |
      |          if (abs(d) >=. ) {                                            |
      |                  if (abs(d=A[1,1])<=tol) {                             |
      |                          b[1,.] = J(1, m, zero)                        |
      |                          --rank                                        |
      |                  }                                                     |
      |                  else {                                                |
      |                          b[1,.] = b[1,.] :/ d                          |
      |                          if (missing(d)) rank = .                      |
      |                  }                                                     |
      |                                                                        |
      |                  for (i=2; i<=n; i++) {                                |
      |                          im1 = i - 1                                   |
      |                          sum = A[|i,1\i,im1|] * b[|1,1\im1,m|]         |
      |                          if (abs(d=A[i,i])<=tol) {                     |
      |                                  b[i,.] = J(1, m, zero)                |
      |                                  --rank                                |
      |                          }                                             |
      |                          else {                                        |
      |                                  b[i,.] = (b[i,.]-sum) :/ d            |
      |                                  if (missing(d)) rank = .              |
      |                          }                                             |
      |                  }                                                     |
      |          }                                                             |
      |          else {                                                        |
      |                  if (abs(d)<=tol) {                                    |
      |                          rank = 0                                      |
      |                          b = J(rows(b), cols(b), zero)                 |
      |                  }                                                     |
      |                  else {                                                |
      |                          b[1,.] = b[1,.] :/ d                          |
      |                                                                        |
      |                          for (i=2; i<=n; i++) {                        |
      |                                  im1 = i - 1                           |
      |                                  sum = A[|i,1\i,im1|] * b[|1,1\im1,m|] |
      |                                  b[i,.] = (b[i,.]-sum) :/ d            |
      |                          }                                             |
      |                  }                                                     |
      |                                                                        |
      |          }                                                             |
      |                                                                        |
      |         return(rank)                                                   |
      | }                                                                      |
      |                                                                        |
      | end                                                                    |
      +------------------------------------------------------------------------+


    Recommendation: visit help system


          mata > m4 > matrix > solvelower()


                          then clock for source code


          mata > language definition > goto


11.  Programs and ado-files


        . sysuse auto
        (1978 Automobile Data)

        . varsum mpg
           sum = 1576


        . viewsource varsum.ado
      +-----------------------------------------------------------------+
      | *! version 1.0.0                                                |
      | program varsum                                                  |
      |         syntax varname [if] [in]                                |
      |         marksample touse                                        |
      |         mata: calcsum("`varlist'", "`touse'")                   |
      |         display as txt "   sum = " as res r(sum)                |
      | end                                                             |
      |                                                                 |
      | mata:                                                           |
      | void calcsum(string scalar varname, string scalar touse)        |
      | {                                                               |
      |         real colvector     x                                    |
      |         real scalar        sum, i                               |
      |                                                                 |
      |         st_view(x, ., varname, touse)                           |
      |                                                                 |
      |         sum = 0                                                 |
      |         for (i=1; i<=rows(x); i++) {                            |
      |                 sum = sum + x[i]                                |
      |         }                                                       |
      |                                                                 |
      |         st_numscalar("r(sum)", sum)                             |
      | }                                                               |
      | end                                                             |
      +-----------------------------------------------------------------+


        . drop _all

        . set obs 10000
        obs was 0, now 10000

        . gen x = uniform()

        . varsum(x)
           sum = 4998.4725


-------------
Top