2301520 Fundmentals of AMCS
Assignments, Rules, Functions

Section 6 : Assignments and Rules

6.1 Assignments: Immediate Versus Delayed

random1=RandomReal[]

random2:=RandomReal[]

Table[random1,{5}]

Table[random2,{5}]

6.2 Multiple Assignments

x=y=3

{x,y}

{x,y}={11,23}

x

y

Clear[x,y]

6.3 Rules: Immediate Versus Delayed

a+2b/.a->3

a+2b/.{a->3,b->4}

n=1; Table[x,{5}]/.x->n++

n=1;Table[x,{5}]/.x:>n++

Clear[x,y,n]

{1,2}/.{x_,y_}->{y,x}

{{1,2},{3,4},{5,6}}/.{x_,y_}->x+y

f[a^b]/.f[x:_^n_]->p[x,n]

Section 7 : Functions

7.1 A Simple Function

square[x_]:=(x^2)

square[3]

square[1+2x]

f[x_,y_]:=(x^2)+(y^2)

f[a,3]

polarTransform[r_,θ_]:=(x=r Cos[θ];y=r Sin[θ];{x,y})

polarTransform[10,(π/6)]

polarTransform[{10,(π/6)}]

polarTransform[{r_,θ_}]:=polarTransform[r,θ]

polarTransform[r_]:= "Only one argument! Sorry, can't do. I need two.";

polarTransform[10,(π/6)]

polarTransform[{10,(π/6)}]

polarTransform[2]

polarTransform[2,3,4]

Remove[f];
f[x_]:=If[Element[x,Rationals],1,0]

{f[1],f[π],f[(1/2)],f[(Sqrt[2])]}

7.2 Type Checking

fac[n_Integer]:=(∏_(k=1)^n)k
fac[10]

fac[1.5]

Clear[fac]

fac[n_Integer/;n≥0]:=(∏_(k=1)^n)k

fac[-1]

fac[0]

7.3 Conditional Evaluation

Clear[f]

f[x_]:=1/;-1≤x≤1

f[x_]:=0/;Abs[x]≥1

Plot[f[x],{x,-3,3},PlotStyle->{Hue[0],Thickness[0.01]}]

Clear[f]

f[x_/;-1≤x≤1]:=1

f[x_/;Abs[x]≥1]:=0

Plot[f[x],{x,-3,3},PlotStyle->{Hue[0],Thickness[0.01]}]

Plot[Which[x>0, (x^2), x≤0, -x],{x,-2,2}]

grade[x_]:=Which[x≥90,"A",x≥80,"B",x≥70,"C",x≥60,"D",True,"F"];
grade[50]

7.4 Default Values

Range[10,15]

Range[10]

myRange[first_:0,last_]:=Range[first,last]

myRange[10,15]

myRange[10]

7.5 Documenting Functions

?myRange

myRange::usage="myRange[n] generates the list {0,1,2,...,n}.myRange[m,n] generats the list {m,m+1,m+2,...,n}."

?myRange

??myRange

7.6 Pure Functions

Function[x,(x^2)][3]

Function[{x,y},(x^2)+(y^2)][a,b]

((#)^2)&[3]

((#1)^2)+((#2)^2)&[a,b]

7.7 Attributes

Attributes[Plot]

Clear[f];Attributes[f]

f[{1,2,3}]

SetAttributes[f,Listable]

f[{1,2,3}]

Attributes[Table]

RandomReal[{0,1},5]

Table[Evaluate[RandomReal[]],{5}]

7.8 Listable and Map

Remove[f]

f[{1,2,3,4}]

Map[f,{1,2,3,4}]

f/@{1,2,3,4}

Map[f, (x^2) + 2 x+ 1]

Map[f,{{1,2},{{3,4},{5,6}}}]

f[{1,2,3},{4,5,6}]

SetAttributes[f,Listable]

f[{1,2,3}]

f[{1,2,3},{4,5,6}]

7.9 Recurrence Relations

Remove[f]

f[1]=f[2]=1;f[n_]:=f[n-1]+f[n-2]  (* Fibonacci Sequence *)

Table[f[n],{n,30}]

7.10 Periodic Functions

Remove[f];
f[x_/;0≤x<1]:=1;
f[x_/;1≤x<2]:=0;
f[x_/;x≥2]:=f[x-2];
f[x_/;x<2]:=f[x+2];

Plot[f[x],{x,-4,4},PlotStyle->{Hue[0],Thickness[0.01]}]