next up previous contents
Next: Select Mathematica Commands and Up: Appendix II: Brief Intro Previous: Mathematica Tips, Tricks and

Mathematica Tips, Tricks and Traps

ABORT EXECUTION (INTERRUPT COMPUTATION)
INTERRUPT computation:   CTRL-C (if in cmd tool)
    CTRL-C CTRL-C or F2 F2 (if in EPOCH)
Mathematica will respond with: Interrupt>

Your response options are: h, a, c, i, s or t.

h   Help for options:
a   Abort current calculation:
c   Continue:
i   Enter an interactive dialog:
s   Show current operation:
t   Show all operations:

Note that if running Mathematica from Epoch, your response must be executed by META-RETURN as usual.


Clear functions

It is important to realize that values you assign to variables are permanent. Once you have assigned a value to a particular variable, the value will be kept until you explicitly remove it. Forgetting about definitions you made earlier is the single most common cause of mistakes when using Mathematica. To avoid such mistakes, you should remove values you have assigned to variables as soon as you finish using them. Clearing definitions of simple variables or functions can be done by the following;

In[n]:= x=.
or
In[n]:= Clear[f]   (* Clear the old definition of function f *)

Comments

You may want to add some comments in your programs to make it easier to understand. You can add such text at any point in your code simply by enclosing it in matching (* and *).  
In[n]:= (* Comments enclosed like this are ignored by Mathematica *)


Equal signs, assignments

When programming in Mathematica, you can modify the value of a particular variable by explicitly perforning an assignment such as the following;
x=y=value assign the same value to both x and y
{x,y}={value1, value2} assign different values to x and y
{x,y}={y,x} interchange the values of x and y
lhs = rhs rhs is evaluated when the assignment is made and stored in lhs
lhs:=rhs rhs is evaluated each time the value of lhs is requested as in calls to a function.

The basic difference between = and := operators is when the expression rhs is evaluated. lhs = rhs (with an equal sign) is an immediate assignment in which rhs is evaluated at the time when the assignment is made. lhs:=rhs, on the other hand, is a delayed assignment, in which rhs is not evaluated when the assignment is made, but is instead evaluated each time the value of lhs is requested. Use the = operator when rhs is intended to be the final value of lhs; use the := operator when rhs gives a command to be executed when asking for the value of lhs. Use the := operator rather than the = operator in function definitions. See Example

Equal signs, conditionals

Mathematica provides various ways to set up conditionals.
  TrueQ[expr] True if expr is True, and False otherwise.
lhs==rhs or Equal[lhs,rhs] True if lhs and rhs are identical, False otherwise.
lhs===rhs or SameQ[lhs, rhs] True if lhs and rhs are symbolically identical, False otherwise.
lhs!=rhs or NotEqual[lhs,rhs] True if lhs and rhs are not identical, False otherwise.
lhs=!=rhs or UnsameQ[lhs, rhs] True if lhs and rhs are not symbolically identical, False otherwise.

The main difference between lhs===rhs and lhs==rhs is that === always returns True or False, whereas == does not yield True or False unless x and y have specific values, such as numeric ones. When you want to test numerical equality, you should use ==. Use == to represent a symbolic equation as in Solve[x^2-2==0,x].


Functions (built-in)

Arguments to functions are always in square brackets, [ ], NOT in the usual open PARENTHESES, ( ). Also, all built-in functions are capitalized and normally use the standard math names. Thus, Sin[x] is correct whereas Sin(x) and sin[x] and sin(x) are wrong. Since built-in functions all begin with capital letters, there will be no conflict if your own user-defined functions contain all lowercase letters. See HELP to query Mathematica regarding the name or definition of a built-in function. For example, we define our own absolute value function as

In[1]:= abs[x_]:=If[x>0,x,-x]

In[2]:= abs[-3]

Out[2]= 3

In[3]:= Abs[-3]

Out[3]= 3
Built-in functions are compiled and hence much faster than the equivalent user-defined functions.

Functions (user-defined)

When you define your own functions, be sure and use the underscore character on the left side following each argument. Otherwise, the function will return a result only when given specific arguments. In general, the right side of function definitions never has underscore characters. This explains the following:

In[1]:= f[z] := z^2 + 2  (* This does not define a normal function *)

In[2]:= f[x]

Out[2]= f[x]

In[3]:= f[z]

             2
Out[3]= 2 + z

In[4]:= f[z_] := z^2 +2  (* defining a function *)

In[5]:= f[x]

             2
Out[5]= 2 + x

In[6]:= f[x+y]

                 2
Out[6]= 2 + (x+y) 
Thus, f[z]=value in In[1] gives a definition for a specific expression z. f[z_]=value in In[4] gives a definition which can be evaluated for any expression z.
To compare user-defined functions with built-in functions, see Example.

incrementation of iteration variables

When writing procedural programs, you may need to modify the value of a particular iteration variable repeadedly. Here are special notations for incrementing the values of variables. See Example.
i++ increment the value of i by 1
i-- decrement i
++i pre-increment i
--i pre-decrement i
i +=di add di to the value of i
i -=di subtract di from i
x *=c multiply x by c
x /=c divide x by c


Indexed objects

You may set up arrays which contain sequences of expressions, each specified by a certain index. You can define a list a={x,y,z,...} and think of the expression a[[i]] as being an "indexed" or "subscripted" variable whose value is the ith component of the list a. You can manipulate indexed variables using the following;
a[ [ i ] ]=value add or overwrite a value
a[ [ i ] ] access a value
a[ [ i ] ]=. remove a value
?a show all defined values of a
Clear[a] clear all defined values of a

In some cases it may be faster to define a as a function in which case one can refer to the function a evaluated at i, by a[i], instead of a[[i]].
See also Table, List and Array operations.


Multiplication

Multiplication can be indicated either by a * or a space. Thus, a b == a*b is True. Adjacent expressions enclosed in parentheses also indicate multiplication: (a)(b) == a b is True. Mathematica output always uses spaces to indicate multiplication. Note that ab $\ne$ a b since ab is a single variable, regardless of what previous definitions a and b may have.


Parentheses (Bracketing in Mathematica)

Each kind of bracketing has a different meaning. ( expression ) are parentheses for grouping, f[x] are square brackets for functions, {a,b,c} are curly braces for lists, a[ [ i ] ], a[ [ i,j ] ] are double brackets for indexing in arrays, lists and tables. It is important for you to see matching pairs of brackets.


Precedence of operators

Precedence of operators is generally the same as in other programming languages. One notable exception is the ^ (power) operator. Thus, 2^2^3 == 256 is True whereas 2^2^3 == 64 is False. You can always specify the order in which operations will be performed by explicitly using parentheses. Thus, (2^2)^3 == 64 is True as well as 2^(2^3) == 256 is True.


Recursion

Recursively defined functions are easily programmed in Mathematica. For example, the famous Fibonacci sequence could be recursively defined by:

In[1]:= f[0]=f[1]=1 (* Special case definitions *)

Out[1]= 1

In[2]:= f[k_]:=f[k]=f[k - 1]+f[k - 2]

In[3]:= ?f      (* Now we look at the definition of f *)

Global`f

f[0] = 1
 
f[1] = 1
 
f[k_]:= f[k] = f[k - 1] + f[k - 2]

In[4]:= f[3]

Out[4]= 3

In[5]:= ?f     (* Look at the expanded definition of f due to In[3] *)

Global`f

f[0] = 1
 
f[1] = 1

f[2] = 2
 
f[3] = 3
 
f[k_] := f[k] = f[k - 1] + f[k - 2]

Note that the f[k] on the right side of the definition f[k_]:=f[k]=f[k-1]+f[k-2] will expand the special case definitions of f and save the value f[n] when computed as f[3] in In[4]. This is important in many cases, particularly if values of f are needed again and time consuming to compute.

Solve an equation

An expression like lhs==rhs represents an equation in Mathematica. Solve[lhs==rhs, x] gives the solutions to the equation as replacements for x. For example,

In[n]:=     Solve[x^2-6x==-8,x]

Out[n]=     {{x->2},{x->4}}
You can get a list of the actual solutions for x by applying the rules generated by Solve to x using the replacement operator. That is to use x /. solution.
In[n+1]:=   x/. %

Out[n+1]=   {2,4}
Since the output is in the form of 1 X k matrix (an array), expression[[n]] operation can be applied to extract the nth term in the expression. In the example above,
In[n+2]:=   x/. %%[[2]]

Out[n+2]=   4
gives the second root.

 

 

  Additional Mathematica commands and examples can be found at
Select Mathematica Commands and Exmaples




next up previous contents
Next: Select Mathematica Commands and Up: Appendix II: Brief Intro Previous: Mathematica Tips, Tricks and