Matlab Introduction
Matlab (which really should be typed in all capitals: MATLAB) is
a high-level, interactive system for scientific computing.
Matlab started out as a simple interface to the original Linpack
library of linear system solvers, created by Cleve Moler so
that students could quickly tie together routines in the library
without spending a lot of time writing drivers.
The basic data type is a 2D array, explaining the name
MATrix LABoratory. Moler has claimed only
half-jokingly that the matrix is the mother of all data structures,
and with version 5.0 the language now includes structures and
"cell arrays": arrays where the entries can be anything else.
The current version of MATLAB is 6.0.
Matlab and PSEs
Matlab is used throughout scientific computing because
- it has quickly-learned, easily-used graphics capabilities
- it constitutes a very high level language for matrix and
vector operations, which in turn constitute the most
commonly used kernels in computational methods
- it encourages vector thinking, a precept for high performance
computing
- it can be used interactively, allowing rapid experimentation
and playing with ideas
- it interfaces with C/C++ and Fortran, the two languages accounting
for the vast majority of scientific code (a Java interface is
also standard).
- it presents a different "face" (user interface) for different
applications areas
- it simultaneouly allows hiding of unnecessary algorithmic and
architectural details, and allows a user to "dive in" and
alter those details if desired.
These features make Matlab the prototypical problem-solving
environment (PSE).
PSEs are software systems which provide the complete facilities
for solving application problems from a particular domain. A familiar
example of a PSE is Microsoft Word - a PSE for document preparation.
A user need not be aware of algorithms for line-breaking in Word, but
can override those to put a line break where desired. The toolbar in
Word presents a high-level, application-specific interface. It can
be used interactively, so that a user can see effects of changes
immediately (depending on document size, immediate could be
several minutes!) And Word provides the facilities for the full range
of activities of document preparation ranging from text entry to
printing.
Another term commonly used for systems like Matlab is "rapid prototyping
environment", which was its primary use originally. You could use
Matlab to test algorithms and ideas quickly and easily; when you got
one that worked, you would then implement it in a "real" language
like Fortran or C. However, Matlab has evolved in efficiency and
ability to interact with the outside world to the point where many
scientists and engineers carry out all their work within Matlab.
More specific Matlab features include
- The basic object is a rectangular array of double precision
complex entries.
- Numerically reliable matrix calculations: unlike computer
algebra systems for which numerical computations are an
afterthought, Matlab has always concentrated on reliable
numerics.
- Multilevel usage:
- Interactive usage for beginners and quick changes
in programs.
- Programmable by means of "M-files": Matlab programs
and functions
- Interface capabilities with C and Fortran, allowing
Matlab to be called as an "engine" or to invoke C and
Fortran functions.
- Multilevel graphics capabilities; simple usage to OO programming.
- High level matrix computations: s = eig(A) computes the
eigenvalues of a square matrix A.
- Large user community supplying programs, help.
- Sophisticated Fortran90 like indexing for submatrices, permutations.
Beware, however the subtle differences between Matlab indexing
and Fortran90 indexing.
- Automatic use of complex numbers when appropriate.
- Matrix and vector indices must be positive: x(0) not allowed. However,
empty matrices are allowed: A = ones(0,4) creates an example.
- Symbolic algebra computations provided via an interface to
a Maple kernel.
- Matlab is a commercial product, which means implementation details
are hidden (bad for researchers), but professional support is
available (good for everybody).
- Primarily interpreted language with some precompilation.
Using Matlab
You start up Matlab on a Unix system with the command "matlab" at
the Unix prompt. A header will be displayed, and if you have
graphics capabilities set up correctly a "splash window" showing
a nifty Matlab 3D graph will show briefly. This will occur on
the IU Nations or Ships cluster machines if you are logged in on the console
of one of those machines in the Geology or Student Building. To logon remotely
to one of those from a Unix-based machine that does not have Matlab,
type "ssh nations" and follow the login procedure. You will
automatically be logged in on whichever Nations machine has lightest
load. Be sure that you are using ssh version 2 from your console
machine; that is what UITS is running currently. You should also use
ssh-agent, so that graphic windows can be displayed back on your
local computer.
In Matlab version 6.0, Matlab's interface is run using Java and
a Swing window. That means it is slow, especially over a network.
In that case you probably would want to start it up in console mode:
matlab -nojvm -nosplash
Vectors in Matlab
We will start out dealing with vectors,
since those are what Matlab's plotting routines use. Consider the
problem of generating a 2D plot of n ordered pairs
(xi,yi). In Matlab,
the way to think of this is
plotting a vector y of length n against a
vector x of length n, where
x = (x1, x2, ... , xn)
y = (y1, y2, ... , yn)
NOTE that the indexing starts from 1, as it does in
every field of endeavor except computer science!
C/C++ programmers beware of this ... you can complain, but
the fields of mathematics and applications science (with
several centuries of development and existence) strangely
enough expect computer science (with only a few years of existence)
to adapt to 1-based indexing. The rudeness of this is
shocking to a C programmer, but we live in an incivil world.
We can type in a vector x via:
>> x = [1.0 2.1718 3.141 -17]
and Matlab comes back with
>> x =
1.0000 2.1718 3.1410 -17.0000
>>
By default, Matlab echos the result of every assignment.
You can supress this by appending a semicolon:
>> x = [1.0 2.1718 3.141 -17];
to which Matlab's snappy comeback is:
>>
If you want to index into x, you must use round parentheses
instead of square brackets. So the last element of x is
accessed as
>> x(4)
and not as x[4]. Note again that the indexing is 1-based,
not 0-based. What happens if you type x[4], by the way?
Now the vector x is set up as a row vector (a 1x4 vector).
If we had wanted it to be a column vector instead, we could
use the other role of a semicolon in Matlab:
>> x = [1.0; 2.1718; 3.141; -17];
which creates a 4x1 vector. Four points arise now:
- If you screwed up and got the wrong orientation for the
vector, you can save some typing by using the transpose
operator:
>> x = x'
which flips x from one to the other. More generally, if A is
an mxn array, A' is the nxm transposed array whose (i,j) component
is the (j,i) component of A.
- Suppose you don't know if you got it right or not. Here is
the first and most important debugging command in Matlab: whos.
This returns a listing of all variables currently in your
workspace, along with their sizes as arrays and in memory usage.
Try it!
- Which is more natural, row or column vectors? The answer is
"yes". However, in linear algebra you often talk about
solving the system Ax = b, where A is an nxn matrix and b is
a given vector. So what orientation do x and b necessarily have?
- Matrices and vectors are mathematical entities,
while arrays are computer storage entities. This is a
critical distinction which we often blur. Matlab helps blur
the distinction even further, since storage is automatically
allocated and resized on demand. Note that we simply set
the values of the vector x - nowhere did we declare its size
or type.
Plotting in Matlab
Now we get to plotting. All of my life I have wondered what the
inverse hyperbolic cosine function looks like, and
>> x = [1 2 3 4 5 6 7 8 9 10];
>> y = acosh(x);
>> plot(x,y);
fairly well fulfills my life's dream. Note that "acosh" is a built-in
math function in Matlab .... the interesting thing here is that it
works on a vector as well as a scalar, applying the acosh() function
componentwise. In fact, you can apply just about any scalar
function like square root to a matrix,
where it operates component-by-component.
Mathematically adept students are aware that there is also a
square root function for matrices, which gives something
different from component-wise square root. In Matlab,
matrix
functions (as opposed to scalar functions applied componentwise
to a matrix) are typically given with a postpended "m": sqrtm()
instead of sqrt().
The plot function creates a graphics window and
plots the vector y against x, drawing a line from one
(xi,yi) pair to the next.
In general, the plot() function is much more powerful than what
is shown above. For example, we can
- Set a color for the line: plot(x,y,'g')
- Explicitly plot just the points, with a specified marker
type: plot(x,y,'r*')
- Plot both the line and the points: plot(x,y,'g',x,y,'r*')
- Plot two different functions on the same axes: z = cosh(x); plot(x,y,x,z).
[Note: Matlab uses the term "axes" where you would normally say
"plot", so this bullet means the two functions are in the same plot.]
A title, x-axis label, and y-axis label can be added using
title(), xlabel(), and ylabel(), resp.
In a plot command like plot(x,y),
omitting the x will cause the elements of y to be plotted against
their index number. When y is a matrix, each column is plotted in
this manner, giving c curves when y has c columns.
A Matlab Gotcha
Note that I plotted
the acosh() function on the interval [1,10]. We could try the
same for the interval [-10,10] via
>> x = [-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10];
>> y = acosh(x);
>> plot(x,y);
But now a warning gets issued: complex components ignored in plot.
This is because acosh() is not defined for negative values. Matlab
will automatically switch to complex variables whenever
it is "appropriate". So if you take the square root of -17,
Matlab won't blink ... and if you meant to stay in the realm of real
numbers, you had better check arguments yourself in your
Matlab programs.
Revised: Mon Oct 7 16:22:07 EST 2002, updates about Matlab 6.0
Revised: Wed Feb 2 09:05:37 EST 2005, because of some changes in
array handling in Matlab 7.0