IS: Useful Mathematica Functions (75.html)


Mathematica_9
Mathematica_9


In the examples below:
- the following sequences of letters each refer to one keyboard key not multiple keys
Esc, F1, F3, F7, F12, Alt, shift, ctrl, Enter
- iff means "if and only if"

After purchasing a $35 Raspberry computer in Feb 2015, David Cole, the author of this article, found it very easy to use it to surf the web. But he also discovered the free working copy of the Mathematica programming language on the Raspberry. David has been a computer programmer (and electrical engineer) since 1966. This article is a notebook recording his early interactions with this programming language.
The basic Mathematica is similar to other programming languages, but it differs in many important ways. The primary difference is that it is based on Functions. Such functions can minimally be used as mathematical functions. Each function creates an object after accepting an object as input. Anyone familiar with UNIX or Linux, notices that Mathematica is a major extension of the UNIX command line. In fact, the basic concept of "piping results from one function to the next" carries through into Mathematica. But the differences between Mathematica and its peers are immense. Back in the 60's when Iverson created his innovative APL programming language, goal was to make programs more concise. But they were also difficult to read (or understand) and they required a special ball on Selectric typewriter terminals. Some say that a trip is usually more about the voyage than the destination. When a program is being written, creation of a working algorithm is all-important. A program's comments and documentation are also important, but even more important is the mental process that was in the programmer's mind. Mathematica is less concise than APL, but the opportunity to follow the evolution or development of a program is fostered by Mathematica's concept of the "notebook".
Mathematica is more than a mere programming language. The "code" is a notebook in which one can type notes describing ongoing research, as in working thesis notes. Many typsetting features enable sentences and paragraphes to include mathematical expressions, equations etc. Mathematica can be used to list data, to evaluate the data on-the-spot by using the "actual data" (not data similar to it) through program segments. The user can write programs (within the notebook), solve equations, cite (and verify) references and much more. Mathematica can be used to draw figures and to create objects such as graphs, images and figures programatically. Resulting objects can be static or dynamic. Expressions are the main construct in Mathematica. Such expressions can be procedural, can contain logic and can contain formulae, numbers (integers, decimal fractions and complex numbers). In Mathematica, 1/0 produces Infinity, and 1/Infinity produces 0. Each expression is a sequence of functions that can even be recursive.
Interaction with Mathematica is primarily in the form of questions and answers. Each question is posed in the form of an expression eg. 23 * 17^2 followed by the Shift-Return key. Mathematica then evaulates the expression. If the expression ends with a ";" the result is not output to the screen for the user to see. Mathematica then evaluates the subsequent expression in the same way. After processing all the expressions in the notebook, Mathematica waits for the user to tell it what expression(s) to evaluate next. At this point, the user composes more expressions. A program's statements, per se, do not exist. Instead, we have a series of expressions written in the notebook. The results of such a Mathematica session are usually stored in one or more named notebooks on the user's storage device such as a hard drive or flash drive.

The author of Mathematica, Stephan Wolfram, has created a hierarchy of three engines:
-Wolfram - an interactive programming language which manipulates numbers and strings (c1980)
-Mathematica - an interactive programming language containing Wolfram and adding image functionality
-Wolfram|Alpha - a WebSite that answers questions. It uses the following:
Mathematica
An engine to understand questions that are posed in English
Data located elsewhere on the Internet.
This document restricts itself to notes about Mathematica, specifically Mathematica running under Raspian on the Raspberry Pi 2 B computer platform. More articles cited or written by David Cole can be found at ePC Articles by Cole .

The first group is a list of Built-In Mathematica Functions (not just Mathematica-9 functions) that I think might be useful to me. Special System Variables (Functions not needing arguments) are also listed. After this, some useful Mathematica Commands are listed, then an explanation of some Special Operator Coding Syntax for Mathematica. Finally a number of one-liners that a new coder must know. This is followed by a list of Related References.

Mathmatica uses a large collection of symbols in its lexicon. Rather than forcing its users to learn how to use a new keyboard, many constructs are included. These constructs permit the user to choose which method is best to write Mathematica code. But this does lead to some confusion. Hopefully this confusion is short-lived for every Mathematica novice. For example, the operator named "Rule" can be produced in any of the following ways:
Not all operators can be input in all these ways. The user must use trial & error to discover which to use. Note that x==4. no longer works. It has been deprecated (removed) from having this meaning. The "==" now means something else. References to old Mathematica programs may still use this old construct. Such programs need to be identified before they are used. Special precautions must be taken to avoid such temporal problems. Fortunately, this rarely happens after a programming language has been in use for a long time.

Useful Mathematica Functions

( * indicates na [not available . . . yet] )

create a list of numbers from 1 to 5EdgeDetect[object]
Discipline... Name Description
All Cases[n,n..._p ]Returns cases that match the pattern
All Now Returns current time e.g. Wed 2 Apr 2014 13:34:45
All Timing [e]Returns elapsed time, value of e
All SortBy[list,f ]Sorts the elements by applying f to each element
Asm. ByteArray[s ]Converts a Base64 string to a byte array
Crypt. Encrypt [ ]Encrypts something using a key/code
Dict. DictionaryLookup[s]Looks up words using patterns
Editting TextWords[ ]Break into a list of words
Info. WikipediaSearch*[s ]Structured search for content in Wikipedia
Linux UnixTime[date]Converts Date/Time to seconds since 1970 A Jan 01
Math. MinMax[l,d ]Returns the min & max values padded by d
Math. NestWhileList[f,e,?]repeats f starting with e till test:? fails
Math. Solve[{e,e},x]Solves a list of equationsfor x
Math. With[{x=x0..},e]evaluates e with x=x0 etc
Math. Range[n ]Range[5]
Stats. TTest[{d,d...}]Probability that the mean (ie Average) is zero
Strings StringJoin[s,s,s ]Joins a list of strings
Strings StringPartition[s,n ]Partitions a string into a list of ..
Tables Table[x^2,{x,3}]create a Table with 1,4,9 in it.
Vision(IS) EdgeDetect[j]Creates an object showing edges
Vision(IS) ImageIdentify[ ]Tries to identify what the image is
[ ]


Useful Mathematica Commands

Discipline... Name Description
All Clear[] clears previous definition of variables
All Clear[f] clears previous definition of function f
All Clear[Global`*] clears all previous Global definitions
Coding ctrl-6 superscript
Coding ?Name Look Up "Name" in Documentation
Coding Print[s] Output s to window pane just prior to next [Out-nn]
Coding Print[s,s] Output s,s to window pane
Coding % Previous Output Result
Coding %n Output Result number n
Coding (* *) These enclose comments
Coding Word` Context Names must end with `
Coding SetAttributes[f,Listable] function is defined by a list
Coding FullForm["a"<>"b"] Prints a string enclosed in double quotes
Coding FullForm[2Pi] Prints Times[2,Pi] (* showing the implied multiplication *)
Math. InputArray(in menu)accepts array elements from the user
Math. Solve[{x^2-1==0},x] Solves x^2-1 for x [iff x is undefined]
Math. Solve*[{Equal[x^2-1,0]},x] Solves x^2-1 for x
NoteBook Print[$OperatingSystem] Prints "Unix" for example


Voiced Equivalent of Mathematica Syntax (under Raspbian)

** indicates deprecated syntax (either "no longer valid" or "now has a different meaning")
!! indicates Warning: this similar construct does not have the same meaning
GT is voiced as Greater Than
LT is voiced as Less Than
EQ is Voiced as Equal To

Name.... Syntax Voiced EquivalentExampleVoiced As
Alias Esc Escescaped Esc->Esc Escaped "->" is the alias of the Rule Operator
All FullFormprint the full form of FullForm[2.Pi]print the full form of 2.Pi prints 6.283185307179586`
Anonymous Function f[&]see Pure Function Can be piped (see Piping)
Apply @@apply to Plus @@ {a,b,c} Plus apply to list ie a+b+c
Arguments _1 argument f[x_] function f with only 1 argument
Arguments __1 or more arguments f[x__] function f with 1 or more arguments
Arguments ___0, 1 or more arguments f[x___] function f with 0, 1 or more arguments
Assign. :=set equal to (deferred) x:=b x is set equal to b (deferred)
Assign. =set equal to x=b x is set equal to b
Assign. =set equal to x=5. x is set equal to 5.
Assign. =is given the value of x=5. x is given the value of 5.
Assign. ! not x!<y x not less than y
Code Alt-/Uncomment Alt-/ Uncomment a statement-removes (* & *)
Concat. <>concatenated toa$<>b$ a$ concatenated to b$
Condition >=is GT or EQ toy>=x^2-3y is GT or EQ to x^2-3
Condition <=is LT or EQ toy<=x^2-3y is LT or EQ to x^2-3
Cond. /;such that f[r_ /; r <a]:=n*r function of r such that r<a is equal to deferred n times r
Full Name \[ ]full name of \[Rule]\[Rule] is the full name of the Rule operator.
Function f[x_]=f is the result of x being substituted inf[x_]=Sin[x] f is the result of x being substituted in Sin[x]
Iteration +=increment by then test after i += 1 begin with i=first, increment by 1 then test for completion
Help F1Find Selected Function Select Sin then F1Wolfram Doc center explains Sin
Help shift-F1any symbol shift-F1 then (# in search documentation box)shift F1 explains any single symbol (#-first arg of a pure function)
Help F3Find Next F3Finds next occurance of current search string
Help shift-F3Find Previous shift-F3Finds previous occurance of cureent previous search string
Help F7Evaluate in Subsession F7?
Help F12Toggle Full Screen F12Toggles Full Screen Mode on/off
Iter. {x,a,z,d} iterated {x,1,7,2}x iterated from 1 to 7 by 2
Math. ==is equal toy==x^2-3y is equal to x^2-3
Math. Equal[ ]is equal to Equal[x^2-1,0] x^2-1 is equal to 0
Math. Equal[]is equal toEqual[y,x^2-3]y is equal to x^2-3
Math. Esc==Escis equal toyEsc==Escx^2-3y is equal to x^2-3
Math. Iimaginary I 3+I*2 3 plus imaginary I times 2
Patterns "d"defined string DictionaryLookup["sphinx"] Searches for "sphinx"
Patterns ~~joined to DictionaryLookup["so"~~"x"] Searches for "sox"
Patterns ___any string DictionaryLookup["x"~~___~~"x"] Finds "xerox"
Patterns yvariable name y="x";DictionaryLookup[y~~___~~y] Finds "xerox"
Patterns _pattern match a pattern _Integermatch an Integer
Piping//piped to Sin[.01] // ArcSin Sin[.01] piped to ArcSin ie ArcSin[Sin[.01]]
Pure Function f[&]is a pure function f[&]=Sin[#] f is a pure function of Sin
Rule ->goes toy->x^2-3y goes to x^2-3
Rule Esc->Escgoes toyEsc->Escx^2-3y goes to x^2-3
Rule Rule[]goes toRule[y,x^2-3]y goes to x^2-3
Rule :>goes to (delayed)y:>x^2-3y goes to delayed x^2-3
Rule!! =>Invalidy=>x^2-3y=>x^2-3 (* bad syntax *)
Rule!! Esc=>EscImpliesyEsc=>Escx^2-3y Implies x^2-3
Rule!! \[Implies]Impliesy\[Implies]x^2-3y Implies x^2-3
Rule!! Implies[]ImpliesImplies[y,x^2-3]y Implies x^2-3
Replacement /.given that 2.Sin[x]/.x->4. 2.Sin[x] given that x goes to 4. (* 2Sin[4] *)
Replacement /.given that 2.Sin[x]/.xEsc->Esc4. 2.Sin[x] given that x goes to 4. (* 2Sin[4] *)
R.Replacement //.. repeated replacement


Mathematica Concepts (One-Liners)

  1. Elements of lists are numbered beginning with 1.
  2. Example variables in function definitions end with _.
  3. Numbers for aritmetic should contain a decimal point.
  4. Imaginary I must be capitalized.
  5. Clear[] variable parameters before using them in functions or commands such as Solve[]
  6. Clear[Global`*] is wise at the beginning of a NoteBook (if n GT 1 in line In[n])
  7. The command "c=d" assigns the expression on the right (d) to the variable on the left (c)
  8. The command "j:=k" does the same as "=" but it is deferred until the command is executed.
  9. The operator "l==m" asserts that (l EQ m) is True. This is how an equation is defined.
  10. The rule "p->q" asserts that the rule is True iff p goes to the expression on the right (q).It does not do p=q.
  11. The operator "=>" is bad syntax. It means neither "EQ or GT" nor "Esc=>Esc" which would mean \[Implies]/
  12. The expression 3.*x/.x->4. is equivalent to 3.*4. The expression 3.*x/.x->n is equivalent to 3.*n
  13. Use StringJoin[] instead of the undefined function: Concatenate[]
  14. The character "`" printed after a decimal number means "approximated i.e. truncated"
  15. The integer 2 in "2 Pi" vs 2. in "2. Pi" is an unevaluated 2 (* quite different; try FullForm[] of each *)
  16. A $ as the last letter of a string name is not necessary, but improves code readability
  17. Plot IBM since 2008 using DateListPlot[TimeSeries[FinancialData["IBM","Jan.1,2008"]]];

References

Related Articles (to Mathematica)

Click on Title to view the Mathematica article

Discipline... Title Description
Math. Mathematical Operators List of such operators eg +, *, <>
Input Assistant Wolfram Predictive Interface Provides suggestions while typing into a notebook.
Intro. Fast Introduction for Programmers. First slides for coders.

Bibliography

The www link is on the web, the main link is "identical" but may also be archived on the Webmaster's server, just in case the www link disappears or is altered. The small icons after the name of the main link indicate the type or location of the reference.

Book 1: Stephen Wolfram - www It's Been 10 Years: What's Happened with A New Kind of Science , Date: 2012 E May 07


External References

Source 1:www Mathematica Tips, Tricks, and Techniques by Michael A. Morrison Date: 2000 D Apr 02

Source 2:www Mathematica Stack Exchange by many authors Date: 2015 D Apr 02

Source 3:www Mathematica Stack Exchange: Tips and Tricks (very thorough) by faysou Date: 2012 A Jan 09

Source 4:www Basic Advice for beginners (short excerpt from Source 3) by faysou Date: 2015 C Mar 15

Source 5:www Code Refactoring Wikipedia Date: 2015 C Mar 15

Source 6:www Refactoring by Martin Fowler Date: 2015 C Mar 25

Source 7:www Mathematica 10 announcement by Amoud Buzing of Wolfram Date: 2014 8 Aug 14


WebMaster: Thou Old King Cole

Click here to return to ePC Articles by Old King Cole

Updated: 2015 D Apr 11
/75.html