\section{Warming up}

Before getting start, you should know how do enter and leave the
system.  To execute the Mx line-by-line interpreter, type:
\begin{quote}
\begin{verbatim}
OS% java MxMain
\end{verbatim}
\end{quote}
or you want to execute your program:
\begin{quote}
\begin{verbatim}
OS% java MxMain myprog.mx
\end{verbatim}
\end{quote}

Once you entered the Mx line-by-line mode, type (without ending ``;''):
\begin{quote}
\begin{verbatim}
Mx> exit
\end{verbatim}
\end{quote}
to return to the operating system.  Note that \texttt{exit} is not
permitted in your program, please use \texttt{return} to end your program.

Another useful function is \texttt{what()}.  You can use it to check
all or specified variables in the system, or specified variables.
\begin{quote}
\begin{verbatim}
Mx> a=2;
Mx> what();
<double>  3.141592653589793
<int>  a = 2
<double>  2.718281828459045
Mx> what(a);
<int>  a = 2
\end{verbatim}
\end{quote}

We can see $\pi$ and $e$ are pre-assigned.  You can use \texttt{PI} and
\texttt{E} to access them (note that Mx is case-sensitive):
\begin{quote}
\begin{verbatim}
Mx> print(PI);
3.141592653589793
\end{verbatim}
\end{quote}

Suppose you want to save a matrix
\[ \left[ \begin{array}{ll}
1 & 2 \\
3 & 4 
\end{array} \right] \]
to a variable, namely $A$, type:
\begin{quote}
\begin{verbatim}
Mx> A = [ 1, 2; 3, 4 ];
\end{verbatim}
\end{quote}
To print the matrix $A$, type:
\begin{quote}
\begin{verbatim}
Mx> print( A );
\end{verbatim}
\end{quote}
Then do some computations:
\begin{quote}
\begin{verbatim}
Mx> print( A * A );
\end{verbatim}
\end{quote}
It shows
\begin{quote}
\begin{verbatim}
A =
      7.0000 10.0000
     15.0000 22.0000
\end{verbatim}
\end{quote}

Let us define another matrix, say $B$:
\begin{quote}
\begin{verbatim}
Mx> B = [ 1, 2; 0, 1 ];
\end{verbatim}
\end{quote}
Then print the product $AB$ and $BA$ (note that they are different):
\begin{quote}
\begin{verbatim}
Mx> print( A * B );
      1.0000  4.0000
      3.0000 10.0000
Mx> print( B * A );
      7.0000 10.0000
      3.0000  4.0000
\end{verbatim}
\end{quote}
We can add two matrices together:
\begin{quote}
\begin{verbatim}
Mx> print( A + B );
      2.0000  4.0000
      3.0000  5.0000
\end{verbatim}
\end{quote}
The result can be saved to another variable:
\begin{quote}
\begin{verbatim}
Mx> S = A + B;
\end{verbatim}
\end{quote}

To invert a matrix, type
\begin{quote}
\begin{verbatim}
Mx> print( inv(S) );
     -2.5000  2.0000
      1.5000 -1.0000
\end{verbatim}
\end{quote}
or
\begin{quote}
\begin{verbatim}
Mx> print( 1/S );
     -2.5000  2.0000
      1.5000 -1.0000
\end{verbatim}
\end{quote}
To check its correctness, just compute the product:
\begin{quote}
\begin{verbatim}
Mx> print( S * inv(S) );
      1.0000  0.0000
      0.0000  1.0000
\end{verbatim}
\end{quote}
The result is an identity matrix, which can be generated by function
\texttt{eye(n)} (n is the dimension):
\begin{quote}
\begin{verbatim}
Mx> print( eye(3) );
      1.0000  0.0000  0.0000
      0.0000  1.0000  0.0000
      0.0000  0.0000  1.0000
\end{verbatim}
\end{quote}
There are two kinds of division of two matrices, say $A$ and $B$.  The
right-division, $A/B$, means $A*inv(B)$, and the left-division, $A/'B$,
means $inv(B)*A$.  $A/'B$ is also means to solve equation $BX=A$.
For example,
\begin{quote}
\begin{verbatim}
Mx> QR = A/B;
Mx> QL = A/'B;
Mx> print( QR );
QR =
      1.0000 -0.0000
      3.0000 -2.0000
Mx> print( QR * B );
      1.0000  2.0000
      3.0000  4.0000
Mx> print( QL );
QL =
     -5.0000 -6.0000
      3.0000  4.0000
Mx> print( B * QL );
      1.0000  2.0000
      3.0000  4.0000
\end{verbatim}
\end{quote}
We can see that the results agree.  You can also compute the
determinant of a matrix:
\begin{quote}
\begin{verbatim}
Mx> print( det(A) );
-2.0
\end{verbatim}
\end{quote}

\section{Matrix operations}

If you want to generate a large matrix, using ways like
\texttt{[1,2;3,4]} is too cumbersome.  Function \texttt{zeros(m,n)}
generates an $m\times n$ matrix with all entries zero:
\begin{quote}
\begin{verbatim}
Mx> print( zeros(2,3) );
      0.0000  0.0000  0.0000
      0.0000  0.0000  0.0000
\end{verbatim}
\end{quote}
Of course, you can use function \texttt{eye(n)} mentioned above. 
Sometimes you may want to generate a matrix with random numbers:
\begin{quote}
\begin{verbatim}
Mx> print( random(2,3) );
      0.2151  0.5153  0.0138
      0.0875  0.1132  0.8355
\end{verbatim}
\end{quote}
All random numbers are uniformly distributed between 0 and 1
(inclusive).  Another very useful matrix generator is
\texttt{indgen(m,n,s,dsm,dsn)}, which means {\em index generating}.
This function generates an $m\times n$ matrix with linear increment,
whose top-left entry $(0,0)$ is $s$, and $(1,0)$ is $s+dsm$, and
$(2,0)$ is $s+dsm*2$, and so forth.  Similarly, $(0,1)$ is $s+dsn$,
and $(0,2)$ is $s+dsn*2$, and so forth.  For example:
\begin{quote}
\begin{verbatim}
Mx> print( indgen(3,4,1,1,10) );
      1.0000 11.0000 21.0000 31.0000
      2.0000 12.0000 22.0000 32.0000
      3.0000 13.0000 23.0000 33.0000
\end{verbatim}
\end{quote}
You can use \texttt{indgen} to generate a matrix that contains a same
value other than zero:
\begin{quote}
\begin{verbatim}
Mx> print( indgen(2,3,5.7,0,0) );
      5.7000  5.7000  5.7000
      5.7000  5.7000  5.7000
\end{verbatim}
\end{quote}

Next important thing is to get an individual entry from a matrix.  In
Mx, the first row is indexed as 0, and the second row is 1, and so do
columns.  To get the second row and the fourth element from a matrix,
type:
\begin{quote}
\begin{verbatim}
Mx> C = [1,2,3,4,5;6,7,8,9,10;11,12,13,14,15];
Mx> print( C );
C =
      1.0000  2.0000  3.0000  4.0000  5.0000
      6.0000  7.0000  8.0000  9.0000 10.0000
     11.0000 12.0000 13.0000 14.0000 15.0000
Mx> print( C[1,3] );
      9.0000
\end{verbatim}
\end{quote}

If you want to get matrix entries with some consecutive rows and
consecutive columns, you can use \textsl{range}, two integers
separated by \texttt{:},
\begin{quote}
\begin{verbatim}
Mx> print( C[0:1,2:3]);
      3.0000  4.0000
      8.0000  9.0000
\end{verbatim}
\end{quote}

You can get a single row or column by
\begin{quote}
\begin{verbatim}
Mx> print( C[:,3] );
      4.0000
      9.0000
     14.0000
Mx> print( C[2,:] );
     11.0000 12.0000 13.0000 14.0000 15.0000
\end{verbatim}
\end{quote}

These operation are called \textsl{matrix slicing}.  Also, it is not
necessary to use only rectangular region: one can select matrix
entries by the results of comparing values of this matrix or other matrices
with the same size.  This operation is called \textsl{matrix masking}.
You can save to a variable of \textsl{matmask} type the information
about which elements are selected.  Figure \ref{fig:matop} illustrates
the operations of slicing and masking.

\begin{figure}[ht]
\begin{center}
\includegraphics[width=4in]{figs/matop.eps}
\caption{matrix slicing and masking\label{fig:matop}}
\end{center}
\end{figure}

We can set a matmask variable indicating those entries that
are greater than 2.5 and less than 7.5:

\begin{quote}
\begin{verbatim}
Mx> mask = C>2.5 and C<7.5;
\end{verbatim}
\end{quote}

and set these entries to zeros:
\begin{quote}
\begin{verbatim}
Mx> C[mask] = 0;
Mx> print( C );
C =
      1.0000  2.0000  0.0000  0.0000  0.0000
      0.0000  0.0000  8.0000  9.0000 10.0000
     11.0000 12.0000 13.0000 14.0000 15.0000
\end{verbatim}
\end{quote}

\section{Display your results}

\begin{figure}[ht]
\begin{center}
\includegraphics[width=2.8in]{figs/sin.eps}
\caption{plot of $\sin(x)$\label{fig:sin}}
\end{center}
\end{figure}

Let us begin to draw some graphs.  First example is to
draw a sinusoidal curve:
\begin{quote}
\begin{verbatim}
Mx> A = indgen(200,2,0,0.2,0);
Mx> A[:,1] = sin(A[:,0]);
Mx> plot(A);
\end{verbatim}
\end{quote}

The \texttt{plot(A);} will open a new window and draw the curve as in
Figure \ref{fig:sin}.  A more complicated example is to draw a 3-dimensional 
Lissajous trajectory:
\begin{quote}
\begin{verbatim}
Mx> B = zeros(200,3);
Mx> B[:,0] = sin(A[:,0]);
Mx> B[:,1] = sin(A[:,0]*1.2);
Mx> B[:,2] = sin(A[:,0]*1.4);
Mx> colormap(2);
Mx> plot(B);
\end{verbatim}
\end{quote}

\begin{figure}[hb]
\begin{center}
\includegraphics[width=2.8in]{figs/lissajous.eps}
\caption{3-d Lissajous trajectory.  The z-coordinate is represented by
changing colors.
\label{fig:lissajous}}
\end{center}
\end{figure}

The plot window is shown in Figure \ref{fig:lissajous}.  The $z$-coordinate
is represented by changing colors.  Finally, let us plot something

\begin{quote}
\begin{verbatim}
Mx> C = random(10,10);
Mx> colormap(1);
Mx> paint(C);
\end{verbatim}
\end{quote}

A 10 by 10 image is very small, but you can resize it as in Figure
\ref{fig:random}.

\begin{figure}
\begin{center}
\includegraphics[width=2in]{figs/random.eps}
\caption{painting a random matrix
\label{fig:random}}
\end{center}
\end{figure}

\section{Using program files}

When things cannot be done in several lines, you can edit a
program file.  Use any kind of text editor to create a program file
\texttt{myprog.mx} contains (don't type in line numbers):

\begin{quote}
\begin{verbatim}
1:  func grid( x, y ) {
2:      c = (x/25+y/25)%2;
3:      return c;
4:  }
5:  
6:  func distance( a, b ) = sqrt(
7:      (a-100)*(a-100)+(b-100)*(b-100));
8:
9:  A = zeros(200,200);
10:
11: for ( i = 0:199, j=0:199 ) {
12:     A[i,j] = grid( i, j );
13:     if ( distance(i,j) >= 60 )
14:         A[i,j] = 1-A[i,j];
15: }
16:
17: colormap(1);
18: paint(A);
\end{verbatim}
\end{quote}

\begin{figure}
\begin{center}
\includegraphics[width=2in]{figs/chess.eps}
\caption{circle in a chess board
\label{fig:chess}}
\end{center}
\end{figure}

This program draws a circle in a chess board. (Figure \ref{fig:chess})

Lines 1-4 define a function that determines if point $(x,y)$ is in
a black or white square.  You can define functions at the beginning of the
program.  A function definition always starts with the keyword
\texttt{func}.  (Several keywords are used in this language, explained
in the next chapter, Language Reference Manual.) Function identifier
follows the func keyword.  Identifier can consist of one or more
alphanumeric characters.  Following the identifier is the variable or
argument list enclosed by parenthesis.  It can consist of zero or more
identifiers.  The function body can contain an expression led by an
assignment ($=$), or a group of statements enclosed in \{ \}.

Lines 6-7 define a function that calculate the distance between $(a,b)$
and the center of the board, $(100,100)$.

Line 9 initializes a 100 by 100 matrix.  Then in line 11-15, we use a
for loop to do the same operations for all points.  This is similar to the
\textsl{for/do} loop in many other programming languages.  The difference is
that Mx have a range type to specify the range of iteration.  

Line 12 is an example of calling a function.  The return value of
a function can be assigned to a variable, or a matrix entry.

Line 13 uses the \textsl{if} conditional statement to check whether a
point $(a,b)$ is inside the circle.  There are two types of
conditional statements, \textsl{if} and \textsl{if-else}.  The uses of
these are exactly the same as C and Java.  Keyword \texttt{if} is
followed by a logical or relational expression.  The relational
expression compares two numbers by operators $<$, $>$, $==$, $!=$,
$<=$, or $>=$.  A logical expression can be a boolean expression of
two or more relational expressions, using keywords
\texttt{and}, \texttt{or}, and \texttt{not} as operators.

The last two lines select the black-white colormap and draw the
matrix as an image.  The picture is shown in Figure \ref{fig:chess}


\section{Example: Lorenz equations}

We now begin to show some complicated examples.  The first example is
the Lorenz equations.  The Lorenz equations were discovered in 1963 by
Edward Lorenz, a meteorologist at MIT, when he and other mathematicians
did research in the modeling of convection that takes place in the
atmosphere.  They presented a model with three equations, which is now
the famous Lorenz equations:
\begin{eqnarray*}
\frac{dy_0}{dt} &=& \alpha(y_1-y_0) \\
\frac{dy_1}{dt} &=& y_0(r-y_2) - y_1 \\
\frac{dy_2}{dt} &=& y_0y_1 - by_2
\end{eqnarray*}
Given an initial condition, they found the system state (three
variables) will not go to infinity, and it is not convergent, either.
A small fluctuation will cause large difference in the future, which
might be the reason that the weather is not predictable in a long
term.  This phenomenon is called chaos.

To simulate such an system, we need a good algorithm to solve
differential equations numerically.  The most popular, good and simple
algorithm is the fourth-order Runge-Kutta algorithm.  Given the
parameters and initial conditions that $\alpha=10$, $r=28$, $b=8/3$,
and $x(0)=10$, $y(0)=0$, $z(0)=10$, now we code both Runge-Kutta
algorithm and Lorenz equations in Mx:

\begin{quote}
\verbatiminput{test/lorenz.mx}
\end{quote}

The important features in Mx used in this program include vector
operations, function variables, and plotting.  Figure \ref{fig:lorenz}
shows what the program generates.

\begin{figure}[h]
\begin{center}
\includegraphics[width=3in]{figs/lorenz.eps}
\caption{plot of a solution of Lorenz equations.  Parameters are
$\alpha=10$, $r=28$, $b=8/3$, and the initial condition is
$(10,0,10)$.   The $z$ coordinates are represented in color.
\label{fig:lorenz}}
\end{center}
\end{figure}

\section{Example: fractals}

Let us draw some pictures of fractals.  This example draws the
Sierpinski triangle, which is generated by removing
the lower-right quarter from the square and recurring on rest
quarters with the same action:

\begin{figure}[h]
\begin{center}
\includegraphics[width=2in]{figs/sierpinski.eps}
\caption{the Sierpinski triangle
\label{fig:sierpinski}}
\end{center}
\end{figure}

\begin{quote}
\verbatiminput{test/sierpinski.mx}
\end{quote}

The important features used in the program include matrix slicing,
recursion and painting.  Figure \ref{fig:sierpinski} shows the result.

The second example is to draw another important and famous fractal
image: the Mandelbrot set.  The value of each point is generated by
the speed of divergence of $Z$ by this recursive formula
\[ Z^{(i+1)} = (Z^{(i)})^2 + Z^{(0)}, \]
where $Z^{(0)}$ is the coordinates of the point, represented by
a complex number.

The important features of Mx programming language used here are internal
functions, matrix masking, and painting over an existing image.
Figure \ref{fig:mandelbrot} shows what the program draws.

\begin{figure}\begin{center}
\includegraphics[width=2in]{figs/mandelbrot.eps}
\caption{the Mandelbrot set.  The range of x-axis is $[-2.1,0.9]$
and the range of y-axis is $[-1.5,1.5]$.
\label{fig:mandelbrot}}
\end{center}\end{figure}

\begin{quote}
\verbatiminput{test/mandelbrot.mx}
\end{quote}

\section{Example: image processing}

These examples are going to show that Mx programming language can
be used to do some basic image processing.

The first example (Figure \ref{fig:potato}) shows the eight
orientations of Mr. Potato Head (geometric transformation):

\begin{quote}
\verbatiminput{test/potato.mx}
\end{quote}

\begin{figure}[h]
\begin{center}
\includegraphics[width=3in]{figs/potato.eps}
\caption{global geometric image transformation
\label{fig:potato}}
\end{center}
\end{figure}

The second example (Figure \ref{fig:lenna}) shows effects of various
local geometric operations:

\begin{figure}[h]
\begin{center}
\includegraphics[width=3in]{figs/lenna.eps}
\caption{local geometric operations
\label{fig:lenna}}
\end{center}
\end{figure}

\begin{quote}
\verbatiminput{test/lenna.mx}
\end{quote}

The third example (Figure \ref{fig:fmri}) shows the brain activation
of one of our authors: his corresponding brain regions of sequential finger
tapping movement.  The data was acquired on a magnetic resonance imaging (MRI)
scanner.

\begin{figure}\begin{center}
\includegraphics[width=2in]{figs/fmri.eps}
\caption{Brain activation map of finger tapping, overlaid on a
anatomical image.  Data was sampled by functional MRI (fMRI)
techniques and pre-processed with cross-correlation (CC) algorithm
(pre-processed elsewhere). 
\label{fig:fmri}}
\end{center}\end{figure}

\begin{quote}
\verbatiminput{test/fmri.mx}
\end{quote}



