Mata course: The programming language

Only a few things to know

if if (exp) ... else ...

for for (exp1; exp2; exp3) stmt

while while (exp) stmt

do do ... while (exp)

break break out of for, while, or do

continue continue with next iteration of for, while, or do

goto goto label

return return(exp)

and then there are

declarations

Declarations

1. You do not need them.

2. Using them makes your code easier to debug.

3. Using them can make your code easier to understand in the future.

4. Using them can make your code run faster.

What's a declaration

Consider the following program

function silly()
{
return(2)
}

and then consider

real scalar silly()
{
return(2)
}

The real scalar part is a declaration.

You are not required to specify it. The program works either way.

Advantages of specification:

1.
It is now obvious that code returns a real scalar even without
looking at the body (pretend the return(2) was really long).

2.
Mata can catch the errors in your program if it attempts to return anything
but a real scalar (perhaps the return(2) part has a bug).

So what can a function return?

A function can return

void

or it can return

column 1 column 2

real scalar
complex rowvector
numeric colvector
string vector
pointer matrix
transmorphic

Choose one word from column 1 and one
from column 2

When you do not declare what a function returns,

transmorphic matrix

is assumed.

Argument declarations

Just as with return values, functions can declare the types of their
arguments

real scalar add(real scalar a, real scalar b)
{
return(a+b)
}

or not

real scalar add(a, b)
{
return(a+b)
}

Advantages of argument declarations:

1. As a user, I can more easily see how the function is intended to be used.

2. If I make a mistake using the function, Mata can tell me.

So what can arguments be?

Anything but void.

Choose a word from column 1, and a word from column 2.

column 1 column 2

real scalar
complex rowvector
numeric colvector
string vector
pointer matrix
transmorphic

When you do not say what an argument is

transmorphic matrix

is assumed.

Declaration of working variables

In your program, you can introduce new variables as you need them:

real scalar getvalue(real colvector V, real scalar i, real scalar j)
{
if (j<i) idx = i*5 + j
else idx = j*5 + i
return(V[idx])
}

or you can declare them ahead of time

real scalar getvalue(real colvector V, real scalar i, real scalar j)
{
real scalar idx

if (j<i) idx = i*5 + j
else idx = j*5 + i
return(V[idx])
}

Advantages of declarations:

1.
I can more easily maintain my program in the future.

2.
If I make a mistake, Mata can tell me.

3.
Mata can produce more efficient code.

Concerning (2), Mata does not always mention. Mata never lets (2) get in the
way of (3).

So what can variables be?

The same as arguments;
anything but void.

Choose a word from column 1, and a word from column 2.

Top