Course 7 : Programming Structures

Conditional structures

If

a=100
If[a>0, Print["a>0"], Print["a<0"]];

If[a>0, Print["a>0"], If[a<0,Print["a<0"], Print["a=0"]]];

If[a>0, b=Sqrt[a]; Print["Sqrt(a)=",b], b=Sqrt[-a]; Print["Sqrt(a)=i",b]; a=a^2];

Which

x=12;
Which[x<10, "small", x≥10&&x<100, "medium", x>100, "large"]

Which[x<10, a="small"; b=x, x≥10&&x<100, a="medium"; b=x^2, x>100, a="large";b=x^3]; 
Print[a,"   ",b]

Switch

a=1;
mytype=Switch[a,0,"no type",1,"small", 2, "medium", 3, "large", 4,"extra large"]

Conditional (piecewise) functions

f[x_]:=(x^2)/;x>0
f[x_]:=-(x^2)/;x≤0

y=f[-2]

g[x_]=Piecewise[{{x^2+1,x>0},{-x^2-1, x<0},{0,x==0}}]
g[0]
Plot[g[x],{x,-2,2}]

Loops

For

x=1;
For[k=1,k<10,k=k+0.5, x+=x/k; Print[k,"  ",x]]

While

x=100;
Print["Αρχική τιμή του x=",x]
While[x>2, x=x/2; Print[x]]

Do

x=-2;
Do[x=x^2+1, {5}]
x

a=1;
Do[x=(a+1)^2;Print[x]; a++, {5}]

x=1;
Do[x=k/x, {k,1,15,0.5}]
x

Nested functions

Clear[g, x, a, y]
f[x_] = x^2/2;
y = x
Do[y = f[y]; Print[y], {4}]

Nest[g, x, 4]

Nest[f, x, 4]

NestList[f, x, 4]

Programming Procedures:Modules and Blocks

Module :Localizing names of variables

minmax[data_List]:=Module[
{min=data[[1]], max=data[[1]],n,i}, (* declare local vars *)
n=Length[data];  (* body of procedure *)
For[i=2,i≤n,i++, If[ min>data[[i]],min=data[[i]]];
If[ max<data[[i]],max=data[[i]]]];
{min,max} (* results *)
]

(* apply module *)
Clear[n,i,ll]
aa={2,3,-1,2,9,10,4};
ll=minmax[aa]
Print["n=",n,"   i=",i]
Print["min=",ll[[1]],"   max=",ll[[2]]]

Block : local values

Clear[x,y]
y=x^2;
Print["Before Block it is x=",x,"   and y=",y]

Block[{x=5},Print["in block it is x=",x, " and y=",y]]

Print["on exit it is x=",x,"   and y=",y]

(*try Module instead of Block*)
Clear[x,y]
y=x^2;
Module[{x=5},Print["in Module it is x=",x, " and y=",y]]  
Print["on exit it is x=",x,"   and y=",y]

Dynamic Processes

Dynamic

a=3;
Dynamic[Plot[x^4-a x^2-1,{x,-2,2}]]

(* change value of a *)
a=-2

Manipulate

Manipulate[Plot[x^4-a x^2-1,{x,-2,2}], {a,-2,2}]

Manipulate[a*b,{a,0,10},{b,0,10}]

Animate

Animate[Plot[x^4-a x^2-1,{x,-2,2}], {a,-3,3}]

Exercise : Export the above animation as video