18
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 is an ful ly in tegrate d env ir on me nt fo r tec hn ic al co mp ut in g. It ha s be en de ve lo pe d by pr of . Ste ph en Wo lf ram and is now bei ng dev elo pe d and dis tr ib ut ed by Wolf ram Rese arch Inc.  Mathematica comes with an exce llen t on-bo ard help facil ity, whic h includes the full text of the handbook (over 1400 pages).  Mathematica used to be slow and memory-intensive. This might be the reaso n why so many comput er vis ion lab s hav e not con sidere d app lyi ng it to ima ges. It is a ple asa nt 'di sco ver y' that Mathematica is now fast and efficient with memory. As a concis e qui ck reference gui de, here ar e the most imp ortant thi ngs to know whe n you want to get started with Mathematica: A.1 Quick overview of using Mathematica Ma the matica con sis ts ess ent ial ly of two pro grams, that communica te wit h eac h other: the kernel fo r the ca lcul at ions and the  front-end for the graphi ca l user -i nt er face (i nput and pr esenta ti on of da ta ). The fr ont- end is an advanc ed text pr ocessor. It cr ea te s notebooks, porta ble documents that consis ts of cells , indica ted by the brack ets to the right of the ce ll. The front-end and kernel together form an interactive interpreter. Cell s come in many styles, like 'title', 'text', 'input ' etc. The front-en d take s care of automati c grouping of the cells (this, as any function, can be turned off). By double-c licking 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 exec uted by pres sing 'shift-r eturn '. Comma nds can exte nd over seve ral lines in an input type cell , separate d by returns . Cells can be edited, and run agai n.  Mathematica reme mber s acti vities in the orde r of processi ng, not by the locati on of the cell in the notebook. The format men u ite m contai ns all command s for for mat ting text. The style she ets set the defi nitio ns for appeara nces of elements for each cell type. We initi aliz e ever y chapt er 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`; 395 A.1 Quick overview of using Mathematica

90 Appendix a - Introduction to Ma Thematic A

Embed Size (px)

Citation preview

Page 1: 90 Appendix a - Introduction to Ma Thematic A

8/8/2019 90 Appendix a - Introduction to Ma Thematic A

http://slidepdf.com/reader/full/90-appendix-a-introduction-to-ma-thematic-a 1/18

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 is an fully integrated environment for technical computing. It has been

developed by prof. Stephen Wolfram and is now being developed and distributed by

Wolfram Research Inc. Mathematica comes with an excellent on-board help facility, which

includes the full text of the handbook (over 1400 pages).

 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:

A.1 Quick overview of using Mathematica

Mathematica consists essentially of two programs, that communicate with each other: the

kernel  for the calculations and the  front-end  for the graphical user-interface (input andpresentation of data). The front-end is an advanced text processor. It creates notebooks,

portable documents that consists of  cells, indicated by the brackets to the right of the cell.

The front-end and kernel together form an interactive interpreter.

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`;

395 A.1 Quick overview of using Mathematica

Page 2: 90 Appendix a - Introduction to Ma Thematic A

8/8/2019 90 Appendix a - Introduction to Ma Thematic A

http://slidepdf.com/reader/full/90-appendix-a-introduction-to-ma-thematic-a 2/18

 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, xD1ÅÅÅÅx

Use of brackets in Mathematica:

{ } List Example: {x,y,z}

[ ] Function Example: HermiteH[n,x]( ) Combine Example: Hx + 3L2(*...*) Comment Example: (* This function .. *)

The internal structure of every expression is a Head in front of a list of operands. Check the

internal representation with FullForm :

FullForm @81, 2, a b, c2, 8p, q<<D

List@1, 2, Times@a, bD, Power@c, 2D, List@p, qDD

 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}.

- Often we use the 'postfix' form for the application of a function: 2 ^ 100 // N is

equivalent to N @2 D .

2 ̂ 100 êê N

1.26765 µ1030

 A. Introduction to Mathematica 396  

Page 3: 90 Appendix a - Introduction to Ma Thematic A

8/8/2019 90 Appendix a - Introduction to Ma Thematic A

http://slidepdf.com/reader/full/90-appendix-a-introduction-to-ma-thematic-a 3/18

Some front-end tips:

- The menu item Format - Show Toolbar gives a handy toolbar below the title bar of your

window.

- 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.

A.2 Quick overview of the most useful commands

The commands below occur often in this book. Full explanation and many examples are

given in the Help browser of  Mathematica. For the sake of the readers that do not have

 Mathematica running, available or at hand while reading this book, some short examples are

given of the actions of the commands.

Plot commands come with many options. See available options in the Help browser or with

e.g. Options[Plot3D].

Plot, Plot3D, ContourPlot, ListPlot, ListDensityPlot

 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.

397 A.1 Quick overview of using Mathematica

Page 4: 90 Appendix a - Introduction to Ma Thematic A

8/8/2019 90 Appendix a - Introduction to Ma Thematic A

http://slidepdf.com/reader/full/90-appendix-a-introduction-to-ma-thematic-a 4/18

Block@8$DisplayFunction = Identity<,p1 = Plot@Sin@xD, 8x, 0, 6 p <D;p2 = Plot3D@Sin@xD Cos@yD, 8x, 0, 2 p <, 8y, 0, 2 p <DD;

Show 

@GraphicsArray

@8p1, p2

<DD;

2.5 5 7.5 10 12.5 15 17.5

-1

-0.5

0.5

1

 Mathematica is List oriented. This is a short nested List:

 ma=

88a, b, c<, 8d, e, f<, 8g, h, i<<88a, b, c<, 8d, e, f<, 8g, h, i<<

FullForm gives the internal representation, i.e. a Head with a series of operands:

FullForm @ maD

List@List@a, b, cD, List@d, e, fD, List@g, h, iDD

Listable is an attribute of many functions. It means that they perform their action on all

elements of a list:

 ma + 1

881 + a, 1 + b, 1 + c<, 81 + d, 1 + e, 1 + f<, 81 + g, 1 + h, 1 + i<<

 ma2

88a2 , b2 , c2<, 8d2 , e2 , f2<, 8g2 , h2 , i2<<

Clear[x] or f[x]=. clears f[x]. Remove[f] completely removes the symbol f.

f =.; f3

f3

 Nest applies a function multiple times.

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:

 A. Introduction to Mathematica 398

Page 5: 90 Appendix a - Introduction to Ma Thematic A

8/8/2019 90 Appendix a - Introduction to Ma Thematic A

http://slidepdf.com/reader/full/90-appendix-a-introduction-to-ma-thematic-a 5/18

Nest@SubsuperscriptBox@#, #, #D &, "W", 5D êê DisplayForm 

WW

W

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWWWWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

WWW

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.

ap maps a function on the elements of a list:

 Map@f, maD

8f@8a, b, c<D, f@8d, e, f<D, f@8g, h, i<D<

You can specify the level in the list where the function should be mapped:

 Map@f, ma, 2D

8f@8f@aD, f@bD, f@cD<D, f@8f@dD, f@eD, f@fD<D, f@8f@gD, f@hD, f@iD<D<

 Map@f, ma, 82<D

88f@aD, f@bD, f@cD<, 8f@dD, f@eD, f@fD<, 8f@gD, f@hD, f@iD<<

 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:

 Apply@Plus, ma, 81<D

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:

 Apply@Plus, ma, 80, 1<D

a + b + c + d + e + f + g + h + i

Some often used commands have short notations:

  Apply @@

ap /@

399 A.2 Quick overview of the most useful commands

Page 6: 90 Appendix a - Introduction to Ma Thematic A

8/8/2019 90 Appendix a - Introduction to Ma Thematic A

http://slidepdf.com/reader/full/90-appendix-a-introduction-to-ma-thematic-a 6/18

 

Replace /.

Condition /;

Postfix //

Timesüü ma ê. 8c -> c2<

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

88c, a, b<, 8f, d, e<, 8i, g, h<<

RotateRight@ maD88g, h, i<, 8a, b, c<, 8d, e, f<<

Plus üü ma

8a + d + g, b + e + h, c + f + i<

 ma êê MatrixForm 

i

k

jjjjjjj

a b c

d e f

g h i

y

{

zzzzzzz

To execute a function on every dimension of a multidimensional array (e.g. 2D the columns

and the rows), use the function Map[f,data,level] with indication of the level of 

mapping. Here is an example for an operation on a 3D array, for the z, y and x direction:

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

888e, f<, 8g, h<<, 88a, b<, 8c, d<<<

888c, d<, 8a, b<<, 88g, h<, 8e, f<<<

888b, a<, 8d, c<<, 88f, e<, 8h, g<<<

Table generates lists of any dimension, e.g. vectors, matrices, tensors:

rt = Table@Random @D, 8i, 1, 3<, 8j, 1, 4<D; rt êê MatrixForm 

i

k

jjjjjjj

0.419066 0.685606 0.696535 0.470892

0.898048 0.0157444 0.0700894 0.44903

0.0873124 0.818922 0.833205 0.0487981

y

{

zzzzzzz

 A. Introduction to Mathematica 400

Page 7: 90 Appendix a - Introduction to Ma Thematic A

8/8/2019 90 Appendix a - Introduction to Ma Thematic A

http://slidepdf.com/reader/full/90-appendix-a-introduction-to-ma-thematic-a 7/18

A.3 Pure functions

An operator is a 'pure function', e.g.

H#2

L& is a function without name, where some

operation on the operand # is performed, in this case squaring the variable. So H#2L &means: 'square the argument'. Multiple variables are indicated with #1, #2 etc.

H#2L & @fD

f2

p = HSin@#1 + #2D + Sqrt@#2DL &;

p@f, gDè!!!

g + Sin@f + gD

We use a pure function frequently when we have to apply a function repeatedly to different

arguments:

f = windingnumber@#D &;

f êü 81, 4, 6<

8 windingnumber@1D, windingnumber@4D, windingnumber@6D<

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;DisplayTogetherArray@ListDensityPlot@gD@im, 1, 0, #DD & êü 82, 3, 6<, ImageSize Ø 410D;

Figure A.2 Use of the function Map (/@).

A.4 Pattern matching

To show the usefulness of pure functions and the technique of pattern matching we work out

an example in some more detail: We do manipulations on words of a complete English

dictionary, consisting of 118617 English words.

401 A.3 Pure functions

Page 8: 90 Appendix a - Introduction to Ma Thematic A

8/8/2019 90 Appendix a - Introduction to Ma Thematic A

http://slidepdf.com/reader/full/90-appendix-a-introduction-to-ma-thematic-a 8/18

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!

data = ReadList@"dictionary118617.txt", StringD;Dimensions@dataD

8118617<

These are the first 20 elements:

Take@data, 20D8aardvark, aardvarks, aaronic, abaca, abaci, aback, abacterial, abacus,

abacuses, abaft, abalienate, abalienated, abalienating, abalienation,

abalone, abalones, abandon, abandoned, abandonedly, abandonee<

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:

Select@data, H# == StringReverse@#D && StringLength@#D > 2L &D

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<

To calculate the length of each word, we map StringLength on data:

 wordLengths = Map@StringLength, dataD; Max@ wordLengthsD

45

 Count[list, pattern] gives the number of elements in list that match pattern.

 A. Introduction to Mathematica 402

Page 9: 90 Appendix a - Introduction to Ma Thematic A

8/8/2019 90 Appendix a - Introduction to Ma Thematic A

http://slidepdf.com/reader/full/90-appendix-a-introduction-to-ma-thematic-a 9/18

Count@ wordLengths, 10 D

14888

t = Table@Count@ wordLengths, iD, 8i, 1, Max@ wordLengthsD<D

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<

ListPlot@t, PlotStyle Ø [email protected], AxesLabel -> 8"wordlength", "occurrence"<,PlotJoined -> False, ImageSize -> 230D;

10 20 30 40wordlength

2500

5000

7500

10000

12500

15000

occurrence

Figure A.3 Histogram of word lengths in a large English dictionary.

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:

Position@data, x_ ê; StringLength@xD > 23D

885028<, 817833<, 833114<, 833134<, 835841<, 849683<, 850319<,

857204<, 857205<, 860016<, 862133<, 862598<, 862599<, 863552<,863723<, 863724<, 863725<, 867140<, 867141<, 870656<, 874099<,

874101<, 874103<, 874166<, 879229<, 879273<, 879274<, 879500<,

883241<, 8104039<, 8105810<, 8106774<, 8113411<, 8114511<<

This returns the first pair of two consecutive 13-letter words in the dictionary:

Dimensions@dataD

8118617<

403 A.4 Pattern matching

Page 10: 90 Appendix a - Introduction to Ma Thematic A

8/8/2019 90 Appendix a - Introduction to Ma Thematic A

http://slidepdf.com/reader/full/90-appendix-a-introduction-to-ma-thematic-a 10/18

data ê. 8a___, b_ ê; StringLength@bD == 13,

c_ ê; StringLength@cD == 13, d___ < -> 8b, c<

8abstentionism, abstentionist<

A.5 Some special plot forms

ParametricPlot3D[{fx,fy,fz},{t,tmin,tmax},{u,umin,umax}] creates a

surface, rather than a curve.

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.

r

@u_ 

D:= -1 + E

uÅÅÅÅÅÅÅ6 p  ; x = 2 r

@u

D Cos

@u

D Cos

A

vÅÅÅÅ

2 E

2

;

y = 2 r@uD CosA vÅÅÅÅ

2E2

 Sin@uD; z = -1

ÅÅÅÅÅÅÅÅÅÅè!!!!2

 r@2 uD + r@uD Sin@vD;

shell = ParametricPlot3D@8x, y, z<, 8u, 0, 6 Pi<, 8v, 0, 2Pi<,PlotPoints Ø 8100, 40<, PlotRange Ø All, Axes Ø False, Boxed Ø False,

ViewPoint -> 82.581, 1.657, 0.713<, ImageSize -> 200D;

Figure A.4 An example of ParametricPlot3D for the plotting of more complicated 3D

manifolds.

 A. Introduction to Mathematica 404

Page 11: 90 Appendix a - Introduction to Ma Thematic A

8/8/2019 90 Appendix a - Introduction to Ma Thematic A

http://slidepdf.com/reader/full/90-appendix-a-introduction-to-ma-thematic-a 11/18

Clear@x, y, zD; << FrontEndVision`ImplicitPlot3D`;

torus = ImplicitPlot3D@z^2 ã 1 - H2 - Sqrt@x^2 + y^2DL^2,8x, -3, 3<, 8y, -3, 3<, 8z, -1, 1<, PlotPoints Ø 815, 15, 10<,Passes Ø Automatic, ImageSize -> 200

D;

Figure A.5 An example of ImplicitPlot3D for the plotting of more complicated 3Dmanifolds.

A.6 A faster way to read binary 3D data

 Mathematica has a set of utilities to read and write binary data from and to files. Examples of 

such commands are ReadBinary[...] and WriteBinary[...] . They are available

in the package Utilities`BinaryFiles` (see the help browser). These commands

however are slow.

A faster way is to use an external C program to read the data, and to communicate with this

program with MathLink . The program binary.exe (for Windows) is an executable C-program

that contains all commands of the package BinaryFiles` in a fast version. Thisexecutable is available from MathSource at the URL:

www.mathsource.com/Content/Enhancements/MathLink/0206-783.

Here also versions for other platforms are available. It is beyond the scope of this book to

explain  MathLink , but in the help browser and at the  MathSource repository good manuals

are available. The package is installed by Install:

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.

405 A.5 Some special plot forms

Page 12: 90 Appendix a - Introduction to Ma Thematic A

8/8/2019 90 Appendix a - Introduction to Ma Thematic A

http://slidepdf.com/reader/full/90-appendix-a-introduction-to-ma-thematic-a 12/18

im = Table@8<, 8166<D;Table@im @@iDD = Partition@ReadListBinary@channel, Byte, 168 146D, 146D;,

8i, 1, 166

<D;

Close@channelD;

We check for the dimensions of our 3D image, about 4 million pixels:

Dimensions@im D

8166, 168, 146<

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.

DisplayTogetherArray@ListDensityPlot êü 8im @@85DD, Transpose@im, 83, 2, 1<D@@85DD,Transpose@im, 83, 1, 2<D@@85DD<, ImageSize Ø 500D;

Figure A.6 Multiplanar reformatting  is the visualization of perpendicular images in a 3D

dataset by transposing the 3D dataset. The left image is one of the original acquisitions in

the coronal plane. The middle image shows the 85th image in the sagittal plane. It is formed

by showing all rows of pixels perpendicular to the pixels in the 85th column in the left image.

The right image shows the 85th image in the transversal plane. It is formed by showing all

rows of pixels perpendicular to the pixels in the 85th row in the left image.

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

 

 A. Introduction to Mathematica 406  

Page 13: 90 Appendix a - Introduction to Ma Thematic A

8/8/2019 90 Appendix a - Introduction to Ma Thematic A

http://slidepdf.com/reader/full/90-appendix-a-introduction-to-ma-thematic-a 13/18

 

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;

A.7 What often goes wrong

In this section we give a random set of traps in which you may easily fall if not warned:

A7.1 Repeated definition

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@Histogram D

Histogram 

Histogram 

The function does not work, because the package Graphics`Graphics` has not beenread.

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.

407 A.6 A faster way to read binary 3D data

Page 14: 90 Appendix a - Introduction to Ma Thematic A

8/8/2019 90 Appendix a - Introduction to Ma Thematic A

http://slidepdf.com/reader/full/90-appendix-a-introduction-to-ma-thematic-a 14/18

<< Graphics`Graphics`;

Histogram::shdw  :  

Symbol Histogram appears in multiple contexts 8Graphics`Graphics`, Global`<;

definitions in context Graphics`Graphics` mayshadow or be shadowed by other definitions.

Remove@Histogram D;<< Graphics`Graphics`;

Now the definition is fine:

?Histogram 

Histogram @8x1, x2, ...<D generates a bar graph representing a histogram of the

univariate data 8x1, x2, ...<. The width of each bar is proportional

to the width of the interval defining the respective category, and

the area of the bar is proportional to the frequency with which the

data fall in that category. Histogram range and categories may bespecified using the options HistogramRange and HistogramCategories.

Histogram @8f1, f2, ...<, FrequencyData -> TrueD generates a histogram 

of the univariate frequency data 8f1, f2, ...<, where fi is the

frequency with which the original data fall in category i. More…

Histogram @8x1, x2, ...<D generates a bar graph representing

a histogram of the univariate data 8x1, x2, ...<. More…

A7.2 Endless numerical output

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.

 m = Table@Random @D, 81000<, 81000<D

 m = Table@Random @D, 81000<, 81000<D;

Use Alt-. to abort an unwanted evaluation.

A7.3 For speed: make data numerical when possible

Be careful with symbolic computations on larger datasets. You may only be interested in the

numerical result. Compare the examples below:

 mm1 = Table@Sin@x yD, 8y, 1, 8<, 8x, 1, 8<D;Timing@symbolicInverse = Inverse@ mm1D;D

836.343 Second, Null<

Even for this small matrix, each symbolic term is huge, and very impractical to handle. The

numerical result is very fast:

 A. Introduction to Mathematica 408

Page 15: 90 Appendix a - Introduction to Ma Thematic A

8/8/2019 90 Appendix a - Introduction to Ma Thematic A

http://slidepdf.com/reader/full/90-appendix-a-introduction-to-ma-thematic-a 15/18

Timing@numericalInverse = Inverse@N@ mm1DD;D

80. Second, Null<

We look at the result:

Short@numericalInverse, 4D

880.150096, -0.00900765, 0.16249, -0.295079,

-0.194507, -0.0870855, 0.139714, 0.336583<, á6à , 8á1à <<

Another example: the numerical Eigenvalues of a matrix with 10,000 elements is computed

fast:

 mm2 = Table@Random @D, 8100<, 8100<D;Timing@Eigenvalues@ mm2D;D

80.032 Second, Null<

And use functional programming and internal functions as much as possible.

Timing@array = Range@107D;D

80.031 Second, Null<

Timing@array = Table@i, 8i, 1, 107<D;D

85.906 Second, Null<

A7.4 No more loops and indexing

E.g. to multiply each 2 elements of an array, from head to tail:

k1 = m = Table@Random @D, 8i, 1, 106<D;Timing@For@i = 0, i < 106, k1@@iDD = m @@iDD m @@106 - i + 1DD, i++DD êê First

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.

Timing@k = m Reverse@ m DD êê First

0.406 Second

A7.5 Copy and paste in InputForm

There are 4 format types for cells in  Mathematica. InputForm , OutputForm ,

StandardForm and TraditionalForm . See the help browser for a description of these

types. Be alert when pasting a TraditionalForm cell as input cell,  Mathematica may be

not able to interpret this unequivocally. When you attempt this,  Mathematica will issue a

warning, and you see the wigged line in the cell bracket.

409 A.7 What often goes wrong

Page 16: 90 Appendix a - Introduction to Ma Thematic A

8/8/2019 90 Appendix a - Introduction to Ma Thematic A

http://slidepdf.com/reader/full/90-appendix-a-introduction-to-ma-thematic-a 16/18

A.8 Suggested reading

A number of excellent books are available on Mathematica. A few of the best are listed here:

[Blachman1999] N. Blachman.  Mathematica: A practical approach. Prentice Hall, 2nd

edition, 1999. ISBN 0-13-259201-0.

This complete tutorial is the easiest, quickest way for professionals to learn Mathematica, the

world's leading mathematical problem-solving software. The book introduces the basics of 

Mathematica and shows readers how to get around in the program. It walks readers through

all of Mathematica's practical, built-in numerical functions--and covers symbolic

capabilities, plotting, visualization, and analysis.

[Ruskeepää1999] H. Ruskeepää.  Mathematica Navigator: Graphics and methods of applied

mathematics. Academic press, London. 1999. ISBN 0-12-603640-3 (paperback+CD-ROM).

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.

From the author:

- I would like first to ask, what is the general nature of your book Mathematica Navigator?

- Before answering, I would like to ask you, whether you know what is the difference

between an applied mathematician and a pure mathematician?

- Hm..., I seem to remember having heard some differences, but no, I don't remember any at

this moment. Tell me.

- An applied mathematician has a solution for every problem while a pure mathematician has

a problem for every solution.

- Yes, indeed. That is a very describing difference. But how does this maxim relate with my

question about the nature of your book?

- I am an applied mathematician, and so I took the task of solving every problem - namely in

using Mathematica.

- Not a very modest goal...

- Frankly, I took the task to write as useful a guide as possible so that you would have a more

easy way to the wonderful world of Mathematica.

- Do you start with the basics?

- Yes, and then the book goes carefully through the main material of Mathematica.

- What are the main areas of Mathematica?

- Graphics, symbolic calculation, numerical calculation, and programming.

- And how far does your book go?

- The book contains some advanced topics and material not easily found elsewhere, such as

stereographic figures, graphics for four-dimensional functions, graphics of real-life data,

fractal images, constrained nonlinear optimization, boundary value problems, nonlinear

 

 A. Introduction to Mathematica 410

Page 17: 90 Appendix a - Introduction to Ma Thematic A

8/8/2019 90 Appendix a - Introduction to Ma Thematic A

http://slidepdf.com/reader/full/90-appendix-a-introduction-to-ma-thematic-a 17/18

 

difference equations, bifurcation diagrams, partial differential equations, probability,

simulating stochastic processes, statistics.

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.

[Wolfram1999] S. Wolfram. The  Mathematica book. Fourth edition, Wolfram Media /

Cambridge University Press, 1999. 1470 pages. ISBN 0-52-164314-7.

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.

[Mäder1996a] R. Mäder, Programming in Mathematica, 3rd ed.. Addison-Wesley Pub., 1996.

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.

 

411 A.8 Suggested reading

Page 18: 90 Appendix a - Introduction to Ma Thematic A

8/8/2019 90 Appendix a - Introduction to Ma Thematic A

http://slidepdf.com/reader/full/90-appendix-a-introduction-to-ma-thematic-a 18/18

[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.

A9. Web resources

Webpages are very dynamic, and it is impossible to give a complete overview here. Some

stable pointers to a wealth of information and support are:

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.

www.mathsource.com:  MathSource is a vast electronic library of  Mathematica materials,

including immediately accessible  Mathematica programs, documents, journals ( Mathematica

in Education, the  Mathematica Journal) and many, many examples. Established in 1990,

 MathSource offers a convenient way for  Mathematica developers and users to share their

work with others in the  Mathematica community. In MathSource you can either browse the

archive or search by author, title, keyword, or item number.

There are many introductions to  Mathematica and pages with helpful links. Here are some

examples:

Tour of Mathematica (also available in the helpbrowser of  Mathematica)www.verbeia.com/mathematica/tips/tip_index.html Ted's Tips and Tricks

www.mathematica.ch/ (in German)

phong.informatik.uni-leipzig.de/~kuska/mview3d.html/ (MathGL3d, an OpenGL translator

for Graphics3D structures)

www.unca.edu/~mcmcclur/mathematicaGraphics/ Mathematica graphics examples

www.wolfram.com/products/applications/parallel/ Parallel computing toolkit

www.wolfram.com/solutions/mathlink/jlink/ Java toolkit

www.math.wright.edu/Calculus/Lab/Download/ Calculus teaching material

forums.wolfram.com/mathgroup/ MathGroup newsgroup archive

mathforum.org/math.topics.html MathForum by Drexler University

integrals.wolfram.com/ The Integrator

 A. Introduction to Mathematica 412