Getting Started with Mathematica (II)
Functions (built-in, user defined)
Plotting options
Conditional Statements (If, Switch)
Loops (For, While, Do)
Control structures (Break, Return)

More plotting commands

ContourPlot[f[x, y] == g[x, y], {x, xmin, xmax}, {y, ymin, ymax}]
plots the contour of the region in the xy plane where f[x, y] is equal to g[x, y].

ContourPlot[x^2+y^2==1/4,{x,-1,1},{y,-1,1} ]

ContourPlot[{(x^2+y^2)^2==x^2-y^2,(x^2+y^2)^2==2 x y},{x,-1,1},{y,-1,1}, PlotLegends->{"First plot: ((x^2)+(y^2))^2 = (x^2)-(y^2)", "Second plot: ((x^2)+(y^2))^2 = 2xy"} ]

ParametricPlot[{x[t], y[t]}, {t, tmin, tmax}]
generates a parametric plot of a curve with x and y coordinates as a function of t.

ParametricPlot[{2Cos[t],Sin[t]},{t,0,2Pi}]

3D Plots

Plot3D[f, {x, xmin, xmax}, {y, ymin, ymax}]
generates a three dimensional plot of f as a function of x and y.

Plot3D[Sin[x+y^2],{x,-3,3},{y,-2,2}]

There are many options that one can use with a 3D plot. For a full list, see http://reference.wolfram.com/language/ref/Plot3D.html. For instance, one can use the option BoundaryStyle to color the boundary of the region.

Plot3D[Sin[x+y^2],{x,-3,3},{y,-2,2}, BoundaryStyle->{Thick, Blue}]

Let' s generate the same 3D plot as before, assign it to a variable P, and then export it as pdf.

P=Plot3D[Sin[x+y^2],{x,-3,3},{y,-2,2}, Mesh->None, ColorFunction->"Rainbow", Boxed->False, Axes->False, MaxRecursion->15]
(* we want to save the graphics P to a picture that we can use later *)
SetDirectory[NotebookDirectory[]];
Export["mypicture.pdf",P];

The graphical 3 D object obtained as output of the Plot3D command Let' s now rotate the picture, save a couple of positions, create a list of these positions and export them to a gif file. Mathematica will automatically create an animated gif out of them.

face1=;
face2=;
face3 = ;
face4=;
views = {face1, face2, face3, face4};
Export["animated_pic.gif",views,"DisplayDurations"->.2];

The condition operator /;

Many functions are only valid if certain conditions are met. Mathematica can handle such situations. The Condition operator (/;) can be used to make sure a pattern is used only if a condition is met. You can also place the condition operator in the argument of the function, or right after the body of the function.

f0[x_ /; x<0]:= 0 
f0[0]:=10
f0[1]:=20
f0[x_ /; x>1] := Log[x]

f1[x_,c_]:= 0 /; x ≤c
f1[x_,c_] := (x-c)^3 /; x>c

You can list all definitions associated with a function as before, using ? followed by the name of the function. In particular, this will also show the order in which the definitions are applied.

?f1

Plot[f1[x,3],{x,0,7}]
RevolutionPlot3D[f1[x,3],{x,0,7}, RevolutionAxis->{0, 0, 1}]

Some functions only make sense for some type of input, like integers.

IntegerQ[expr]    true if expr is an integer, false otherwise
EvenQ[expr]    true is expr is an even number, false otherwise
OddQ[expr]    odd number
PrimeQ[expr]    prime number
NumberQ[expr]   explicit number of any kind
NumericQ[expr]    numeric quantity
VectorQ[expr]    a list representing a vector
MatrixQ[expr]   a list of lists representing a matrix
FreeQ[expr, form]   form matches nothing in expr
MatchQ[expr, form]   expr matches the pattern form
TrueQ[expr]  tests whether expr is true

f2[x_ ]:= x^3
f3[x_ /;  NumberQ[x]]:= x^3

Evaluate the function f2

f2[3]
f2[{1,2,3}]

Evaluate the function f3

f3[3]
f3[{1,2,3}]

Conditional Statements

Elementary numerical relations :
      ==  (is equal to)         !=  (is not equal to) 
       <   (is less than)       <=  (is less than or equal to) 
       >  (is greater than)   >=  (is greater than or equal to)

Elementary logical relations :
      || (or)     && (and)    ! (not)

3==4

If[condition, t, f] - the “If” command returns t if condition evaluates to true and 
                                                                 f if condition evaluates to false.

a=3; b=4;
If[a>b,a,b]

x=2; If[x==0,Print["x is 0"], Print["x is different from 0"]]

Exercise : Rewrite the function f1[x_,c_], from the previous section, using only the If[...] command.

Case Study :

The following functions f, g, h do the same thing, but when we plot the functions, we notice some loss of accuracy when using f.

Clear[f,g,h]
f[x_]:=1 /; 0<x≤Pi
f[x_]:=-1 /; -Pi≤x<0
Plot[f[x],{x,-1,1},PlotLabel->"f"]

g[x_]:=Piecewise[{{1,0<x≤Pi},{-1, -Pi≤x<0}}]
Plot[g[x],{x,-1,1},PlotLabel->"g"]

h[x_]:=If[0<x≤Pi,1,-1]
Plot[h[x],{x,-1,1},PlotLabel->"h"]

More on Conditional Statements

Sometimes we only need to perform an action when the condition is true, so we can use the command If[..] with only two arguments.

x=0; If[x==0,Print["x is 0"]]

If we want to execute more commands when x is 0, we put a semicolon ; between the successive commands.

x=0; If[x==0, Print["x is 0."]; x=x+2; Print["We have assigned the value 2 to x."], Print["x is not 0"]]

Switch[expr,form1,value1,form2,value2,…,_,default]  - compares expr with each of the form form1, form 2, ... , giving the value associated with the first form it matches. If expr does not match any form, then the default value is returned.

expr = 3;
Switch[expr,
             1,Print["expr is 1"], 
             2,Print["expr is 2"],
             3,Print["expr is 3"],
	    _, Print["expr has some other value"]]

Loops and control structures

Do[expr,{i,max}] - evaluates expr repetitively, with the local variable i varying from 1 (one) to max in steps of 1(one)
Do[expr,{i,min,max,di}] - evaluates expr with i varying from min to max in steps of di.
Do[expr,{i,list}] - evaluates expr with i taking on values from a list
Do[expr,{n}] - evaluates expr n times

Examples with Do:

Print the first 10 positive integers:

Do[Print[i],{i,10}]

Print only the odd integers between 4 and 10:

Do[Print[i],{i,5,10,2}]

Do[If[Mod[i,2]!=0,Print[i]],{i,4,10,1}]

Loops and control structures (Break, Return)

We can use some control flow functions to terminate the loop:
Break[ ] - causes the loop to terminate
Return[expr] - causes the loop/function to terminate and returns the value expr

Print the first odd integer between 4 and 10

Do[If[Mod[i,2]!=0,Print[i];Break[]],{i,4,10,1}]

Print the first odd integer between 4 and 10

Do[If[Mod[i,2]!=0,Return[i]],{i,4,10,1}]

Loops (For)

For[start,test,incr,body] - evaluates start, then repetitively evaluates body and incr, 
                                      until test fails

For[i=1, i<4,i++,Print[i]]

First i is assigned the value 1. As long as the condition i < 5 remains true, i is incremented by 1 (i++ is just a shortening for i = i + 1) and the body of the function For is executed (that is, we print the integer i).

Loops (While)

While[condition, body] - evaluates body repetitively, so long as condition is True

n=17; While[(n=Floor[n/2])≠0, Print[n]]

Even if the last value printed by the While function is 1, the current value of n is not 1, as one may assume, but 0. This value was not printed when we ran the While command, because when n is 0, the condition n != 0 is false, so the body of the function While (which would have been Print[0]) is not executed.

n

In the Wolfram Language, both While and For always evaluate the loop test before evaluating the body of the loop. As soon as the loop test fails to be True, While and For terminate. The body of the loop is thus only evaluated in situations where the loop test is True.

While[False, Print["False"]]

The command While[False, Print["False"]] does not print anything, because the test condition is always False, so the body of the function is never executed.

The functions While and For in the Wolfram Language are similar to the control structures While and For in languages such as C++. Notice, however, that there are a number of important differences. For example, the roles of comma and semicolon are reversed in Wolfram Language For loops relative to C++ language ones.