Mathematica Cookbook
Building Blocks for Science, Engineering, Finance, Music, and More
Publisher: O'Reilly Media
Release Date: May 2010
Pages: 830
Read on Safari with a 10day trial
Start your free trial now Buy on AmazonWhere’s the cart? Now you can get everything on Safari. To purchase books, visit Amazon or your favorite retailer. Questions? See our FAQ or contact customer service:
18008898969 / 7078277019
support@oreilly.com
Mathematica Cookbook helps you master the application's core principles by walking you through realworld problems. Ideal for browsing, this book includes recipes for working with numerics, data structures, algebraic equations, calculus, and statistics. You'll also venture into exotic territory with recipes for data visualization using 2D and 3D graphic tools, image processing, and music.
Although Mathematica 7 is a highly advanced computational platform, the recipes in this book make it accessible to everyone  whether you're working on high school algebra, simple graphs, PhDlevel computation, financial analysis, or advanced engineering models.
 Learn how to use Mathematica at a higher level with functional programming and pattern matching
 Delve into the rich library of functions for string and structured text manipulation
 Learn how to apply the tools to physics and engineering problems
 Draw on Mathematica's access to physics, chemistry, and biology data
 Get techniques for solving equations in computational finance
 Learn how to use Mathematica for sophisticated image processing
 Process music and audio as musical notes, analog waveforms, or digital sound samples
Table of Contents

Chapter 1 Numerics

1.0 Introduction

1.1 Controlling Precision and Accuracy

1.2 Mixing Different Numerical Types

1.3 Representing Numbers in Other Bases

1.4 Extracting the Digits of a Number

1.5 Working with Intervals

1.6 Converting Between Numerical Types

1.7 Displaying Numbers in Alternate Forms


Chapter 2 Functional Programming

2.0 Introduction

2.1 Mapping Functions with More Than One Argument

2.2 Holding Arbitrary Arguments

2.3 Creating Functions That Automatically Map Over Lists

2.4 Mapping Multiple Functions in a Single Pass

2.5 Keeping Track of the Index of Each Item As You Map

2.6 Mapping a Function over a Moving Sublist

2.7 Using Prefix and Postfix Notation to Produce More Readable Code

2.8 Defining Indexed Functions

2.9 Understanding the Use of Fold As an Alternative to Recursion

2.10 Incremental Construction of Lists

2.11 Computing Through Repeated Function Application

2.12 Building a Function Through Iteration

2.13 Exploiting Function Composition and Inverse Functions

2.14 Implementing Closures

2.15 Currying in Mathematica

2.16 Creating Functions with Default Values

2.17 Creating Functions That Accept Options


Chapter 3 Data Structures

3.0 Introduction

3.1 Ensuring the Most Efficient Representation of Numerical Lists

3.2 Sorting Lists

3.3 Determining Order Without Sorting

3.4 Extracting the Diagonals of a Matrix

3.5 Constructing Matrices of Specific Structure

3.6 Constructing Permutation and Shift Matrices

3.7 Manipulating Rows and Columns of Matrices

3.8 Using Sparse Arrays to Conserve Memory

3.9 Manipulating Deeply Nested Lists Using Functions with Level Specifications

3.10 Implementing Bit Vectors and Using Format to Customize Their Presentation

3.11 Implementing Trees and Traversals Using Lists

3.12 Implementing Ordered Associative Lookup Using a RedBlack Tree

3.13 Exploiting Mathematica’s BuiltIn Associative Lookup

3.14 Constructing Graphs Using the Combinatorica’ Package

3.15 Using Graph Algorithms to Extract Information from Graphs


Chapter 4 Patterns and RuleBased Programming

4.0 Introduction

4.1 Collecting Items That Match (or Don’t Match) a Pattern

4.2 Excluding Items That Match (or Don’t Match) a Pattern

4.3 Counting Items That Match a Pattern

4.4 Replacing Parts of an Expression

4.5 Finding the Longest (or Shortest) Match for a Pattern

4.6 Implementing Algorithms in Terms of Rules

4.7 Debugging Infinite Loops When Using ReplaceRepeated

4.8 Preventing Evaluation Until Replace Is Complete

4.9 Manipulating Patterns with Patterns

4.10 Optimizing Rules

4.11 Using Patterns As a Query Language

4.12 Semantic Pattern Matching

4.13 Unification Pattern Matching


Chapter 5 String and Text Processing

5.0 Introduction

5.1 Comparing Strings

5.2 Removing and Replacing Characters from Strings

5.3 Extracting Characters and Substrings

5.4 Duplicating a String

5.5 Matching and Searching Text

5.6 Tokenizing Text

5.7 Working with Natural Language Dictionaries

5.8 Importing XML

5.9 Transforming XML Using Patterns and Rules

5.10 Transforming XML Using Recursive Functions (à la XSLT)

5.11 Writing Parsers and Grammars in Mathematica


Chapter 6 TwoDimensional Graphics and Plots

6.0 Introduction

6.1 Plotting Functions in Cartesian Coordinates

6.2 Plotting in Polar Coordinates

6.3 Creating Plots Parametrically

6.4 Plotting Data

6.5 Mixing Two or More Graphs into a Single Graph

6.6 Displaying Multiple Graphs in a Grid

6.7 Creating Plots with Legends

6.8 Displaying 2D Geometric Shapes

6.9 Annotating Graphics with Text

6.10 Creating Custom Arrows


Chapter 7 ThreeDimensional Graphics and Plots

7.0 Introduction

7.1 Plotting Functions of Two Variables in Cartesian Coordinates

7.2 Plotting Functions in Spherical Coordinates

7.3 Plotting Surfaces in Cylindrical Coordinates

7.4 Plotting 3D Surfaces Parametrically

7.5 Creating 3D Contour Plots

7.6 Combining 2D Contours with 3D Plots

7.7 Constraining Plots to Specified Regions

7.8 Plotting Data in 3D

7.9 Plotting 3D Regions Where a Predicate Is Satisfied

7.10 Displaying 3D Geometrical Shapes

7.11 Constructing Wireframe Models from Mesh

7.12 Controlling Viewing Geometry

7.13 Controlling Lighting and Surface Properties

7.14 Transforming 3D Graphics

7.15 Exploring Polyhedra

7.16 Importing 3D Graphics from CAD and Other 3D Software


Chapter 8 Image Processing

8.0 Introduction

8.1 Extracting Image Information

8.2 Converting Images from RGB Color Space to HSV Color Space

8.3 Enhancing Images Using Histogram Equalization

8.4 Correcting Images Using Histogram Specification

8.5 Sharpening Images Using Laplacian Transforms

8.6 Sharpening and Smoothing with Fourier Transforms

8.7 Detecting Edges in Images

8.8 Image Recognition Using Eigenvectors (Eigenimages)


Chapter 9 Audio and Music Processing

9.0 Introduction

9.1 Creating Musical Notes

9.2 Creating a Scale or a Melody

9.3 Adding Rhythm to a Melody

9.4 Controlling the Volume

9.5 Creating Chords

9.6 Playing a Chord Progression

9.7 Writing Music with Traditional Chord Notation

9.8 Creating Percussion Grooves

9.9 Creating More Complex Percussion Grooves

9.10 Exporting MIDI files

9.11 Playing Functions As Sound

9.12 Adding Tremolo

9.13 Adding Vibrato

9.14 Applying an Envelope to a Signal

9.15 Exploring Alternate Tunings

9.16 Importing Digital Sound Files

9.17 Analyzing Digital Sound Files

9.18 Slicing a Sample


Chapter 10 Algebra

10.0 Introduction

10.1 Solving Algebraic Equations

10.2 Finding a Polynomial from a Given Root

10.3 Transforming Expressions to Other Forms

10.4 Generating Polynomials

10.5 Decomposing Polynomials into Their Constituent Parts

10.6 Dividing Polynomials by Other Polynomials


Chapter 11 Calculus: Continuous and Discrete

11.0 Introduction

11.1 Computing Limits

11.2 Working with Piecewise Functions

11.3 Using Power Series Representations

11.4 Differentiating Functions

11.5 Integration

11.6 Solving Differential Equations

11.7 Solving Minima and Maxima Problems

11.8 Solving Vector Calculus Problems

11.9 Solving Problems Involving Sums and Products

11.10 Solving Difference Equations

11.11 Generating Functions and Sequence Recognition


Chapter 12 Statistics and Data Analysis

12.0 Introduction

12.1 Computing Common Statistical Metrics of Numerical and Symbolic Data

12.2 Generating Pseudorandom Numbers with a Given Distribution

12.3 Working with Probability Distributions

12.4 Demonstrating the Central Limit Theorem

12.5 Computing Covariance and Correlation of Vectors and Matrices

12.6 Measuring the Shape of Data

12.7 Finding and Adjusting for Outliers

12.8 Fitting Data Using a Linear Model

12.9 Fitting Data Using a Nonlinear Model

12.10 Creating Interpolation Functions from Data

12.11 Testing for Statistically Significant Difference Between Groups Using ANOVA

12.12 Hypothesis Testing with Categorical Data

12.13 Grouping Data into Clusters

12.14 Creating Common Statistical Plots

12.15 QuasiRandom Number Generation

12.16 Creating Stochastic Simulations


Chapter 13 Science and Engineering

13.0 Introduction

13.1 Working with Element Data

13.2 Working with Chemical Data

13.3 Working with Particle Data

13.4 Working with Genetic Data and Protein Data

13.5 Modeling PredatorPrey Dynamics

13.6 Solving Basic Rigid Bodies Problems

13.7 Solving Problems in Kinematics

13.8 Computing Normal Modes for Coupled Mass Problems

13.9 Modeling a Vibrating String

13.10 Modeling Electrical Circuits

13.11 Modeling Truss Structures Using the Finite Element Method


Chapter 14 Financial Engineering

14.0 Introduction

14.1 Leveraging Mathematica’s Bundled Financial Data

14.2 Importing Financial Data from Websites

14.3 Present Value of Future Cash Flows

14.4 Interest Rate Sensitivity of Bonds

14.5 Constructing and Manipulating Yield Curves

14.6 BlackScholes for European Option Pricing

14.7 Computing the Implied Volatility of Financial Derivatives

14.8 Speeding Up NDSolve When Solving BlackScholes and Other PDEs

14.9 Developing an Explicit Finite Difference Method for the BlackScholes Formula

14.10 Compiling an Implementation of Explicit Trinomial for Fast Pricing of American Options

14.11 Modeling the ValueatRisk of a Portfolio Using Monte Carlo and Other Methods

14.12 Visualizing Trees for InterestRate Sensitive Instruments


Chapter 15 Interactivity

15.0 Introduction

15.1 Manipulating a Variable

15.2 Manipulating a Symbolic Expression

15.3 Manipulating a Plot

15.4 Creating Expressions for Which Value Dynamically Updates

15.5 Intercepting the Values of a Control Attached to a Dynamic Expression

15.6 Controlling Updates of Dynamic Values

15.7 Using DynamicModule As a Scoping Construct in Interactive Notebooks

15.8 Using Scratch Variables with DynamicModule to Balance Speed Versus Space

15.9 Making a Manipulate SelfContained

15.10 Remembering the Values Found Using Manipulate

15.11 Improving Performance of Manipulate by Segregating Fast and Slow Operations

15.12 Localizing a Function in a Manipulate

15.13 Sharing DynamicModule Variables across Cell or Window Boundaries

15.14 Creating Your Own Custom Controls

15.15 Animating an Expression

15.16 Creating Custom Interfaces

15.17 Managing a Large Number of Controls in Limited Screen Real Estate


Chapter 16 Parallel Mathematica

16.0 Introduction

16.1 Configuring Local Kernels

16.2 Configuring Remote Services Kernels

16.3 Sending a Command to Multiple Kernels for Parallel Evaluation

16.4 Automatically Parallelizing Existing Serial Expressions

16.5 Distributing Data Segments in Parallel and Combining the Results

16.6 Implementing DataParallel Algorithms by Using ParallelMap

16.7 Decomposing a Problem into Parallel Data Sets

16.8 Choosing an Appropriate Distribution Method

16.9 Running Different Algorithms in Parallel and Accepting the First to Complete

16.10 Sharing Data Between Parallel Kernels

16.11 Preventing Race Conditions When Multiple Kernels Access a Shared Resource

16.12 Organizing Parallel Processing Operations Using a Pipeline Approach

16.13 Processing a Massive Number of Files Using the MapReduce Technique

16.14 Diagnosing Parallel Processing Performance

16.15 Measuring the Overhead of Parallelization in Your Environment


Chapter 17 Interfacing Mathematica

17.0 Introduction

17.1 Calling External Command Line Programs from Mathematica

17.2 Launching Windows Programs from Mathematica

17.3 Connecting the Frontend to a Remote Kernel

17.4 Using Mathematica with C and C++

17.5 Using Mathematica with Java

17.6 Using Mathematica to Interact with Microsoft’s .NET Framework

17.7 Using the Mathematica Kernel from a .NET Application

17.8 Querying a Database

17.9 Updating a Database

17.10 Introspection of Databases


Chapter 18 Tricks of the Trade

18.0 Introduction

18.1 Cleaning Up During Incremental Development

18.2 Modifying Builtin Functions and Constants

18.3 Locating Undocumented Functions

18.4 Packaging Your Mathematica Solutions into Libraries for Others to Use

18.5 Compiling Functions to Improve Performance

18.6 Automating and Standardizing the Appearance of Notebooks Using Stylesheets

18.7 Transforming Notebooks into Other Forms

18.8 Calling into the Mathematica Frontend

18.9 Initializing and Cleaning Up Automatically

18.10 Customizing Frontend User Interaction


Chapter 19 Debugging and Testing

19.0 Introduction

19.1 Printing as the First Recourse to Debugging

19.2 Debugging Functions Called Many Times

19.3 Stack Tracing to Debug Recursive Functions

19.4 Taming Trace to Extract Useful Debugging Information

19.5 Creating a Poor Man’s Mathematica Debugger

19.6 Debugging BuiltIn Functions with Evaluation and Step Monitors

19.7 Visual Debugging with Wolfram Workbench

19.8 Writing Unit Tests to Help Ensure Correctness of Your Code

19.9 Creating MUnit Tests Where Success Is Not Based on Equality Testing

19.10 Organizing and Controlling MUnit Tests and Test Suites

19.11 Integrating Wolfram Workbench’s MUnit Package into the Frontend


Appendix About the Author

Colophon