Documente Academic
Documente Profesional
Documente Cultură
A. Introduction to Mathematica
After finding the next-to-last bug, clean up your debugging stuff. The last bug in any
piece of code is invariably found by the first user of the code and never by the programmer.
Roman Maeder, Programming in Mathematica I, pp. 43.
Mathematica used to be slow and memory-intensive. This might be the reason why so many
computer vision labs have not considered applying it to images. It is a pleasant 'discovery'
that Mathematica is now fast and efficient with memory.
As a concise quick reference guide, here are the most important things to know when you
want to get started with Mathematica:
Cells come in many styles, like 'title', 'text', 'input' etc. The front-end takes care of automatic
grouping of the cells (this, as any function, can be turned off).
By double-clicking on the group bracket a group of cells can be closed or opened, for quick
overview of the document.
Input style cells are sent to the kernel and executed by pressing 'shift-return'. Commands can
extend over several lines in an input type cell, separated by returns. Cells can be edited, and
run again. Mathematica remembers activities in the order of processing, not by the location
of the cell in the notebook.
The format menu item contains all commands for formatting text. The style sheets set the
definitions for appearances of elements for each cell type. We initialize every chapter with
the following commands. The first sets paths and options for often used functions, the second
contains the functions predefined for the book:
<< FrontEndVision`FEV`;
A. Introduction to Mathematica 396
Mathematica can do both symbolic and numerical calculations. It has arbitrary precision.
N[p,100] gives the numerical value of p in 100 significant digits, D[Log[x],x] gives
the first derivative of the natural logarithm of x .
N@p, 100D
3.1415926535897932384626433832795028841971693993751058209749445923078Ö
16406286208998628034825342117068
D@Log@xD, xD
1
ÅÅÅÅ
x
The internal structure of every expression is a Head in front of a list of operands. Check the
internal representation with FullForm:
Mathematica is strongly list oriented. Lists can be nested in any order. Every expression is a
list, as are our image data. Most commands are optimized for list operations.
Notation:
- Multiplication is indicated with a space or *.
- A semicolon ; at the end of a command means "Print no output". Useful when a lot of
textual output is expected. The semicolon ; is also the regular expression statement separator.
- Enter Greek letters with the escape key Ç before and after it: E.g.: Ç p Ç turns into p. Any
symbol can be entered through 'palettes' (see the File menu on the title bar of your
Mathematica session).
- Enter superscript with control-^, subscript with control-_, division line with
control-/, a square-root sign with control-2.
- Mathematica's internal variables and functions all begin with a capitalized letter, your own
defined variables should always begin with a lower case for clear distinction: Pi,
Plot3D[], myfunction[], {x,y,z}.
equivalent to N@2100 D.
- Often we use the 'postfix' form for the application of a function: 2 ^ 100 // N is
2 ^ 100 êê N
1.26765 µ 1030
397 A.1 Quick overview of using Mathematica
- Keeping the alt-key press while dragging the mouse gives smooth window scrolling.
- Help is available on any command.
The full 1400 page manual is online under the Help menu item.
There is a very useful 'getting started' section, and a 'tour of Mathematica'. Shortcut for help:
Highlight the text and press F1.
- Command completion is done with control-k, the list of arguments of a function with shift-
control-k.
- The notebook can be executed completely with the Kernel menu commands.
- All output can be deleted, which may save disk space considerably.
- A series of Graphics output can be animated by double-clicking one of the figures. The
bottombar of the window show steering controls for the animation.
- The input menus contains many interesting features, as 3D viewpoint selection, color
selection, hyperlinks, sound, tables and matrices, automatic numbering objects etc. and is
worth studying the features.
Plot commands come with many options. See available options in the Help browser or with
e.g. Options[Plot3D].
Mathematica shows every plot it creates immediately. The output of the plot commands is
controlled by the option DisplayFunction. It specifies the function to apply for displaying
graphics (or sound).
To prevent intermediate results, e.g. while preparing a series of plots to be shown with
GraphicsArray, a useful construct is to create a scoping construct with
Block[{vars} ... ]. Within a block, all variables vars are hidden from the main
global context. E.g. in the following example the setting for $DisplayFunction is
temporarily set in the block context to Identity, which means: no output.
A. Introduction to Mathematica 398
0.5
-0.5
-1
FullForm gives the internal representation, i.e. a Head with a series of operands:
FullForm@maD
Listable is an attribute of many functions. It means that they perform their action on all
elements of a list:
ma + 1
ma2
f =.; f3
f3
f =.; Nest@f, x, 3D
f@f@f@xDDD
With repeated operations (using Nest) a wide variety of self-similar structure can be
generated. From Stephen Wolfram's new book [Wolfram2002] the gasket fractal:
399 A.2 Quick overview of the most useful commands
Figure A.1 The gasket fractal is created by repeated action, which is implemented with the
function Nest. See also mathforum.org/advanced/robertd/typefrac.html.
Map@f, maD
You can specify the level in the list where the function should be mapped:
Map@f, ma, 2D
Apply replaces the head of an expression with a new head. This sums the columns:
Apply@Plus, maD
8a + d + g, b + e + h, c + f + i<
This sums the rows, i.e. Plus is applied at level 1 in the List:
8a + b + c, d + e + f, g + h + i<
Apply can even replace at level 0, i.e. the head itself. This sums all elements of a matrix:
a+b+c+d+e+f+g+h+i
Postfix //
8a d g, b e h, c2 f i<
In the following lines, the first statement rotates (cyclic) the elements one position to the
right, while the second rotates one position downward (rowshift down).
RotateRight êü ma
RotateRight@maD
Plus üü ma
8a + d + g, b + e + h, c + f + i<
ma êê MatrixForm
ia b c z
j y
j
j z
j
j d e fz
z
z
j z
kg h i {
Clear@a, b, c, d, e, f, gD; m2 = 888a, b<, 8c, d<<, 88e, f<, 8g, h<<<;
Map@RotateRight, m2, 80<D
Map@RotateRight, m2, 81<D
Map@RotateRight, m2, 82<D
i
j y
z
j
j z
z
j
j z
z
0.419066 0.685606 0.696535 0.470892
j z
k 0.0873124 0.818922 {
0.898048 0.0157444 0.0700894 0.44903
0.833205 0.0487981
401 A.3 Pure functions
f2
We use a pure function frequently when we have to apply a function repeatedly to different
arguments:
f êü 81, 4, 6<
f = windingnumber@#D &;
f@4D
windingnumber@4D
or when we want to plot something for a particular range of scales: (the pure function is now
'ListDensityPlot the output of gD at some scale for the scales 2, 3 and 6'):
im = Import@"mr256.gif"D@@1, 1DD;
We find palindromes (words that are the same when written in reverse order) and word
length statistics. The example is taken from one of the Wolfram Mathematica tutorials, see
library.wolfram.com.
We read the data with ReadList and check its size with Dimension. Note that we put a
; (semicolon) at the end of the next cell. This prevents the full text of the dictionary to be
printed as output to the screen, which is in this case a very useful feature!
8118617<
Take@data, 20D
We use the commands for counting the number of letters in a string, and to reverse a string:
StringLength@"FrontEndVision"D
14
StringReverse@"FrontEndVision"D
noisiVdnEtnorF
The following command selects those elements which are equal to its reverse, and are longer
then 2 letters. && denotes the logical And. Note the use of the pure function:
8adinida, aha, ama, ana, anna, bib, bob, boob, civic, dad, deed, deified,
deled, did, dud, eke, ene, ere, ese, esse, eve, ewe, eye, gag, gig, hah,
huh, kayak, kook, level, madam, malayalam, minim, mom, mum, nisin,
non, noon, nun, pap, peep, pep, pip, poop, pop, pup, radar, redder,
refer, reviver, rotator, rotor, sagas, sees, sexes, shahs, sis,
solos, sos, stats, succus, suus, tat, tenet, tit, tnt, toot, tot, wow<
45
Count[list, pattern] gives the number of elements in list that match pattern.
403 A.4 Pattern matching
Count@wordLengths, 10D
14888
80, 93, 754, 3027, 6110, 10083, 14424, 16624, 16551, 14888, 12008,
8873, 6113, 3820, 2323, 1235, 707, 413, 245, 135, 84, 50, 23,
16, 9, 4, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2<
occurrence
15000
12500
10000
7500
5000
2500
wordlength
10 20 30 40
Pattern matching is one of the most powerful techniques in Mathematica. There are three
symbols for a pattern: _ denotes anything which is a single element, __ denotes anything
which is one or more elements, ___ denotes anything which is zero, one or more elements.
è!!!
x_ denotes a pattern which is known under the name x. Replacement (/.) is by Rule
(Ø). The following statement replaces every occurrence of a into a :
è!!!!
f =.; ma ê. 9a -> a=
è!!!
88 a , b, c<, 8d, e, f<, 8g, h, i<<
This returns the positions in the dictionary where words are found of more then 23 letters:
This returns the first pair of two consecutive 13-letter words in the dictionary:
Dimensions@dataD
8118617<
A. Introduction to Mathematica 404
8abstentionism, abstentionist<
The surface is formed from a collection of quadrilaterals. The corners of the quadrilaterals
have coordinates corresponding to the values of the f i when t and u take on values in a
regular grid.
8x, -3, 3<, 8y, -3, 3<, 8z, -1, 1<, PlotPoints Ø 815, 15, 10<,
Passes Ø Automatic, ImageSize -> 200D;
Install@"binary.exe"D;
The taskbar in Windows at the bottom of the screen should now display the active program
binary.exe with which we now will communicate.
Let us read a file in raw bytes dataformat with a 3D MRI dataset. It is given that the set
mri_01.bin contains 166 slices with 146 rows (x-dimension) and 168 columns (y-
dimensions). Each pixel is stored as an unsigned byte. To read this file we first need to open
it:
channel = OpenReadBinary@
$FEVDirectory <> "Images\mri02.bin", FilenameConversion Ø IdentityD;
It is fastest to read the binary 3D image stack slice by slice. We first define space to store the
image, then we read 166 slices as bytes. Each slice is partitioned into 146 rows. At the end
we close the file.
A. Introduction to Mathematica 406
im = Table@8<, 8166<D;
Table@
8i, 1, 166<D;
im@@iDD = Partition@ReadListBinary@channel, Byte, 168 146D, 146D;,
Close@channelD;
Dimensions@imD
By calculating the Transpose of the 3D image, we can interchange the coordinates. The
second argument is the new ordering of the coordinates. In this way it is easy to plot the
other perpendicular planes. Let us look at the 85th image of the original stack, and the 85th
image of two transposed forms respectively, as shown in the statement below. As we see
from the left figure, the original slices were acquired in the coronal plane. The transposed
images show us the sagittal plane (middle, Latin 'sagitta' = arrow) and the transversal plane
(right). This method of transposing the data so we get other perpendicular planes is called
multiplanar reformatting.
Multiplanar reformatting is of course only of high quality if the voxels are isotropic. Note in
this example that slight differences in overall intensities in the original 3D MRI acquisition
show up as vertical lines.
By manipulation of the pointer StreamPosition we can read an arbitrary slice from the 3D
dataset. This pointer points at the position just preceding the next bytes to read. After
opening the file, the streamposition is set to zero, which is at the beginning of the data. By
setting the stream position pointer 84 images further (84*168*146 locations further from
zero), the next statement reads the 85th image only:
407 A.6 A faster way to read binary 3D data
By manipulation of the pointer StreamPosition we can read an arbitrary slice from the 3D
dataset. This pointer points at the position just preceding the next bytes to read. After
opening the file, the streamposition is set to zero, which is at the beginning of the data. By
setting the stream position pointer 84 images further (84*168*146 locations further from
zero), the next statement reads the 85th image only:
channel = OpenReadBinary@
$FEVDirectory <> "Images\mri02.bin", FilenameConversion Ø IdentityD;
SetStreamPosition@channel, 84 * 168 * 146D;
im85 = Partition@ReadListBinary@channel, Byte, 168 146D, 146D;
ListDensityPlot@im85, ImageSize -> 150D;
Figure A.7 Direct read of a single slice from a 3D dataset is best done by manipulation of the
stream position pointer.
Close@channelD;
When a function from a package is called before the package is actually read into the kernel,
Mathematica adds the name to its global list as soon as it appears:
Remove@HistogramD
Histogram
Histogram
The function does not work, because the package Graphics`Graphics` has not been
read.
When subsequently the package is read, Mathematica complains that it may overwrite a
previous definition, and does not redefine the function Histogram. The natural way out is
to Remove the first definition, and to read the package again.
A. Introduction to Mathematica 408
<< Graphics`Graphics`;
Remove@HistogramD;
<< Graphics`Graphics`;
? Histogram
univariate data 8x1, x2, ...<. The width of each bar is proportional
Histogram@8x1, x2, ...<D generates a bar graph representing a histogram of the
Prevent accidental output to the notebook if not necessary and very long, eg. when an image
is calculated.
Any output is not printed when the statement is concluded with a semicolon. The first
statement generates about a million random numbers to the screen, which will take a very
long time to generate and prevent you from continuing (luckily, we made the cell
inevaluatable). The second statement with the semicolon is fine.
Be careful with symbolic computations on larger datasets. You may only be interested in the
numerical result. Compare the examples below:
Even for this small matrix, each symbolic term is huge, and very impractical to handle. The
numerical result is very fast:
409 A.7 What often goes wrong
Timing@numericalInverse = Inverse@N@mm1DD;D
Short@numericalInverse, 4D
Another example: the numerical Eigenvalues of a matrix with 10,000 elements is computed
fast:
18.719 Second
The same result is acquired much faster if we use mathematical programming with native
Mathematica functions. They are optimized for speed, and programming becomes much
more elegant.
0.406 Second
Mathematica Navigator gives you a general introduction to the use of Mathematica, with
emphasis on graphics, methods of applied mathematics, and programming.
The book serves both as a tutorial and as a handbook. No previous experience with
Mathematica is assumed, but the book contains also advanced material and material not
easily found elsewhere. Valuable for both beginners and experienced users, it is a great
source of examples of code.
And for many subjects we also write our own programs, to practice programming.
- Do you emphasize symbolic or numerical methods?
- Both are important. For a given problem, we usually first try symbolic methods, and if they
fail, then we resort to numerical methods. Thus, for each topic, the book presents first
symbolic methods and then numerical methods. The book gives numerical methods a special
emphasis.
- Have you excluded some topics?
- Topics of a "pure" nature such as number theory, finite fields, quaternions, or graph theory
are not considered. Commands for manipulating strings, boxes, and notebooks are covered
only briefly. MathLink is left out (MathLink is a part of Mathematica enabling interaction
between Mathematica and external programs).
- Do you like to say something about the writing of the book?
- The writing was simply exciting. It is one of the most interesting epochs of my life thus far.
By writing the book I learned a lot about Mathematica and obtained a comprehensive view
of it. And the more I learned about Mathematica, the more I admired it.
- What are the fine aspects of Mathematica?
- It is consistent, reliable, and comprehensive. In addition, Mathematica has very powerful
commands, produces excellent graphics, and has a wonderful interface. However, it certainly
takes some time to get used to Mathematica, but that time is interesting and rewarding, and
then you have a powerful tool at your disposal.
- Thank you very much for this interview.
- Thank you.
The definite reference guide for Mathematica, written by the author of Mathematica,
Stephen Wolfram. Not a tutorial, but a handbook. The full text of this book is available in the
indexed help-browser of Mathematica, as well as a searchable document on the web:
documents.wolfram.com/v4/index3.html.
This revised and expanded edition of the standard reference on programming in Mathematica
addresses all the new features in the latest versions 3 and 4 of Mathematica.
The support for developing larger applications has been improved, and the book now
discusses the software engineering issues related to writing and using larger programs in
Mathematica. As before, Roman Mäder, one of the original authors of the Mathematica
system, explains how to take advantage of its powerful built-in programming language. It
includes many new programming techniques which will be indispensable for anyone
interested in high level Mathematica programming.
[Mäder1996b] R. Mäder, The Mathematica programmer II. Academic Press, 1996. 296
pages. ISBN 0-12-464992-0 (paperback). This book, which includes a CD-ROM, is a second
volume to follow The Mathematica Programmer (now out of print) and includes many new
programming techniques which will be indispensable for anyone interested in high level
Mathematica programming.
A. Introduction to Mathematica 412
[Mäder1996b] R. Mäder, The Mathematica programmer II. Academic Press, 1996. 296
pages. ISBN 0-12-464992-0 (paperback). This book, which includes a CD-ROM, is a second
volume to follow The Mathematica Programmer (now out of print) and includes many new
programming techniques which will be indispensable for anyone interested in high level
Mathematica programming.
www.wolfram.com: The official homepage of Wolfram Inc., the maker and distributor of
Mathematica. Here many links are available for support, add-on packages, books, the
complete Mathematica book on-line, WebMathematica, GridMathematica, etc.
There are many introductions to Mathematica and pages with helpful links. Here are some
examples: