Preface


This tutorial was made solely for the purpose of education and it was designed for students taking Applied Math 0330. It is primarily for students who have very little experience or have never used Mathematica and programming before and would like to learn more of the basics for this computer algebra system. As a friendly reminder, don't forget to clear variables in use and/or the kernel. The Mathematica commands in this tutorial are all written in bold black font, while Mathematica output is in normal font.

Finally, you can copy and paste all commands into your Mathematica notebook, change the parameters, and run them because the tutorial is under the terms of the GNU General Public License (GPL). You, as the user, are free to use the scripts for your needs to learn the Mathematica program, and have the right to distribute this tutorial and refer to this tutorial as long as this tutorial is accredited appropriately. The tutorial accompanies the textbook Applied Differential Equations. The Primary Course by Vladimir Dobrushkin, CRC Press, 2015; http://www.crcpress.com/product/isbn/9781439851043

Return to computing page for the first course APMA0330
Return to computing page for the second course APMA0340
Return to Mathematica tutorial for the first course APMA0330
Return to Mathematica tutorial for the second course APMA0340
Return to the main page for the course APMA0330
Return to the main page for the course APMA0340

Logical operators


As many other languages, Mathematica has several built-in logical operators. We will consider logical AND : short-hand &&, literal equivalent And[], logical OR: short-hand ||, literal equivalent Or[], and the negation NOT (short-hand , literal equivalent Not[]). As you can see, the short-hand notation is the same as in C.

The If operator has the following syntax : If[test, Oper1,Oper2] Here < test > is a condition being tested. The condition < test > should in principle evaluate to True or False, in order for If to make a choice. If it evaluates to True, the first operator oper1 is evaluated, otherwise a second one. The second operator may be absent, in which case nothing is done for the False outcome (Null is returned). Since normally the arguments of the function are evaluated before the function itself, while in the case of If the operator which corresponds to True of False branch should only be evaluated after the condition is checked, we conclude that If uses non-standard evaluation.

Operators Which and Switch These operators generalize If to situations where we have to switch between several possibilities. Which is essentially a replacement for nested If statements. Switch in Mathematica resembles Switch in C, but differs from it significantly. First, it has a different (extended in a sense) functionality since it works on patterns (patterns are extremely important. We will cover them later). Also, Break[] operator is unnecessary here, and so the fall-through behavior of C Switch is not possible (patterns sort of compensate for this). Finally, in C Switch can be used in more sophisticated ways to put some entry points in the block of code -- this is not possible here. Both Which and Switch are well-explained in Mathematica Help, and we refer to it for further details regarding them.

Loops

These constructs are quite analogous to the ones in C, with the exception that the roles of comma and semicolon are interchanged with respect to C. In general, loops are not very efficient in Mathematica, and in particular, the most effective in Mathematica functional style of programming does not involve loops at all. We will give just a few examples for completeness.

For loop

For[i=1, i<5, i++, Print[i]];
1 2 3 4 5
If one needs to place several operators in the body of the loop, one can do so by just separating them with a semicolon. The same comment applies to the While loop.
i=1; While[i<=5, (Print[i];i++)]
1 2 3 4 5
And now with Do :
Do[Prnt[i],{i,5}]

In general, most Mathematica built-in functions do not introduce side effects, since they operate on a copy of the given expression. In For and While loops however, the index variables (like < i > above) will keep the final value that they had when the loop terminated, as a global value. It is a good practice to localize all loop variables inside one of the scoping constructs available in Mathematica.

a:= i^2;
Do[Print[a],{i,1,5}]
1
4
9
16
25

There are statements to realize local Goto within the loop -- Break[] and Continue[]. They work in the same way as they work in C. For example, here we will break from the Do loop after 4 iterations :

i=1;
Do[(Print["X"];If[i++ >3,Break[]]), {50}]

X X X X
However, you will get another output if you use the following code
Do[(Print["X"];If[i++ >3,Break[]]), {2}]
X X

The parentheses in this example actually represent a composite operator, which is legitimate everywhere where the single operator is. There are three scoping constructs used in Mathematica to localize variables -- Module, Block and With. Loop can be terminated using one of the following commands: Throw, Catch, Break, Continue, Return, Interrupt, and Abort.

Module does lexical scoping (localizing names).
Block does dynamic scoping (localizing values).

i = 1;
Do[(Print["X"]; If[i++ > 3, Return[i]]), {20}]
X X X X 5
Catch[Do[If[ i > 10, Throw[i]], {i, 1, 20}]]
Out[2]= 11

It turns out that programs that use loops are often inefficient in Mathematica. It is recommended to use instead functional programming functions Map, Scan, MapThread, Fold, FoldList, ... and pure functions. This makes the code cleaner and faster. Let me illustrate this on a simple example. We will compute a sum of the first 100000 natural numbers. We will first do this with a loop, and then show a program written in a functional programming style. Here is the loop version :

Timing[sm=0; Do[sm=sm+i,{i,100000}];sm]
Out[20]= {0.052992, 5000050000}
And this is a functional realization :
Timing[Apply[Plus,Range[100000]]]
Out[21]= {0.021997, 5000050000}
To rehabilitate the loops somewhat, let me mention that they can be quite efficient in cases when it is possible to use the internal compilation :
Compile[{x,{n, _Integer}}, Module[{sm=x},Do[sm=sm+i,{i,n}];sm]][0,100000] // Timing
Out[22]= {0.002999, 5.00005*10^9}

 

V. Brackets


Mathematica utilizes four different types of brackets: parentheses, single square brackets, double square brackets and the curly braces. Each type of brackets has a different meaning and purpose. Parentheses are used to change the priority or precedence of different operations, like in other programming languages; also, to group together a block of operators which we want to be considered as a single composite operator. Curly braces always mean a list. They are equivalent to a literal command List:
Clear[a,b,c];
{a,b,c} == List[a,b,c]
Out[24]= True
Single square brackets are used as building blocks for normal expressions in Mathematica. They are used to represent an arbitrary Mathematica expression as a nested tree-like structure. Finally, double square brackets are used as a shorthand notation for a Part command, which is used to deconstruct an expression and index into sub-expressions, extracting them. We have already seen an example of how this can be done.
A = List[a, b, c]
A[[2]]
Out[26]= b
Lists represent collections of objects, possibly of different type, and are very important building blocks of Mathematica programs, since any complex data structure can be built out of them. Lists can be generated dynamically during the process of program execution, and the correctly written functions work on lists of arbitrary length without taking the length of the list as an explicit parameter. This results in a quite "clean" code, which is at the same time easy to write. Another advantage of lists is that it is usually easy to debug functions that work on them.

 

Return to Mathematica page
Return to the main page (APMA0330)
Return to the Part 1 (Plotting)
Return to the Part 2 (First Order ODEs)
Return to the Part 3 (Numerical Methods)
Return to the Part 4 (Second and Higher Order ODEs)
Return to the Part 5 (Series and Recurrences)
Return to the Part 6 (Laplace Transform)
Return to the Part 7 (Boundary Value Problems)