12.010 Lecture 13
(Fall, 2007)

Slide 03: Flow control statement forms:

If[7>8,x,y] (* Here true or false is clear*)

If[x==y,a,b] (*Here the answer is neither true nor false so nothing is output*)

If[x==y,a,b,c] (* Now there is the neither true nor false option and so c is output*)

Demonstration of using the Which Function. Here a the function is linear for values less than 0, Sin[x] for values greater then 0

Plot[Which[x<0,x,x≥0,Sin[x]],{x,-2π,2π}];

Which[ 7>8,a,x<y,b,6<9,c] (*if part of the Which is neither true nor false, then the remaining which list is returned*)

(* Example of using the Switch form*)
r[x_]:=Switch[Mod[x,3],0,a,1,b,2,c]

r[4]

Clear[r]

Slide 04: Do, while loops

(* Example of using nested do loop*)
Do[Plot[Sin[n * x],{x,0,2π}],{n,1,3,2}];

(* Example of While loop *)
nn=10;While[(nn=nn-1)>5,Print[nn]]; Clear[nn];

nn = 10; While[ nn>5, Print[nn]; nn=nn-1]

(* Example of For loop.  The i++ form is i=i+1*)
For[i=1;t=x,(i^2)<10,i++,t=t+i;Print[t]]; Clear[i,t]

Slide 05: Function forms in more detail

(# + 1)&[x]  (*Form using slot number for parameter*)

(#1/#2)&[x,y] (*Form with two arguments*)

Function[z,(z^2)][{1,2,3}] (* Form using variable names are arguments*)

z  (*z has not been set in Global` context*)

(*Example of using the Map feature.  Reverse is a built in function to reverse lists*)
Reverse/@{{a,b,x },{c,d},{e,f}}

(*Example using function f*)
Clear[x]
 Sin/@(1+2 x+(x^2))

(*Use of Apply in shorthand form*)
New@@Old[a,b,c]

(*Here I can multiply all the elements in a list together*)
Times @@ {a,b,c}
mylist = { 1, 2, 3, 4, 5}; Plus @@ mylist
Clear[mylist]

Slide 08: Directories and files

Directory[]  (* lists the current direcory*)

SetDirectory["TAH_docs/12.010"] (*This will change to a new direcory*)

FileNames["*.nb"]  // TableForm(* This will list all the .nb files in the directory*)