www.it-ebooks.info www.it-ebooks.info Mathematica Cookbook Sal Mangano "EIJING s #AMBRIDGE s &ARNHAM s +LN s 3EBASTOPOL s 4AIPEI s 4OKYO Download from Wow! eBook <www.wowebook.com> www.it-ebooks.info Mathematica Cookbook by Sal Mangano Copyright © 2010 Salvatore Mangano. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online edi- tions are also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com. Editor: Mike Loukides Production Editor: Adam Witwer Production Services: Precision Graphics Cover Designer: Karen Montgomery Interior Designer: David Futato Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trade- marks of O’Reilly Media, Inc. Mathematica Cookbook, the image of a solarium seashell, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. ISBN: 978-0-596-52099-1 Wolfram Mathematica ® Spikey logo is a registered trademark of Wolfram Research, Inc. The Mathematica software design, look and feel, display, and other graphic elements are copyright of Wolfram Research, Inc. “ ” is a registered trademark of Wolfram Research, Inc. The Mathematica Download from Wow! eBook <www.wowebook.com> www.it-ebooks.info To Wanda, Leonardo and Salvatore: My life would not compute without you. Download from Wow! eBook <www.wowebook.com> www.it-ebooks.info Included with this book is a free 30 day trial of the Wolfram Mathematica ® software. To access your free download, simply go to http://www.wolfram.com/books/resources and enter license number L3294-005. You will be guided to download and install the latest version of Mathematica. Download from Wow! eBook <www.wowebook.com> www.it-ebooks.info v Table of Contents Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xv 1. Numerics 1 1 1.1 Controlling Precision and Accuracy 4 1.2 Mixing Different Numerical Types 9 1.3 Representing Numbers in Other Bases 12 1.4 Extracting the Digits of a Number 13 1.5 Working with Intervals 16 1.6 Converting Between Numerical Types 18 1.7 Displaying Numbers in Alternate Forms 20 2. Functional Programming 23 2.0 Introduction 23 2.1 Mapping Functions with More Than One Argument 32 2.2 Holding Arbitrary Arguments 36 2.3 Creating Functions That Automatically Map Over Lists 37 2.4 Mapping Multiple Functions in a Single Pass 38 2.5 Keeping Track of the Index of Each Item As You Map 41 2.6 Mapping a Function over a Moving Sublist 43 2.7 Using Prefix and Postfix Notation to Produce More Readable Code 48 2.8 Defining Indexed Functions 51 2.9 Understanding the Use of Fold As an Alternative to Recursion 53 2.10 Incremental Construction of Lists 57 2.11 Computing Through Repeated Function Application 59 2.12 Building a Function Through Iteration 62 Download from Wow! eBook <www.wowebook.com> www.it-ebooks.info vi | Table of Contents 2.13 Exploiting Function Composition and Inverse Functions 63 2.14 Implementing Closures 66 2.15 Currying in Mathematica 73 2.16 Creating Functions with Default Values 77 2.17 Creating Functions That Accept Options 79 3. Data Structures . 85 3.0 Introduction 85 3.1 Ensuring the Most Efficient Representation of Numerical Lists 95 3.2 Sorting Lists 97 3.3 Determining Order Without Sorting 100 3.4 Extracting the Diagonals of a Matrix 102 3.5 Constructing Matrices of Specific Structure 103 3.6 Constructing Permutation and Shift Matrices 105 3.7 Manipulating Rows and Columns of Matrices 110 3.8 Using Sparse Arrays to Conserve Memory 112 3.9 Manipulating Deeply Nested Lists Using Functions with Level Specifications 114 3.10 Implementing Bit Vectors and Using Format to Customize Their Presentation 119 3.11 Implementing Trees and Traversals Using Lists 121 3.12 Implementing Ordered Associative Lookup Using a Red-Black Tree 125 3.13 Exploiting Mathematica’s Built-In Associative Lookup 130 3.14 Constructing Graphs Using the Combinatorica` Package 134 3.15 Using Graph Algorithms to Extract Information from Graphs 140 4. Patterns and Rule-Based Programming . 145 4.0 Introduction 145 4.1 Collecting Items That Match (or Don’t Match) a Pattern 151 4.2 Excluding Items That Match (or Don’t Match) a Pattern 153 4.3 Counting Items That Match a Pattern 155 4.4 Replacing Parts of an Expression 157 4.5 Finding the Longest (or Shortest) Match for a Pattern 159 4.6 Implementing Algorithms in Terms of Rules 161 4.7 Debugging Infinite Loops When Using ReplaceRepeated 165 4.8 Preventing Evaluation Until Replace Is Complete 168 4.9 Manipulating Patterns with Patterns 169 Download from Wow! eBook <www.wowebook.com> www.it-ebooks.info Table of Contents | vii 4.10 Optimizing Rules 170 4.11 Using Patterns As a Query Language 171 4.12 Semantic Pattern Matching 177 4.13 Unification Pattern Matching 178 5. String and Text Processing . 181 5.0 Introduction 181 5.1 Comparing Strings 187 5.2 Removing and Replacing Characters from Strings 188 5.3 Extracting Characters and Substrings 192 5.4 Duplicating a String 196 5.5 Matching and Searching Text 198 5.6 Tokenizing Text 201 5.7 Working with Natural Language Dictionaries 202 5.8 Importing XML 209 5.9 Transforming XML Using Patterns and Rules 213 5.10 Transforming XML Using Recursive Functions (à la XSLT) 218 5.11 Writing Parsers and Grammars in Mathematica 227 6. Two-Dimensional Graphics and Plots . 237 6.0 Introduction 237 6.1 Plotting Functions in Cartesian Coordinates 238 6.2 Plotting in Polar Coordinates 247 6.3 Creating Plots Parametrically 249 6.4 Plotting Data 252 6.5 Mixing Two or More Graphs into a Single Graph 255 6.6 Displaying Multiple Graphs in a Grid 258 6.7 Creating Plots with Legends 260 6.8 Displaying 2D Geometric Shapes 263 6.9 Annotating Graphics with Text 269 6.10 Creating Custom Arrows 270 7. Three-Dimensional Plots and Graphics . 275 7.0 Introduction 275 7.1 Plotting Functions of Two Variables in Cartesian Coordinates 276 7.2 Plotting Functions in Spherical Coordinates 283 7.3 Plotting Surfaces in Cylindrical Coordinates 285 7.4 Plotting 3D Surfaces Parametrically 290 Download from Wow! eBook <www.wowebook.com> www.it-ebooks.info viii | Table of Contents 7.5 Creating 3D Contour Plots 292 7.6 Combining 2D Contours with 3D Plots 295 7.7 Constraining Plots to Specified Regions 296 7.8 Plotting Data in 3D 298 7.9 Plotting 3D Regions Where a Predicate Is Satisfied 301 7.10 Displaying 3D Geometrical Shapes 302 7.11 Constructing Wireframe Models from Mesh 306 7.12 Controlling Viewing Geometry 309 7.13 Controlling Lighting and Surface Properties 313 7.14 Transforming 3D Graphics 317 7.15 Exploring Polyhedra 320 7.16 Importing 3D Graphics from CAD and Other 3D Software 326 8. Image Processing . 329 8.0 Introduction 329 8.1 Extracting Image Information 332 8.2 Converting Images from RGB Color Space to HSV Color Space 335 8.3 Enhancing Images Using Histogram Equalization 341 8.4 Correcting Images Using Histogram Specification 347 8.5 Sharpening Images Using Laplacian Transforms 351 8.6 Sharpening and Smoothing with Fourier Transforms 356 8.7 Detecting Edges in Images 361 8.8 Image Recognition Using Eigenvectors (Eigenimages) 365 9. Audio and Music Processing . 373 9.0 Introduction 373 9.1 Creating Musical Notes 374 9.2 Creating a Scale or a Melody 375 9.3 Adding Rhythm to a Melody 376 9.4 Controlling the Volume 377 9.5 Creating Chords 378 9.6 Playing a Chord Progression 379 9.7 Writing Music with Traditional Chord Notation 380 9.8 Creating Percussion Grooves 384 9.9 Creating More Complex Percussion Grooves 386 9.10 Exporting MIDI files 389 9.11 Playing Functions As Sound 390 Download from Wow! eBook <www.wowebook.com> www.it-ebooks.info [...]... 686 17 Interfacing Mathematica 689 17.0 17.1 17.2 17.3 17.4 17.5 17.6 17.7 17.8 17.9 17.10 Introduction Calling External Command Line Programs from Mathematica Launching Windows Programs from Mathematica Connecting the Frontend to a Remote Kernel Using Mathematica with C and C++ Using Mathematica with Java Using Mathematica to Interact with Microsoft’s NET Framework Using the Mathematica Kernelfrom... correct Mathematica program is often a short Mathematica program There is much truth to this The truth comes from the idea that good Mathematica programs leverage the capabilities of the vast built-in library of both general-purpose and highly specialized functions Programming in Mathematica is a search for the right combination of primitives My hope is that this cookbook will play a role as your guide MathematicaCookbook.com... these books are designed to help you solve real-world problems Mathematica is an ideal candidate for a cookbook because it is so vast, deep, and full of traps for the novice I was ecstatic to learn that O’Reilly was looking to publish a Mathematica cookbook and even more excited when I was chosen to be its author I have been a user of Mathematica since version 3.0 Although that was over 13 years ago,... living resource that I hope the Mathematica community will help nourish, I am launching http://mathematicacookbook.com Here you will find recipes that did not make it into this book, and more importantly, you will be able rate recipes, contribute your own, or provide alternative implementations to those found in the book or on the site Structure of This Book The Mathematica Cookbook is not necessarily meant... derives from Mathematica s aim to be a platform for publishing mathematical ideas as much as a computer-aided mathematics tool and programming language At this point in the book, I do not go over all possible ways Mathematica can display input and output Rather, I introduce the reader to four basic syntaxes for Mathematica expressions This was a point of confusion for me when I first learned Mathematica, ... combination of primitives My hope is that this cookbook will play a role as your guide MathematicaCookbook.com One risk of authoring a cookbook is that it is almost inevitable that something someone finds important will be left out With Mathematica, this risk is a certainty because even as I wrote the book, Mathematica s capabilities grew However, even if you drew a line at, say, version 6.0, you would... master those core principles by presenting Mathematica in www.it-ebooks.info xv the context of real-world problems However, my goal is not just to show you how to solve problems in Mathematica, but to show you how to do so in a way that plays to Mathematica s strengths This means there is an emphasis on symbolic, functional, and pattern-based styles of programming Mathematica is a multi-paradigm programming... functional programming, Mathematica style Because Mathematica was designed to support multiple development paradigms, its functional programming abilities are not as pure as languages like Haskell This is actually a big plus, because if you are using Mathematica chances are you are solving a problem, and it’s the solution rather than the aesthetics that is foremost in your mind Mathematica programmers... feedback that will draw you into Mathematica However, this style is often mysterious to people who come to Mathematica from other languages like Fortran, C, Mathlab, or Microsoft Excel I think this chapter will help you discover the rewards of the functional style Chapter 3 presents Mathematica data structures, which are largely built on the foundation of lists From lists, Mathematica derives matrices... returns to more mathematical fare by exploring Mathematica s formidable abilities in symbolic math This chapter focuses on algebraic manipulation and solutions to equations Many of the recipes show techniques for massaging results produced by Mathematica into equivalent but sometimes more desirable forms Symbolic and numerical calculus is what most people think about when they think about Mathematica, . I wrote the Mathematica Cookbook. I am a big fan of O’Reilly cookbooks, as these books are designed to help you solve real-world problems. Mathematica is an ideal candidate for a cookbook because. Programming in Mathematica is a search for the right combination of primitives. My hope is that this cookbook will play a role as your guide. MathematicaCookbook.com One risk of authoring a cookbook. Kernel 692 17.4 Using Mathematica with C and C++ 694 17.5 Using Mathematica with Java 700 17.6 Using Mathematica to Interact with Microsoft’s .NET Framework 707 17.7 Using the Mathematica Kernelfrom