Basics of Mathematica Programming


Programming in Mathematica

A program (code) is a sequence of instructions to solve some problem. As we had discussed in class, such a sequence of instructions, described in some "natural-like" language, is called an algorithm. A program expresses the steps of the algorithm in some programming language. The objective of this document is to teach you the basics of programming in mathematica.
In Mathematica, we input each instruction and press the return key. Once all the instructions (the prgram) are typed in, we press the shift+enter key to execute the sequence.
Individual instructions in the code can be assignment statements,
iteration statements (loops), conditionals (if), input or output statements, functions,
or other programming constructs. The sections that follow explain these various constituent parts of a program.

User defined functions


In addition to the built-in functions provided in the function library (such as Cos, Log, Sqrt ...), programming languages generally allow users to define other functions useful in particular applications. As we have discussed in class, a function groups a sequence of statements that perform a particular task. Usually it is a task that has to be performed repeatedly. Functions also help us divide the task into smaller subtasks. This is often called modularization -we have alread discussed in class the virtues of modularization (remember the "throwing a party" example).

We define functions in Mathematica with statements of the form:

fcnName[arg1_,arg2_,...] := body


- where body specifies the computations that must be performed to
evaluate the function. The body is a program code -- it can be a single
expression or a series of expressions, separated by commas and enclosed
in parentheses, involving arithmetic operations, loops, if
statements, etc.

The underscore (_) after each argument name allows that argument
to be replaced with any other name or expression.

Without the underscore, an argument cannot be replaced with any other name or expression.

Example: binPower[x_] := (1+x)^2
In this example, the body of the function is a single statement. The x_ tells mathematica that this function will be called with one argument. The body of the function tells mathematica to add 1 to the argument and square it, and return the resulting number. Thus if we set the value of y4 to be binPower[4], the value is set to (1+4)^2. Similarly, y6 = binPower[6] will make y6 to be 49 (1+6)^2.

y4 = binPower[4]
25

y4yab = y4 binPower[a+b]
25 (1 + a + b)^2

When we set up a function definition using a series of expressions, the general form is:
fcnName[arg1_type1, arg2_type2,...] := (expr1;expr2;...)
- where statements are separated by semicolons.
Examples:

Clear[fcn1]
fcn1[a_,b_] := (c=a^2; b^3+c)

y = fcn1[2,2]
     12

(variable y is assigned last value calculated in the body of fcn1, unless the last expression
is terminated with a semicolon)

Clear[arithFcn]
arithFcn[a_Real,b_Real] :=
(sumab = a + b; diffba = b - a;
prodab = a * b
)

arithFcn[5.2,-3.1]
     -16.12

{result from last expression: a*b}

sumab
     2.1

diffba
     -8.3

Conditionals (decision Statements)

Often your algorithm for solving a problem can be different depending on the conditions. For example, instructions for driving will differ depending on the weather. If the weather is nice, it is OK to "slam" the brakes. On the other hand, if it is snowing, then that is not a good idea.High-level programming languages provide constructs which let you factor in such decisions in your program.
Mathematica provides the functions If, Which, and Switch for decision making.

If Function

If[test, true-stmts, false-stmts]

- if the test is true, the true-stmts are executed; if the test is false,
the false-stmts are executed.

Example:

x = 4;
If[x>0, y=Sqrt[x], y=0]
     2

In Mathematica it is possible that a test can be neither true nor false, since values may not have been assigned to the variables involved in the test. To handle this possibility, we can use the function:

If[test, true-stmats, false-stmts, neither]

- if the test is true, the true-stmts are executed; if the test is false,
the false-stmts are executed; otherwise the neither statements
are executed.


Which Function

Which[test1, value1, test2, value2, ...]

- returns the first valuek associated with the first true testk, as
tests are evaluated left to right.

Example:

x=-4;
y=Which[x>0,1/x,x<-3,x^2, True, 0]
     16

The third test, "True", is the default in this example. In other words, if none of the prior tests is matched, then the value corresponding to True is returned.

Switch Function

Switch[expr, form1, value1, form2, value2, ...,_,defval]

- evaluates expr and compares it to each formk in left-to-right order,
and returns corresponding valuek when a match is found. The
underscore(_) above is an optional default form (matches any-
thing).

Example:

a=-4; b=4;
y=Switch[a^2, ab, 1.0/a, b^2, 1.0/b, _, 01]
     0.25

For this example, the evaluation of a^2 matches the evaluation b^2, so the floating-point value of 1/b is returned.

Looping Constructs (Iteration)

Very often in a prgram, we have to do some task repeatedly, either for a fixed number of times, or as long as some condition holds. For example, for every month of the year, pay phone bill. Or, While still in debt, pay mortgage payment. High level languages provide constructs to handle this situation, which is often called looping or iteration. Mathematica provides functions Do, For, and While, which are similar to looping statements in high-level programming languages.

Do Function
- Has general forms:

Do[body, {k, kstart, kstop, dk}]


- evaluates body repeatedly with k varying from kstart to
kstop in steps of dk. Can omit dk, or both kstart and dk;
default values are 1.

- body contains one or more expressions separated by
semicolons.

Do[Body, {n}]

- body is evaluated n times.

The Do function generates no output, it simply evaluates the expression in the body,
repeating the evaluation for the specified number of iterations.

Using the Print function, we can output the value of an expression at each iteration.

Example Do Statements:


List of factorials (using factorial operator I).

Do[Print[1/m],{m,3}]
1
1
-
2
1
-
3

List of negative powers of 2.

Do[Print[2^k], {k,0,-2,-1}]
1
1
-
2
1
-
4

How would you obtain these results as rational numbers ?

Table of powers.

Do[Print[k," ",k^2, " ",k^3], {k,3}]
1 1 1
2 4 8
3 9 27

{character strings of two blank spaces each are used to separate columns}

Another table with character strings.

Do[Print[k," squared is ",k^2], {k,5}]
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25

A table with column headings.

Print["k   k^2"]
Print[" "]
Do[Print[k," ",k^2],{k,5}]
k   k^2

1 1
2 4
3 9
4 16
5 25

(A better way to produce tables is to set up lists and use the Table function, which aligns columns. We will discuss this method after we take a look at list structures in general.)

Loop variable does not have to be an integer.
It can be a floating-point number, as in

Do[Print[k],{k,1.6, 5.7,1.2}]
1.6
2.8
4.
5.2

It can include units, as in

Do[Print[k], {k, 2cm, 9cm, 3cm}]
2 cm
5 cm
8 cm

Or it can be an expression, as in

	Do[Print[k], {k,3(a+b), 8(a+b), 2(a+b)}]
3 (a + b)
5 (a + b)
7 (a + b)

Nested Loops

Do[Print[{i,j}],{i,4},{j,i-1}]
{2, 1}
{3, 1}
{3, 2}
{4, 1}
{4, 2}
{4, 3}

Body of Do Function can contain multiple expressions, separated by semicolons.

x=10.0;		
Do[Print[x];x=Sqrt[x], {3}]
10.
3.16228
1.77828

For Loop function

Do function is useful for loops that are to be repeated a fixed number of times. But in many cases, we do not know in advance how many times we want to repeat a loop. In Mathematica, we have two general loop functions that allow a loop to be ended when a particular condition is satisfied.

For Function has general form:

For[initial, test, incr, body]

first, the initial statements are processed, then the test condition is evaluated; if test is true, the body is processed, then incr is processed. The sequence test-body-incr is repeatedly processed until test is false.

Example:

Evaluate sum = sum + 1/x, starting at x=1 and continuing as long as 1/x > 0.15.

For[sum=0.0; x=1.0, (1/x) > 0.15, x=x+1,
sum=sum+1/x;Print[sum]]
1.
1.5
1.83333
2.08333
2.28333
2.45

(Note: semicolon is used as delimiter between statements in initial and in body.)

While Loop function

Has general form

While[test, body]

where body is a set of statements that are repeatedly processed
unit test is evaluated to be false.

Similar to For function, except initialization must be given as separate
statements.

Example While loops:

sum=0.0;
x=1.0;
While[1/x>0.15, sum=sum+1/x;
Print[sum]; x=x+1]
1.
1.5
1.83333
2.08333
2.28333
2.45

n=25; While[(n=Floor[n/2])>0, Print[n]]
12
6
3
1

Mathematica provides abbreviated forms for incrementing variables.

For example, we can use x++ in place of x=x+1 (as in C programming language) in the previous example:

	sum=0.0;
x=1.0;
While[1/x>0.15, sum=sum+1/x;
Print[sum]; x++]
1.
1.5
1.83333
2.08333
2.28333
2.45

The following table lists abbreviated forms for incrementing and making other assignments to the value of a variable in Mathematica.

x++ : Increments in the value of x by 1
x-- : Decrements the value of x by 1.
x+ = dx : Adds dx to the value of x
x- = dx : Subtracts dx from the value of x
x*=a : Multiplies the value of x by a
x/= a :Divides the value of x by a

This page has been accessed: times since Feb 12, 1997.