Experiments With MatLab Moled 2011

144
Experiments with MATLAB Cleve Moler October 4, 2011 ii Copyright 2011 Cleve Moler Electronic edition published by MathWorks, Inc. http://www.mathworks.com/moler

Transcript of Experiments With MatLab Moled 2011

Page 1: Experiments With MatLab Moled 2011

Experiments

withMATLAB

Cleve

Moler

October

4,2011

ii

Cop

yrigh

t2011

Cleve

Moler

Electronic

editionpublished

byMathWorks,

Inc.

http://www.mathworks.com/moler

Page 2: Experiments With MatLab Moled 2011

Contents

Pre

face

iii

1Itera

tion

1

2FibonacciNumbers

17

3Calendars

and

Clock

s33

4M

atrices

45

5LinearEquations

63

6Fra

cta

lFern

75

7Google

PageRank

83

8ExponentialFunction

97

9T

Puzzle

113

10

Magic

Square

s123

11

TicTacToeM

agic

141

12

GameofLife

151

13

Mandelbro

tSet

163

14

Sudoku

183

15

Ord

inary

Differe

ntialEquations

199

16

Pre

dato

r-Pre

yM

odel

213

17

Orb

its

221

18

Shallow

WaterEquations

241

iii

ivCon

tents

19

MorseCode

247

20

Music

263

Page 3: Experiments With MatLab Moled 2011

Experiments

withMATLAB

R ©

Cleve

Moler

Copyrightc ©

2011CleveMoler.

Allrights

reserved.Nopart

ofthis

e-bookmay

bereproduced,stored,ortrans-

mitted

inan

ymanner

withoutthewritten

permission

oftheau

thor.

For

more

inform

ation,contact

[email protected].

Theprogramsdescribed

inthis

e-bookhavebeenincluded

fortheirinstructional

value.

Theseprogramshavebeentested

withcare

butare

notguaranteed

foran

yparticularpurpose.

Theau

thordoes

notoffer

anywarranties

orrepresentations,

nordoes

heacceptanyliabilitieswithrespectto

theuse

oftheprograms.

These

programsshould

notberelied

onas

thesolebasisto

solveaproblem

whose

incorrect

solutioncould

result

ininjury

topersonorproperty.

Matlab

R ©is

aregisteredtradem

ark

ofMathWorks,

Inc.

TM.

For

more

inform

ationaboutrelevantMathWorkspolicies,see:

http://www.mathworks.com/company/aboutus/policies_statements

October

4,2011

iiCon

tents

Page 4: Experiments With MatLab Moled 2011

Preface

Figure

1.exmguiprovides

astartingpointforsomeoftheexperimen

ts.

Welcometo

Experim

ents

withMATLAB.This

isnotaconventional

book

.It

iscu

rrentlyavailable

only

via

theInternet,atnocharge,

from

http://www.mathworks.com/moler

Theremay

eventuallybeahardcopyedition,butnotrightaw

ay.

AlthoughMatlabis

now

afullfledged

TechnicalComputingEnvironment,

itstarted

inthelate

1970sasasimple

“Matrix

Laboratory”.Wewantto

build

onthislaboratory

traditionbydescribingaseries

ofexperim

ents

involvingapplied

mathem

atics,technicalcomputing,andMatlabprogramming.

iii

ivPreface

Weexpectthatyou

alreadyknow

somethingab

outhighschoollevel

material

ingeometry,algebra,an

dtrigonometry.

Wewillintroduce

ideasfrom

calculus,

matrix

theory,an

dordinary

differentialequations,

butwedonotassumethatyou

havealreadytaken

courses

inthesubjects.

Infact,theseexperim

ents

areuseful

supplements

tosuch

courses.

Wealsoexpectthatyou

havesomeexperience

withcomputers,perhapswith

wordprocessors

orspreadsheets.If

you

know

somethingaboutprogrammingin

languages

likeC

orJava,thatwillbehelpful,butnotrequired

.Wewillintroduce

Matlabbyway

ofexamples.

Manyoftheexperim

ents

involveunderstandingand

modifyingMatlabscripts

andfunctionsthatwehavealreadywritten

.You

should

haveaccess

toMatlab

andto

ourexmtoolbox

,thecollection

ofprogramsan

ddata

thatare

described

inExperim

ents

withMATLAB.Wehop

eyou

willnoton

lyuse

theseprograms,butwillreadthem

,understandthem

,modify

them

,an

dim

prove

them

.Theexmtoolbox

istheapparatusin

our“Laboratory”.

Youwillwantto

haveMatlabhandy.

Forinform

ationab

outtheStudent

Version,see

http://www.mathworks.com/academia/student_version

For

anintroductionto

themechanicsofusingMatlab,seethevideosat

http://www.mathworks.com/academia/student_version/start.html

For

documentation,including“GettingStarted”,see

http://www.mathworks.com/access/helpdesk/help/techdoc/matlab.html

For

usercontributedprograms,programmingcontests,andlinksinto

theworld-w

ide

Matlabcommunity,

checkout

http://www.mathworks.com/matlabcentral

Toget

started,dow

nloadtheexmtoolbox

,use

pathtoolto

addexmto

the

Matlabpath,andrunexmguito

generate

figure

1.Youcanclickon

theiconsto

preview

someof

theexperim

ents.

Youwillwantto

makefrequentuse

oftheMatlabhelpanddocumentation

facilities.Toquickly

learn

how

touse

thecommandorfunctionnamed

xxx,enter

helpxxx

For

more

extensiveinform

ationab

outxxx,use

docxxx

Wehopeyou

willfindtheexperim

ents

interesting,andthatyouwilllearn

how

touse

Matlabalongtheway.Each

chapterconcludes

witha“Recap”section

thatis

actuallyanexecutable

Matlabprogram.Forexample,you

canreview

the

Magic

Squareschapterbyentering

magic_recap

Page 5: Experiments With MatLab Moled 2011

Preface

v

Betteryet,enter

editmagic_recap

andruntheprogram

cell-by-cellbysimultaneouslypressingtheCtrl-Shift-Enter

keys.A

fairly

new

Matlabfacility

isthepublishcommand.You

canget

anicely

form

atted

web

pageaboutmagic_recapwith

publishmagic_recap

Ifyou

wantto

concentrate

on

learningMatlab,makesure

you

read,run,and

understandtherecaps.

CleveMoler

October

4,2011

viPreface

Page 6: Experiments With MatLab Moled 2011

Chapter1

Iteration

Iterationis

akeyelem

entin

much

oftechnicalcomputation.Examplesinvolvingthe

Golden

Ratiointroduce

theMatlabassignmen

tstatemen

t,forandwhileloops,

andtheplotfunction.

Start

bypickinganumber,an

ynumber.Enteritinto

Matlabbytyping

x=yournumber

This

isaMatlabassignmen

tstatemen

t.Thenumber

youchose

isstoredin

the

variablexforlateruse.For

example,ifyoustart

with

x=

3

Matlabrespondswith

x=

3

Next,enterthis

statement

x=

sqrt(1

+x)

Theabbreviationsqrtis

theMatlab

nameforthesquare

rootfunction.

The

quantity

ontheright,√ 1

+x,iscomputedandtheresultstoredback

inthevariable

x,overridingthepreviousvalueof

x.

Somew

hereon

yourcomputerkeyboard,probably

inthelower

rightcorner,

you

should

beableto

findfourarrow

keys.

Theseare

thecommandlineeditingkeys.

Theup-arrow

key

allow

syou

torecallearliercommands,includingcommandsfrom

Copyright

c ©2011CleveMoler

Matlab

R ©is

aregisteredtradem

ark

ofMath

Works,

Inc.

TM

October

4,2011

1

2Chapter1.

Iteration

previoussessions,

andtheother

arrowskeysallow

youto

revisethesecommands.

Use

theup-arrow

key,follow

edbytheenteror

return

key,to

iterate,or

repeatedly

execute,this

statement:

x=

sqrt(1

+x)

Hereis

whatyou

getwhen

you

start

withx=3.

x=

3

x=

2

x=

1.7321

x=

1.6529

x=

1.6288

x=

1.6213

x=

1.6191

x=

1.6184

x=

1.6181

x=

1.6181

x=

1.6180

x=

1.6180

Thesevalues

are

3,√ 1

+3,√ 1

+√ 1

+3,

√ 1+

√ 1+

√ 1+3,andso

on.After

10steps,

thevalueprintedremainsconstantat1.6180.Try

severalother

starting

values.Try

iton

acalculatorifyou

haveon

e.Youshould

findthatnomatter

where

you

start,youwillalwaysreach

1.6180in

abouttensteps.

(May

beafew

more

will

berequired

ifyouhaveaverylargestartingvalue.)

Matlabis

doingthesecomputationsto

accuracy

ofabout16

decim

aldigits,

butis

displayingonly

five.

Youcanseemore

digitsbyfirstentering

formatlong

andrepeatingtheexperim

ent.

Hereare

thebeginningandendof30stepsstarting

atx=

3.

x=

3

Page 7: Experiments With MatLab Moled 2011

3

x=

2

x=

1.732050807568877

x=

1.652891650281070

....

x=

1.618033988749897

x=

1.618033988749895

x=

1.618033988749895

After

aboutthirty

orso

steps,

thevaluethatis

printeddoesn’t

changeanymore.

You

havecomputed

oneof

themost

famousnumbersin

mathem

atics,φ,the

Golden

Ratio.

InMatlab,an

dmost

other

programminglanguages,theequals

signis

the

assignmentoperator.

Itsayscompute

thevalueon

therightandstore

itin

the

variable

ontheleft.So,thestatement

x=

sqrt(1

+x)

takes

thecurrentvalueofx,computessqrt(1+

x),andstorestheresult

back

inx.

Inmathem

atics,theequals

signhasadifferentmeaning.

x=

√ 1+

x

isanequation.A

solutionto

such

anequationisknow

nas

afixedpoint.

(Becareful

notto

confuse

themathem

aticalusageoffixedpointwiththecomputerarithmetic

usageoffixedpoint.)

Thefunctionf(x)=

√ 1+

xhasexactly

onefixed

point.

Thebestway

tofindthevalueofthefixed

pointis

toavoid

computers

alltogether

andsolvethe

equationusingthequadraticform

ula.Take

alookatthehandcalculationshow

nin

figure

1.1.Thepositiverootofthequadraticequationis

theGolden

Ratio.

φ=

1+

√ 5

2.

YoucanhaveMatlabcompute

φdirectlyusingthestatement

phi=

(1

+sqrt(5))/2

Withformatlong,thisproducesthesamevalueweobtained

withthefixed

point

iteration,

phi=

1.618033988749895

4Chapter1.

Iteration

Figure

1.1.Compute

thefixedpointby

hand.

−10

12

34

−1

−0.50

0.51

1.52

2.53

3.54

Figure

1.2.A

fixedpointatφ=

1.6180.

Figure

1.2isourfirstexample

ofMatlabgraphics.

Itshow

stheintersection

ofthegraphsofy=

xandy=

√ 1+

x.Thestatement

x=

-1:.02:4;

generatesavectorxcontainingthenumbersfrom

-1to

4in

stepsof.02.

The

statements

y1

=x;

y2

=sqrt(1+x);

plot(x,y1,’-’,x,y2,’-’,phi,phi,’o’)

Page 8: Experiments With MatLab Moled 2011

5

produce

afigure

thathasthreecomponents.Thefirsttw

ocomponents

are

graphs

ofxand√ 1

+x.The’-’argumenttellstheplotfunctionto

drawsolidlines.The

last

componentin

theplotis

asingle

pointwithbothcoordinatesequalto

φ.The

’o’tellstheplotfunctionto

draw

acircle.

TheMatlabplotfunctionhasmanyvariations,

includingspecifyingother

colors

andlinetypes.You

canseesomeofthepossibilitieswith

helpplot

φ

φ −

1

1

1

Figure

1.3.Thegolden

rectangle.

TheGolden

Ratioshow

supin

manyplacesin

mathem

atics;we’llseeseveral

inthis

book.TheGolden

Ratiogets

itsnamefrom

thegolden

rectangle,show

nin

figure

1.3.Thegolden

rectangle

hastheproperty

thatremov

ingasquare

leaves

asm

aller

rectangle

withthesameshape.

Equatingtheaspectratiosoftherectangles

gives

adefiningequationforφ:

1 φ=

φ−

1

1.

Multiplyingboth

sides

ofthisequationbyφproducesthesamequadraticpolynomial

equationthatweobtained

from

ourfixed

pointiteration.

φ2−φ−1=

0.

Theup-arrow

key

isaconvenientway

torepeatedly

execute

asinglestatement,

orseveralstatements,separatedbycommasorsemicolons,

onasingle

line.

Two

more

pow

erfulconstructsare

theforloopandthewhileloop.Aforloopexecutes

ablock

ofcodeaprescribed

number

oftimes.

x=

3

fork

=1:31

x=

sqrt(1

+x)

end

6Chapter1.

Iteration

produces32lines

ofoutput,on

efrom

theinitialstatementan

donemore

each

time

throughtheloop.

Awhileloopexecutesablock

ofcodean

unknow

nnumber

oftimes.Termi-

nationiscontrolled

byalogicalexpression,whichevaluatesto

trueor

false.Here

isthesimplest

whileloopforou

rfixed

pointiteration.

x=

3

whilex

~=

sqrt(1+x)

x=

sqrt(1+x)

end

This

producesthesame32

lines

ofoutputastheforloop.How

ever,this

codeis

open

tocriticism

fortw

oreasons.

Thefirstpossible

criticism

involves

theterm

i-nationcondition.Theexpressionx

~=

sqrt(1+x)is

theMatlabway

ofwriting

x�=

√ 1+

x.W

ithexact

arithmetic,xwou

ldnever

beexactly

equalto

sqrt(1+x),

theconditionwou

ldalway

sbetrue,

andtheloopwou

ldrunforever.How

ever,like

most

technicalcomputingenvironments,Matlabdoes

notdoarithmetic

exactly.

Inorder

toeconomizeonbothcomputertimeandcomputermem

ory,Matlabuses

floatingpointarithmetic.Eventuallyourprogram

producesavalueofxforwhich

thefloatingpointnumbersxandsqrt(1+x)are

exactly

equalandtheloopterm

i-nates.

Expectingexact

equality

oftw

ofloatingpointnumbersisadelicate

matter.

ItworksOK

inthisparticularsituation,butmay

notworkwithmore

complicated

computations.

Thesecondpossiblecriticism

ofoursimplewhileloopisthatitisineffi

cient.

Itevaluatessqrt(1+x)tw

iceeach

timethroughtheloop

.Hereisamore

complicated

version

ofthewhileloopthatavoidsbothcriticisms.

x=

3

y=

0;

whileabs(x-y)>

eps(x)

y=

x;

x=

sqrt(1+x)

end

Thesemicolonsat

theendsoftheassignmentstatements

involvingyindicate

that

noprintedoutputshould

result.Thequantity

eps(x),isthespacingof

thefloating

pointnumbersnearx.Mathem

atically,

theGreek

letter

ε,orepsilon,often

rep-

resents

a“small”quantity.This

versionoftheloop

requires

only

onesquare

root

calculationper

iteration,butthatis

overshadow

edbythead

ded

complexityof

the

code.

Both

whileloopsrequireaboutthesameexecutiontime.

Inthissituation,I

preferthefirstwhileloopbecause

itis

easier

toreadan

dunderstand.

HelpandDoc

Matlabhasextensiveon-linedocumentation.Statements

like

helpsqrt

helpfor

Page 9: Experiments With MatLab Moled 2011

7

providebrief

descriptionsof

commandsandfunctions.

Statements

like

docsqrt

docfor

providemore

extensivedocumentationin

aseparate

window

.Oneob

scure,butveryim

portant,helpentryisab

outthevariouspunctuation

marksandspecialcharactersusedbyMatlab.Takealooknow

at

helppunct

docpunct

You

willprobably

wan

tto

return

tothis

inform

ation

asyou

learn

more

abou

tMatlab.

Numbers

Numbersareform

edfrom

thedigits0

through9,an

optionaldecim

alpoint,

aleading+or-sign,an

optionalefollow

edbyaninteger

forapow

erof10

scaling,

andan

optionalior

jfortheim

aginary

part

ofacomplexnumber.Matlabalso

know

sthevalueof

π.Herearesomeexamplesofnumbers.

42

9.6397238

6.0221415e23

-3+4i

pi

Assignmen

tstatemen

tsandnames

Asimple

assignmentstatementconsistsofaname,

an=

sign,andanumber.The

names

ofvariables,functionsan

dcommandsare

form

edbyaletter,follow

edbyan

ynumber

ofupper

andlower

case

letters,

digitsandunderscores.

Single

character

names,likexandN,an

danglicizedGreek

letters,

likepiandphi,are

often

used

toreflectunderlyingmathem

aticalnotation.Non-m

athem

aticalprogramsusually

employlongvariable

names.Underscoresan

daconventionknow

nascamel

casing

are

usedto

create

variable

names

outofseveralwords.

x=

42

phi=

(1+sqrt(5))/2

Avogadros_constant=

6.0221415e23

camelCaseComplexNumber=

-3+4i

Exp

ressions

Pow

eris

denoted

by^and

hasprecedence

over

all

other

arithmetic

operations.

Multiplicationanddivisionareden

otedby*,/,and\andhaveprecedence

over

additionandsubtraction,Additionandsubtractionare

denotedby+and-and

8Chapter1.

Iteration

havelowestprecedence.

Operationswith

equalprecedence

are

evaluated

left

toright.

Parentheses

delineate

subexpressionsthatareevaluatedfirst.

Blankshelp

readability,

buthavenoeff

ectonprecedence.

All

ofthefollow

ingexpressionshavethesamevalue.

Ifyou

don’t

already

recognizethis

value,

youcanaskGoogle

abou

titsim

portance

inpopularculture.

3*4+

5*6

3*

4+5

*6

2*(3+

4)*3

-2^4+

10*29/5

3\126

52-8-2

Rec

ap

%%

Iteration

Chapter

Recap

%This

is

an

executable

program

that

illustrates

the

statements

%introduced

in

the

Iteration

chapter

of

"Experiments

in

MATLAB".

%You

can

run

it

by

entering

the

command

% %iteration_recap

% %Better

yet,

enter

% %edit

iteration_recap

% %and

run

the

program

cell-by-cell

by

simultaneously

%pressing

the

Ctrl-Shift-Enter

keys.

% %Enter

% %publish

iteration_recap

% %to

see

aformatted

report.

%%

Help

and

Documentation

%help

punct

%doc

punct

%%

Format

formatshort

100/81

formatlong

100/81

formatshort

Page 10: Experiments With MatLab Moled 2011

9

formatcompact

%%Names

and

assignment

statements

x=

42

phi=

(1+sqrt(5))/2

Avogadros_constant=

6.0221415e23

camelCaseComplexNumber=

-3+4i

%%Expressions

3*4+

5*6

3*

4+5

*6

2*(3+

4)*3

-2^4+

10*29/5

3\126

52-8-2

%%Iteration

%Use

the

up-arrow

key

to

repeatedly

execute

x=

sqrt(1+x)

x=

sqrt(1+x)

x=

sqrt(1+x)

x=

sqrt(1+x)

%%For

loop

x=

42

fork

=1:12

x=

sqrt(1+x);

disp(x)

end

%%While

loop

x=

42;

k=

1;

whileabs(x-sqrt(1+x))>

5e-5

x=

sqrt(1+x);

k=

k+1;

end

k

%%Vector

and

colon

operator

k=

1:12

x=

(0.0:

0.1:

1.00)’

%%Plot

x=

-pi:

pi/256:

pi;

y=

tan(sin(x))

-sin(tan(x));

10Chapter1.

Iteration

z=

1+

tan(1);

plot(x,y,’-’,pi/2,z,’ro’)

xlabel(’x’)

ylabel(’y’)

title(’tan(sin(x))-

sin(tan(x))’)

%%

Golden

Spiral

golden_spiral(4)

Exe

rcises

1.1

Expressions.

Use

Matlabto

evaluate

each

ofthesemathem

aticalexpressions.

432

−34

sin1

4(32)

(−3)

4sin1◦

(43)2

4√ −3sin

π 34√ 32

−2−4/3

(arcsin1)/π

You

canget

started

with

help^

helpsin

1.2

Tem

perature

conversion.

(a)Write

aMatlabstatementthatconvertstemperature

inFah

renheit,f,to

Cel-

sius,c. c=somethinginvolvingf

(b)Write

aMatlabstatementthatconverts

temperature

inCelsius,c,to

Fah

ren-

heit,f. f=somethinginvolvingc

1.3

Barn-m

egaparsec.A

barn

isaunit

ofareaem

ployedbyhighenergyphysicists.

Nuclearscatteringexperim

ents

tryto

“hit

thesideof

abarn”.A

parsec

isaunit

oflength

employed

byastronomers.

Astarat

adistance

ofoneparsec

exhibits

atrigonometricparallaxof

onearcsecondastheEarthorbitstheSun.

Abarn-

megaparsec

istherefore

aunit

ofvolume–averylongskinnyvolume.

Abarn

is10

−28square

meters.

Amegaparsec

is106parsecs.

Aparsec

is3.262light-years.

Alight-yearis

9.461

·101

5meters.

Acubic

meter

is106milliliters.

Amilliliteris

1 5teaspoon.

Page 11: Experiments With MatLab Moled 2011

11

Express

onebarn-m

egaparsec

inteaspoons.

InMatlab,theletter

ecanbeused

todenote

apow

erof10expon

ent,so

9.461·101

5canbewritten

9.461e15.

1.4

Complexnumbers.W

hathappensifyoustart

withalargenegativevalueofx

andrepeatedly

iterate

x=

sqrt(1

+x)

1.5

Comparison.W

hichis

larger,πφor

φπ?

1.6

Solvingequations.

Thebestway

tosolve

x=

√ 1+

x

or

x2=

1+

x

isto

avoid

computers

alltogether

andjust

doit

yourselfbyhand.But,

ofcourse,

Matlabandmost

other

mathem

aticalsoftwaresystem

scaneasily

solvesuch

equa-

tions.

Hereare

severalpossible

waysto

doitwithMatlab.Start

with

formatlong

phi=

(1

+sqrt(5))/2

Then,foreach

method,explain

whatis

goingonandhow

theresultingxdiffers

from

phiandtheother

x’s.

%roots

helproots

x1

=roots([1

-1

-1])

%fsolve

helpfsolve

f=

@(x)

x-sqrt(1+x)

p=

@(x)

x^2-x-1

x2

=fsolve(f,

1)

x3

=fsolve(f,

-1)

x4

=fsolve(p,

1)

x5

=fsolve(p,

-1)

%solve

(requires

Symbolic

Toolbox

or

Student

Version)

helpsolve

helpsyms

symsx

x6

=solve(’x-sqrt(1+x)=0’)

x7

=solve(x^2-x-1)

12Chapter1.

Iteration

1.7

Sym

bolicsolution.Ifyou

havetheSymbolicToolbox

orStudentVersion,explain

whatthefollow

ingprogram

does.

x=

sym(’x’)

length(char(x))

fork

=1:10

x=

sqrt(1+x)

length(char(x))

end

1.8

Fixed

points.VerifythattheGolden

Ratioisafixed

pointofeach

ofthefollow

ing

equations.

φ=

1

φ−

1

φ=

1 φ+1

Use

each

oftheequationsas

thebasisforafixed

pointiterationto

compute

φ.Do

theiterationsconverge?

1.9

Another

iteration.Before

you

runthefollow

ingprogram,predictwhatit

will

do.Then

runit.

x=

3

k=

1

formatlong

whilex

~=

sqrt(1+x^2)

x=

sqrt(1+x^2)

k=

k+1

end

1.10Another

fixedpoint.

Solvethis

equationbyhand.

x=

1√ 1

+x2

How

manyiterationsdoes

thefollow

ingprogram

require?

How

isthefinalvalueof

xrelatedto

theGolden

Ratioφ?

x=

3

k=

1

formatlong

whilex

~=

1/sqrt(1+x^2)

x=

1/sqrt(1+x^2)

k=

k+1

end

Page 12: Experiments With MatLab Moled 2011

13

1.11cos(x).Findthenumericalsolutionof

theequation

x=

cosx

intheinterval[0,π 2],show

nin

figure

1.4.

00.

51

1.5

0

0.51

1.5

Figure

1.4.Fixed

pointofx=

cos(x).

−6−4

−20

24

6−6−4−20246

Figure

1.5.Threefixedpoints

ofx=

tan(x)

1.12tan(x).

Figure

1.5

show

sthreeofthemanysolutionsto

theequation

x=

tanx

Oneof

thesolutionsis

x=

0.Theother

twoin

theplotare

nearx=

±4.5.If

wedid

aplotover

alargerange,

wewou

ldseesolutionsin

each

oftheintervals

[(n−

1 2)π,(n+

1 2)π]forinteger

n.

(a)Does

this

compute

afixed

point?

x=

4.5

14Chapter1.

Iteration

fork

=1:30

x=

tan(x)

end

(b)Does

this

compute

afixed

point?

Whyis

the“+

pi”necessary?

x=

pi

whileabs(x-

tan(x))

>eps(x)

x=

atan(x)

+pi

end

1.13Summation.Write

amathem

aticalexpressionforthequantity

approxim

ated

bythis

program.

s=

0;

t=

Inf;

n=

0;

whiles

~=

t

n=

n+1;

t=

s;

s=

s+

1/n^4;

end

s

1.14Why.

ThefirstversionofMatlab

written

inthelate

1970’s,hadwho,what,

which,an

dwherecommands.

Soitseem

ednaturalto

addawhycommand.Check

outtoday

’swhycommandwith

why

helpwhy

fork

=1:40,

why,

end

typewhy

editwhy

Asthehelpentrysays,

please

embellish

ormodifythewhyfunctionto

suit

your

owntastes.

1.15Wiggles.Aglimpse

atMatlabplottingcapabilitiesisprovided

bythefunction

f=

@(x)

tan(sin(x))

-sin(tan(x))

Thisusesthe’@’signto

introduce

asimple

function.Youcanlearn

more

aboutthe

’@’signwithhelpfunction_handle.

Figure

1.6show

stheoutputfrom

thestatement

ezplot(f,[-pi,pi])

Page 13: Experiments With MatLab Moled 2011

15

−3−2

−10

12

3

−2.5−2

−1.5−1

−0.50

0.51

1.52

2.5

x

tan(

sin(

x))−

sin(

tan(

x))

Figure

1.6.A

wigglyfunction.

(Thefunctionnameezplotis

intended

tobepronounced“Easy

Plot”.This

pun

doesn’t

workif

you

learned

topronounce

“z”

as“zed”.)

You

can

seethatthe

functionis

veryflatnearx=

0,oscillatesinfinitelyoften

nearx=

±π/2andis

nearlylinearnearx=

±π.

You

canget

more

controlover

theplotwithcodelikethis.

x=

-pi:pi/256:pi;

y=

f(x);

plot(x,y)

xlabel(’x’)

ylabel(’y’)

title(’Awigglyfunction’)

axis([-pipi

-2.8

2.8])

set(gca,’xtick’,pi*(-3:1/2:3))

(a)W

hatis

theeff

ectofvariousvalues

ofnin

thefollow

ingcode?

x=

pi*(-2:1/n:2);

comet(x,f(x))

(b)This

functionis

bou

nded

.A

numeric

valuenearitsmaxim

um

canbefound

with

max(y)

Whatisitsanalyticmaxim

um?(T

obeprecise,Ishould

ask

”W

hatisthefunction’s

supremum?”)

1.16Graphics.

Weuse

alotofcomputergraphicsin

thisbook,butstudyingMat-

labgraphicsprogrammingisnotou

rprimary

goal.How

ever,ifyouare

curious,the

16Chapter1.

Iteration

scriptthatproducesfigure

1.3

isgoldrect.m.Modifythis

program

toproduce

agraphic

thatcomparestheGolden

Rectangle

withTV

screenshav

ingaspectratios

4:3

and16:9.

1.17Golden

Spiral

Figure

1.7.A

spiralform

edfrom

golden

rectangles

andinscribedquarter

circles.

Ourprogram

golden_spiraldisplaysanever-expandingsequence

ofgolden

rectangleswithinscribed

quarter

circles.

Checkitout.

Page 14: Experiments With MatLab Moled 2011

Chapter2

FibonacciNumbers

Fibonaccinumbers

introduce

vectors,functionsandrecursion.

LeonardoPisanoFibonacciwasborn

around1170anddiedaround1250in

Pisain

whatis

now

Italy.Hetraveled

extensivelyin

EuropeandNorthernAfrica.

Hewrote

severalmathem

aticaltexts

that,

amongother

things,

introducedEurope

totheHindu-A

rabic

notationfornumbers.

Even

thoughhisbookshadto

betran-

scribed

byhand,they

werewidelycirculated.In

hisbestknow

nbook

,Liber

Abaci,

published

in1202,heposed

thefollow

ingproblem:

Amanputs

apair

ofrabbitsin

aplace

surrounded

onallsides

byawall.

How

manypairsofrabbitscanbe

producedfrom

thatpair

inayearifit

issupposedthateverymonth

each

pair

begets

anew

pair

whichfrom

the

secondmonth

onbecomes

productive?

Today

thesolutionto

this

problem

isknow

nastheFibonaccisequen

ce,or

Fibonaccinumbers.

Thereis

asm

allmathem

aticalindustry

basedonFibonacci

numbers.

AsearchoftheInternet

for“Fibonacci”

willfinddozensof

Web

sitesan

dhundredsofpages

ofmaterial.Thereiseven

aFibonacciAssociationthatpublishes

ascholarlyjournal,theFibonacciQuarterly.

Asimulationof

Fibonacci’sproblem

isprovided

byourexmprogram

rabbits.

Just

execute

thecommand

rabbits

andclickon

thepushbuttonsthatshow

up.Youwillseesomethinglikefigure

2.1.

IfFibonaccihadnotspecified

amonth

forthenew

bornpair

tomature,he

would

nothaveasequence

named

after

him

.Thenumber

ofpairswould

simply

Copyright

c ©2011CleveMoler

Matlab

R ©is

aregisteredtradem

ark

ofMath

Works,

Inc.

TM

October

4,2011

17

18Chapter2.

Fibon

acci

Numbers

Figure

2.1.Fibonacci’srabbits.

double

each

month.After

nmonthstherewould

be2n

pairsofrabbits.

That’sa

lotof

rabbits,

butnotdistinctivemathem

atics.

Let

f ndenote

thenumber

ofpairsofrabbitsafter

nmonths.

Thekey

fact

isthatthenumber

ofrabbitsattheendofamonth

isthenumber

atthebeginning

ofthemonth

plusthenumber

ofbirthsproducedbythemature

pairs:

f n=

f n−1+f n

−2.

Theinitialconditionsarethatin

thefirstmonth

thereison

epairofrabbitsandin

thesecondtherearetw

opairs:

f 1=

1,

f 2=

2.

Thefollow

ingMatlabfunction,storedin

afilefibonacci.mwitha.msuffix,

producesavectorcontainingthefirstnFibonaccinumbers.

functionf

=fibonacci(n)

%FIBONACCI

Fibonacci

sequence

%f

=FIBONACCI(n)

generates

the

first

nFibonacci

numbers.

Page 15: Experiments With MatLab Moled 2011

19

f=

zeros(n,1);

f(1)=

1;

f(2)=

2;

fork

=3:n

f(k)=

f(k-1)

+f(k-2);

end

Withtheseinitialconditions,thean

swer

toFibonacci’soriginalquestionaboutthe

size

oftherabbitpopulationafteroneyearis

given

by

fibonacci(12)

This

produces

1 2 3 5 8

13

21

34

55

89

144

233

Theansw

eris

233pairsofrabbits.

(Itwou

ldbe4096pairsifthenumber

doubled

everymonth

for12

months.)

Let’s

look

carefullyatfibonacci.m.It’s

agoodexample

ofhow

tocreate

aMatlabfunction.Thefirstlineis

functionf

=fibonacci(n)

Thefirstword

onthefirstlinesaysfibonacci.mis

afunction,notascript.

The

remainder

ofthefirstlinesaysthis

particularfunctionproducesoneoutputresult,

f,an

dtakes

oneinputargument,n.Thenameofthefunctionspecified

onthefirst

lineis

notactuallyused,because

Matlablooksforthenameofthefile

witha.m

suffixthatcontainsthefunction,butitiscommonpracticeto

havethetw

omatch.

Thenexttw

olines

are

comments

thatprovidethetextdisplayed

when

youask

for

help.

helpfibonacci

produces

FIBONACCI

Fibonaccisequence

f=

FIBONACCI(n)

generates

the

first

nFibonacci

numbers.

20Chapter2.

Fibon

acci

Numbers

Thenameof

thefunctionis

inuppercase

because

historicallyMatlab

was

case

insensitiveandranonterm

inals

withon

lyasingle

font.

Theuse

ofcapitalletters

may

beconfusingto

somefirst-timeMatlabusers,buttheconventionpersists.

Itisim

portantto

repeattheinputandou

tputarguments

inthesecomments

because

thefirstlineis

notdisplayedwhen

youask

forhelponthefunction.

Thenextline

f=

zeros(n,1);

createsan

n-by-1

matrix

containingallzerosandassignsit

tof.In

Matlab,a

matrix

withonly

onecolumnisacolumnvectorandamatrix

withonly

onerow

isarow

vector.

Thenexttw

olines,

f(1)=

1;

f(2)=

2;

providetheinitialconditions.

Thelast

threelines

are

theforstatementthatdoes

allthework.

fork

=3:n

f(k)=

f(k-1)

+f(k-2);

end

Weliketo

use

threespacesto

indentthebodyofforandifstatements,butother

people

prefertw

oor

fourspaces,oratab.Youcanalso

puttheentire

construction

ononelineifyouprovideacommaafter

thefirstclause.

This

particularfunctionlooksalotlikefunctionsin

other

programminglan-

guages.

Itproducesavector,

butit

does

notuse

anyof

theMatlab

vectoror

matrix

operations.

Wewillseesomeoftheseoperationssoon.

Hereis

another

Fibonaccifunction,fibnum.m.Itsoutputis

simply

thenth

Fibonaccinumber.

functionf

=fibnum(n)

%FIBNUM

Fibonacci

number.

%FIBNUM(n)

generates

the

nth

Fibonacci

number.

if

n<=

1

f=1;

else f=

fibnum(n-1)

+fibnum(n-2);

end

Thestatement

fibnum(12)

produces

ans=

233

Page 16: Experiments With MatLab Moled 2011

21

Thefibnumfunctionis

recursive.

Infact,theterm

recursiveis

usedin

both

amathem

aticalandacomputerscience

sense.

Inmathem

atics,therelationship

f n=

f n−1+

f n−2is

arecursionrelationIn

computerscience,afunctionthatcalls

itselfis

arecursivefunction.

Arecursiveprogram

iselegant,

butexpensive.

You

canmeasure

execution

timewithticandtoc.Try

tic,fibnum(24),toc

Donottry

tic,fibnum(50),toc

FibonacciMee

tsGolden

Ratio

TheGolden

Ratioφcanbeexpressed

asaninfinitecontinued

fraction.

φ=

1+

1

1+

11+

11+

···

.

Toverifythis

claim

,suppose

wedid

notknow

thevalueof

this

fraction.Let

x=

1+

1

1+

11+

11+

···

.

Wecanseethefirstdenominatoris

just

another

copyofx.In

other

words.

x=

1+

1 x

This

immed

iately

leadsto

x2−

x−

1=

0

whichis

thedefiningquadraticequationforφ,

OurexmfunctiongoldfractgeneratesaMatlabstringthatrepresents

the

firstnterm

softheGolden

Ratiocontinued

fraction.Hereis

thefirstsectionof

codein

goldfract.

p=

’1’;

fork

=2:n

p=

[’1

+1/(’

p’)’];

end

display(p)

Westart

withasingle

’1’,whichcorrespondsto

n=

1.Wethen

repeatedly

make

thecurrentstringthedenominatorin

alonger

string.

Hereis

theoutputfrom

goldfract(n)when

n=

7.

1+

1/(1

+1/(1

+1/(1

+1/(1

+1/(1

+1/(1))))))

22Chapter2.

Fibon

acci

Numbers

You

canseethattherearen-1plussignsandn-1pairsof

matchingparentheses.

Let

φndenote

thecontinued

fractiontruncatedafter

nterm

s.φnisarational

approxim

ationto

φ.Let’s

express

φnasaconventionalfracton,theratioof

two

integers φn=

pn q n

p=

1;

q=

0;

fork

=2:n

t=

p;

p=

p+

q;

q=

t;

end

Now

compare

theresultsproducedbygoldfract(7)andfibonacci(7).The

firstcontainsthefraction21/1

3whilethesecondendswith13and21.This

isnot

just

acoincidence.

Thecontinued

fraction

fortheGolden

Ratiois

collapsed

by

repeatingthestatement

p=

p+

q;

whiletheFibonaccinumbersaregeneratedby

f(k)=

f(k-1)

+f(k-2);

Infact,ifweletφndenote

thegolden

ratiocontinued

fractiontruncatedatnterm

s,then

φn=

f nf n

−1

Intheinfinitelimit,theratioof

successiveFibonaccinumbersap

proaches

thegolden

ratio:

lim

n→

∞f n

f n−1=

φ.

Toseethis,compute

40Fibonaccinumbers.

n=

40;

f=

fibonacci(n);

Then

compute

theirratios.

r=

f(2:n)./f(1:n-1)

This

takes

thevectorcontainingf(2)throughf(n)and

divides

it,elem

entby

elem

ent,bythevectorcontainingf(1)throughf(n-1).Theoutputbeginswith

Page 17: Experiments With MatLab Moled 2011

23

2.00000000000000

1.50000000000000

1.66666666666667

1.60000000000000

1.62500000000000

1.61538461538462

1.61904761904762

1.61764705882353

1.61818181818182

andendswith

1.61803398874990

1.61803398874989

1.61803398874990

1.61803398874989

1.61803398874989

Doyouseewhywechose

n=

40?Compute

phi=

(1+sqrt(5))/2

r-

phi

Whatis

thevalueofthelast

elem

ent?

Thefirstfew

oftheseratioscanalsobeusedto

illustrate

therationaloutput

form

at. formatrat

r(1:10)

ans=

2 3/2

5/3

8/5

13/8

21/13

34/21

55/34

89/55

Thepopulationof

Fibonacci’srabbit

pen

doesn’t

double

everymonth;it

ismultiplied

bythegolden

ratioeverymonth.

AnAnalyticExp

ression

Itis

possible

tofind

aclosed-form

solution

totheFibonaccinumber

recurrence

relation.Thekey

isto

look

forsolutionsof

theform

f n=

cρn

24Chapter2.

Fibon

acci

Numbers

forsomeconstants

candρ.Therecurrence

relation

f n=

f n−1+f n

−2

becomes cρn=

cρn−1+

cρn−2

Dividingboth

sides

bycρ

n−2gives

ρ2=

ρ+1.

We’veseen

thisequationin

thechapterontheGolden

Ratio.Thereare

twopossible

values

ofρ,namelyφand1−φ.Thegeneralsolutionto

therecurrence

is

f n=

c 1φn+c 2(1

−φ)n.

Theconstants

c 1andc 2

are

determined

byinitialconditions,

whicharenow

convenientlywritten

f 0=

c 1+c 2

=1,

f 1=

c 1φ+c 2(1

−φ)=

1.

Oneoftheexercisesasksyouto

use

theMatlabbackslash

operatorto

solvethis

2-by-2

system

ofsimultaneouslinearequations,butitismay

beeasier

tosolvethe

system

byhand:

c 1=

φ

2φ−1,

c 2=

−(1

−φ)

2φ−1.

Insertingthesein

thegeneralsolutiongives

f n=

1

2φ−1(φ

n+1−

(1−φ)n

+1).

This

isanamazingequation.Theright-handsideinvo

lves

pow

ersan

dquo-

tients

ofirrationalnumbers,buttheresultisasequence

ofintegers.

You

cancheck

this

withMatlab.

n=

(1:40)’;

f=

(phi.^(n+1)

-(1-phi).^(n+1))/(2*phi-1)

f=

round(f)

The.^operatoris

anelem

ent-by-elementpow

erop

erator.

Itis

notnecessary

touse

./forthefinaldivisionbecause

(2*phi-1)isascalarquantity.Roundofferror

prevents

theresultsfrom

beingexact

integers,

sotheroundfunction

isused

toconvert

floatingpointquantities

tonearest

integers.

Theresultingfbeginswith

f=

1

Page 18: Experiments With MatLab Moled 2011

25

2 3 5 8

13

21

34

andendswith

5702887

9227465

14930352

24157817

39088169

63245986

102334155

165580141

Rec

ap

%%Fibonacci

Chapter

Recap

%This

is

an

executable

program

that

illustrates

the

statements

%introduced

in

the

Fibonacci

Chapter

of

"Experiments

in

MATLAB".

%You

can

access

it

with

% %fibonacci_recap

%edit

fibonacci_recap

%publish

fibonacci_recap

%%Related

EXM

Programs

% %fibonacci.m

%fibnum.m

%rabbits.m

%%Functions

%Save

in

file

sqrt1px.m

% %function

y=

sqrt1px(x)

%%

SQRT1PX

Sample

function.

%%

Usage:

y=

sqrt1px(x)

% %y

=sqrt(1+x);

%%Create

vector

n=

8;

26Chapter2.

Fibon

acci

Numbers

f=

zeros(1,n)

t=

1:n

s=

[1

23

58

13

21

34]

%%

Subscripts

f(1)=

1;

f(2)=

2;

fork

=3:n

f(k)=

f(k-1)

+f(k-2);

end

f

%%

Recursion

%function

f=

fibnum(n)

%if

n<=

1

%f=

1;

%else

%f=

fibnum(n-1)

+fibnum(n-2);

%end

%%

Tic

and

Toc

formatshort

tic

fibnum(24);

toc

%%

Element-by-element

array

operations

f=

fibonacci(5)’

fpf=

f+f

ftf=

f.*f

ff

=f.^2

ffdf=

ff./f

cosfpi=

cos(f*pi)

even=

(mod(f,2)

==

0)

formatrat

r=

f(2:5)./f(1:4)

%%

Strings

hello_world

Page 19: Experiments With MatLab Moled 2011

27

Exe

rcises

2.1

Rabbits.

Explain

whatourrabbitssimulation

dem

onstrates.

Whatdothe

differentfiguresandcolors

onthepushbuttonssignify?

2.2

Waltz.

WhichFibonaccinumbersareeven?W

hy?

2.3

Primes.Use

theMatlabfunctionisprimeto

discover

whichofthefirst40

Fibonaccinumbersareprime.

You

donotneedto

use

aforloop.Instead,check

out

helpisprime

helplogical

2.4

Backslash.Use

theMatlabbackslash

operatorto

solvethe2-by-2

system

of

simultaneouslinearequations

c 1+c 2

=1,

c 1φ+c 2(1

−φ)=

1

forc 1

andc 2.Youcanfindoutabou

tthebackslash

operatorbytakingapeekat

theLinearEquationschapter,

orwiththecommands

help\

helpslash

2.5

Logarithmic

plot.

Thestatement

semilogy(fibonacci(18),’-o’)

makes

alogarithmic

plotofFibonaccinumbersversustheirindex.Thegraphis

close

toastraightline.

Whatis

theslopeofthis

line?

2.6

Execution

time.

How

does

theexecution

timeoffibnum(n)dep

end

on

the

executiontimeforfibnum(n-1)andfibnum(n-2)?Use

thisrelationship

toobtain

anapproxim

ate

form

ula

fortheexecutiontimeoffibnum(n)asafunctionofn.

Estim

ate

how

longitwould

takeyourcomputerto

compute

fibnum(50).Warning:

You

probably

donotwan

tto

actuallyrunfibnum(50).

2.7

Overfl

ow.W

hatis

theindex

ofthelargestFibonaccinumber

thatcanberep-

resentedexactly

asaMatlab

double-precisionquantity

withoutroundoff

error?

Whatistheindex

ofthelargestFibonaccinumber

thatcanberepresentedapprox-

imately

asaMatlabdouble-precisionquantity

withoutoverflow

ing?

2.8

Slower

maturity.W

hatifrabbitstooktw

omonthsto

mature

insteadofone?

28Chapter2.

Fibon

acci

Numbers

Thesequence

would

bedefined

by

g 1=

1,

g 2=

1,

g 3=

2

and,forn>

3,

g n=

g n−1+

g n−3

(a)Modifyfibonacci.mandfibnum.mto

compute

this

sequence.

(b)How

manypairsof

rabbitsare

thereafter

12months?

(c)g n

≈γn.W

hat

isγ?

(d)Estim

ate

how

longit

wou

ldtakeyourcomputerto

compute

fibnum(50)with

this

modified

fibnum.

2.9

Mortality.W

hatifrabbitstookonemonth

tomature,butthen

diedafter

six

months.

Thesequence

would

bedefined

by

dn

=0,

n<=

0

d1=

1,

d2=

1

and,forn>

2,

dn=

dn−1+dn−2−

dn−7

(a)Modifyfibonacci.mandfibnum.mto

compute

this

sequence.

(b)How

manypairsof

rabbitsare

thereafter

12months?

(c)dn≈

δn.W

hat

isδ?

(d)Estim

ate

how

longit

wou

ldtakeyourcomputerto

compute

fibnum(50)with

this

modified

fibnum.

2.10

Hello

World.

Programming

languages

aretraditionally

introduced

by

the

phrase

”hello

world”.Anscriptin

exmthatillustratessomefeaturesin

Matlabis

available

with

hello_world

Explain

whateach

ofthefunctionsan

dcommandsin

hello_worlddo.

2.11Fibonaccipower

series.TheFibonaccinumbers,f n

,canbeusedascoeffi

cients

inapow

erseries

definingafunctionofx.

F(x)

=∞ ∑ n=1

f nxn

=x+2x2+3x3+5x4+8x5+13x6+...

Page 20: Experiments With MatLab Moled 2011

29

Ourfunctionfibfun1isafirstattemptat

aprogram

tocompute

thisseries.It

sim-

ply

invo

lves

addinganaccumulatingsum

tofibonacci.m.Theheader

offibfun1.m

includes

thehelpentries.

function[y,k]=

fibfun1(x)

%FIBFUN1

Power

series

with

Fibonacci

coefficients.

%y

=fibfun1(x)

=sum(f(k)*x.^k).

%[y,k]

=fibfun1(x)

also

gives

the

number

of

terms

required.

Thefirstsectionofcodeinitializesthevariablesto

beused.Thevalueofnis

the

index

wheretheFibonaccinumbersoverflow

.

\excise

\emph{Fibonaccipowerseries}.

TheFibonaccinumbers,$f_n$,canbe

used

as

coefficients

in

a

powerseriesdefininga

function

of

$x$.

\begin{eqnarray*}

F(x)&

=&

\sum_{n

=1}^\infty

f_n

x^n

\\

&=

&x

+2

x^2

+3

x^3

+5

x^4

+8

x^5

+13

x^6

+...

\end{eqnarray*}

Ourfunction#fibfun1#is

afirst

attempt

at

aprogram

to

computethisseries.

It

simply

involves

adding

an

accumulating

sumto

#fibonacci.m#.

Theheaderof

#fibfun1.m#

includes

the

help

entries.

\begin{verbatim}

function[y,k]=

fibfun1(x)

%FIBFUN1

Power

series

with

Fibonacci

coefficients.

%y

=fibfun1(x)

=sum(f(k)*x.^k).

%[y,k]

=fibfun1(x)

also

gives

the

number

of

terms

required.

Thefirstsectionofcodeinitializesthevariablesto

beused.Thevalueof

nis

the

index

wheretheFibonaccinumbersoverflow

.

n=

1476;

f=

zeros(n,1);

f(1)=

1;

f(2)=

2;

y=

f(1)*x

+f(2)*x.^2;

t=

0;

Themain

bodyof

fibfun1im

plements

theFibonaccirecu

rren

cean

dincludes

atest

forearlyterm

inationoftheloop.

fork

=3:n

f(k)=

f(k-1)

+f(k-2);

y=

y+

f(k)*x.^k;

if

y==

t

return

end

30Chapter2.

Fibon

acci

Numbers

t=y;

end

Thereareseveralobjectionsto

fibfun1.Thecoeffi

cientarrayof

size

1476

isnotactuallynecessary.Therepeatedcomputationof

pow

ers,

x^k,is

ineffi

cient

because

once

somepow

erofxhasbeencomputed,thenextpow

ercanbeobtained

withonemultiplication.W

hen

theseries

converges

thecoeffi

cients

f(k)increase

insize,butthepow

ersx^kdecrease

insize

more

rapidly.

Theterm

sf(k)*x^k

approach

zero,buthugef(k)preventtheircomputation.

Amore

efficientandaccurate

approach

involves

combiningthecomputation

oftheFibonaccirecurrence

andthepow

ersof

x.Let

pk=

f kxk

Then,since

f k+1xk+1=

f kxk+f k

−1xk−1

theterm

spksatisfy

pk+1

=pkx+pk−1x2

=x(p

k+xpk−1)

Thisisthebasisforourfunctionfibfun2.Theheader

isessentiallythesame

asfibfun1

function[yk,k]=

fibfun2(x)

%FIBFUN2

Power

series

with

Fibonacci

coefficients.

%y

=fibfun2(x)

=sum(f(k)*x.^k).

%[y,k]

=fibfun2(x)

also

gives

the

number

of

terms

required.

Theinitialization.

pkm1=

x;

pk

=2*x.^2;

ykm1=

x;

yk

=2*x.^2

+x;

k=

0;

Andthecore.

whileany(abs(yk-ykm1)>

2*eps(yk))

pkp1=

x.*(pk

+x.*pkm1);

pkm1=

pk;

pk=

pkp1;

ykm1=

yk;

yk=

yk

+pk;

k=

k+1;

end

Page 21: Experiments With MatLab Moled 2011

31

Thereis

noarrayofcoeffi

cients.Only

threeofthepkterm

sarerequired

foreach

step.Thepow

erfunction^is

notnecessary.Computationof

thepow

ersis

incor-

poratedin

therecurrence.Consequently,

fibfun2is

both

more

efficientan

dmore

accurate

thanfibfun1.

Butthereisaneven

betterway

toevaluate

thisparticularseries.It

ispossible

tofindaan

alyticexpressionfortheinfinitesum.

F(x)

=

∞ ∑ n=1

f nxn

=x+2x2+3x3+5x4+8x5+...

=x+(1

+1)x2+(2

+1)x

3+(3

+2)x

4+(5

+3)x

5+...

=x+x2+x(x

+2x

2+3x3+5x4+

...)+

x2(x

+2x2+3x3+...)

=x+x2+xF(x)+

x2F(x)

So

(1−x−x2)F

(x)=

x+x2

Finally F(x)=

x+x2

1−

x−

x2

Itis

noteven

necessary

tohavea.mfile.A

one-liner

does

thejob.

fibfun3=

@(x)

(x

+x.^2)./(1

-x

-x.^2)

Compare

thesethreefibfun’s.

32Chapter2.

Fibon

acci

Numbers

Page 22: Experiments With MatLab Moled 2011

Chapter3

CalendarsandClock

s

Computationsinvolvingtime,

dates,

biorhythmsandEaster.

Calendars

are

interestingmathem

aticalob

jects.

TheGregoriancalendarwas

firstproposed

in1582.

Ithasbeen

graduallyadopted

byvariouscountriesan

dchurches

over

thefourcenturies

since

then

.TheBritish

Empire,

includingthe

coloniesin

NorthAmerica,adopteditin

1752.Turkey

did

notadoptituntil1923.

TheGregoriancalendarisnow

themost

widelyusedcalendarin

theworld,butby

nomeanstheonly

one.

IntheGregoriancalendar,ayearyisaleapyearifandon

lyifyisdivisibleby4

andnotdivisible

by100,orisdivisible

by400.In

Matlabthefollow

ingexpression

must

betrue.Thedouble

ampersands,

’&&’,mean“and”andthedouble

vertical

bars,’||’,mean“or”.

mod(y,4)==

0&&

mod(y,100)

~=

0||

mod(y,400)

==

0

For

example,2000wasaleapyear,

but2100willnotbealeapyear.

This

rule

implies

thattheGregoriancalendarrepeats

itselfevery400years.In

that400-year

period,thereare

97leapyears,4800months,

20871weeks,

and146097day

s.The

averagenumber

ofday

sin

aGregoriancalendaryearis

365+

97

400=

365

.2425.

TheMatlabfunctionclockreturnsasix-elementvectorcwithelem

ents

c(1)=

year

c(2)=

month

c(3)=

day

c(4)=

hour

c(5)=

minute

c(6)=

seconds

Copyright

c ©2011CleveMoler

Matlab

R ©is

aregisteredtradem

ark

ofMath

Works,

Inc.

TM

October

4,2011

33

34Chapter3.

CalendarsandClocks

Thefirstfiveelem

ents

are

integers,whilethesixth

elem

enthasafractionalpart

that

isaccurate

tomilliseconds.

Thebestway

toprintaclockvectoristo

use

fprintf

orsprintfwithaspecified

form

atstringthathasboth

integer

andfloatingpoint

fields. f=

’%6d

%6d

%6d

%6d

%6d

%9.3f\n’

Iam

revisingthis

chapteronAugust

2,2011,atafew

minutesafter2:00pm,so

c=

clock;

fprintf(f,c);

produces

2011

82

14

219.470

Inother

words,

year=

2011

month=

8

day=

2

hour=

14

minute=

2

seconds=

19.470

TheMatlabfunctionsdatenum,datevec,datestr,andweekdayuse

clock

andfactsabouttheGregoriancalendarto

facilitate

computationsinvolvingcalendar

dates.

Datesarerepresentedbytheirserialdate

number,

whichis

thenumber

of

day

ssince

thetheoreticaltimean

dday

over

20centuries

agowhen

clockwould

havebeensixzeros.

Wecan’t

pin

thatdow

nto

anactualdate

because

different

calendars

wou

ldhavebeenin

use

atthattime.

Thefunctiondatenum

returnsthedate

number

foran

yclock

vector.

For

example,usingthevectorcthatIjust

found,thecurrentdate

number

is

datenum(c)

is

734717.585

This

indicatesthatthecu

rrenttimeis

alittle

over

halfway

throughday

number

734717.Iget

thesameresultfrom

datenum(now)

orjust now

Thedatenumfunctionalsoworkswithagiven

year,month

andday,oradate

specified

asastring.Forexample

Page 23: Experiments With MatLab Moled 2011

35

datenum(2011,8,2)

and

datenum(’Aug.2,

2011’)

bothreturn

734717

Thesameresult

isobtained

from

fix(now)

Intw

oandahalfday

sthedate

number

willbe

datenum(fix(now+2.5))

734720

Computingthedifference

betweentw

odate

numbersgives

anelapsedtime

measuredin

day

s.How

manyday

sare

left

betweentoday

andthefirstday

ofnext

year?

datenum(’Jan1,

2012’)

-datenum(fix(now))

ans=

152

Theweekdayfunctioncomputestheday

oftheweek,as

both

aninteger

be-

tween1and7andastring.Forexample

both

[d,w]=

weekday(datenum(2011,8,2))

and

[d,w]=

weekday(now)

bothreturn

d=

3

w= Tue

Sotoday

isthethirdday

oftheweek,aTuesday.

Friday

the13th

Friday

the13th

isunlucky,

butisitunlikely?W

hatistheprobabilitythatthe13th

day

ofan

ymonth

fallsonaFriday

?Thequickansw

eris

1/7,butthatis

notquite

right.

Thefollow

ingcodecounts

thenumber

oftimes

thatFriday

occurs

onthe

variousweekdaysin

a400yearcalendarcycleandproducesfigure

3.1.(Y

oucan

alsorunfriday13yourself.)

36Chapter3.

CalendarsandClocks

SuM

TuW

ThF

Sa68

0

681

682

683

684

685

686

687

688

689

690

Figure

3.1.The13th

ismore

likely

tobe

onFridaythananyother

day.

c=

zeros(1,7);

fory

=1601:2000

form

=1:12

d=

datenum([y,m,13]);

w=

weekday(d);

c(w)=

c(w)

+1;

end

end

c bar(c)

axis([08

680

690])

avg=

4800/7;

line([08],[avgavg],’linewidth’,4,’color’,’black’)

set(gca,’xticklabel’,{’Su’,’M’,’Tu’,’W’,’Th’,’F’,’Sa’})

c=

687

685

685

687

684

688

684

Sothe13th

day

ofamonth

ismore

likelyto

beon

aFriday

thananyother

day

oftheweek.Theprobabilityis688/4800=

.143333.This

probabilityis

close

to,

butslightlylarger

than,1/7=

.142857.

Biorhythms

Biorhythmswereinventedover

100years

agoandenteredourpopularculture

inthe

1960s.

YoucanstillfindmanyWeb

sitestoday

thatoff

erto

prepare

personalized

biorhythms,

orthatsellsoftware

tocompute

them

.Biorhythmsare

basedonthe

notion

thatthreesinusoidalcycles

influence

ourlives.

Thephysicalcyclehasa

Page 24: Experiments With MatLab Moled 2011

37

periodof23day

s,theem

otionalcyclehasaperiodof28day

s,an

dtheintellectual

cyclehasaperiodof

33day

s.Foran

yindividual,thecycles

areinitializedatbirth.

Figure

3.2

ismybiorhythm,whichbeginsonAugust

17,1939,plotted

foran

eight-weekperiod

centeredaround

thedate

this

isbeingrevised,July

27,2011.

Itshow

sthatImust

bein

prettygoodshape.

Today,Iam

nearthepeakofmy

intellectualcycle,

andmyphysicalandem

otionalcycles

peaked

onthesameday

less

thanaweekago.

06/2

907

/06

07/1

307

/20

07/2

708

/03

08/1

008

/17

08/2

4−1

00−50050100

07/2

7/11

birt

hday

: 08/

17/3

9

Phys

ical

Emot

iona

lIn

telle

ctua

l

Figure

3.2.Mybiorhythm.

Asearch

oftheUnited

StatesGovernmentPatentand

Tradem

ark

Office

database

ofUSpatents

issued

between1976and2010finds147patents

thatare

baseduponormentionbiorhythms.

(Therewerejust

113in

2007.)

TheWeb

site

is

http://patft.uspto.gov

Thedate

andgraphicsfunctionsin

Matlabmake

thecomputationanddis-

playofbiorhythmsparticularlyconvenient.

Thefollow

ingcodesegmentis

part

of

ourprogram

biorhythm.mthatplots

abiorhythm

foraneight-weekperiodcentered

onthecurrentdate.

t0

=datenum(’Aug.

17,

1939’)

t1

=fix(now);

t=

(t1-28):1:(t1+28);

y=

100*[sin(2*pi*(t-t0)/23)

sin(2*pi*(t-t0)/28)

sin(2*pi*(t-t0)/33)];

plot(t,y)

You

seethatthetimevariable

tis

measuredin

day

sandthatthetrig

functions

takearguments

measuredin

radians.

38Chapter3.

CalendarsandClocks

When

isEaster?

Easter

Day

ison

eofthemost

importantevents

intheChristiancalendar.

Itisalso

oneof

themost

mathem

aticallyelusive.

Infact,regularizationof

theobservan

ceofEaster

was

oneoftheprimary

motivationsforcalendarreform

.Theinform

al

rule

isthatEaster

Day

isthefirstSunday

after

thefirstfullmoonafter

thevernal

equinox

.Buttheecclesiasticalfullmoonandequinox

invo

lved

inthis

rule

are

not

alwaysthesameas

thecorrespondingastronomicalevents,which,afterall,dep

end

upon

thelocation

oftheobserver

ontheearth.

Computingthedate

ofEaster

isfeatured

inDon

Knuth’s

classic

TheArt

ofComputerProgramming

and

has

consequentlybecomeafrequentexercise

inprogrammingcourses.

OurMatlab

versionof

Knuth’s

program,easter.m,is

thesubject

ofseveralexercisesin

this

chapter.

Rec

ap

%%

Calendar

Chapter

Recap

%This

is

an

executable

program

that

illustrates

the

statements

%introduced

in

the

Calendar

Chapter

of

"Experiments

in

MATLAB".

%You

can

access

it

with

% %calendar_recap

%edit

calendar_recap

%publish

calendar_recap

% %Related

EXM

programs

% %biorhythm.m

%easter.m

%clockex.m

%friday13.m

%%

Clock

and

fprintf

formatbank

c=

clock

f=

’%6d

%6d

%6d

%6d

%6d

%9.3f\n’

fprintf(f,c);

%%

Modular

arithmetic

y=

c(1)

is_leapyear=

(mod(y,4)

==

0&&

mod(y,100)

~=

0||

mod(y,400)

==

0)

%%

Date

functions

c=

clock;

dnum=

datenum(c)

dnow=

fix(now)

Page 25: Experiments With MatLab Moled 2011

39

xmas=

datenum(c(1),12,25)

days_till_xmas=

xmas

-dnow

[~,wday]=

weekday(now)

%%Count

Friday

the

13th’s

c=

zeros(1,7);

fory

=1:400

form

=1:12

d=

datenum([y,m,13]);

w=

weekday(d);

c(w)=

c(w)

+1;

end

end

formatshort

c

%%Biorhythms

bday=

datenum(’8/17/1939’)

t=

(fix(now)-bday)

+(-28:28);

y=

100*[sin(2*pi*t/23)

sin(2*pi*t/28)

sin(2*pi*t/33)];

plot(t,y)

axistight

Exe

rcises

3.1

Microcentury.Theoptimum

length

ofaclassroom

lecture

ison

emicrocentury.

How

longis

that?

3.2

π·1

07.A

goodestimate

ofthenumber

ofsecondsin

ayearis

π·1

07.How

accurate

isthis

estimate?

3.3

datestr.W

hatdoes

thefollow

ingprogram

do?

fork

=1:31

disp(datestr(now,k))

end

3.4

calendar(a)W

hatdoes

thecalendarfunctiondo?(IfyouhavetheFinancial

Toolbox

,helpcalendarwillalsotellyouaboutit.)

Try

this:

y=

your

birth

year

%An

integer,

1900

<=

y<=

2100.

m=

your

birth

month

%An

integer,

1<=

m<=

12.

40Chapter3.

CalendarsandClocks

calendar(y,m)

(b)W

hatdoes

thefollow

ingcodedo?

c=

sum(1:30);

s=

zeros(12,1);

form

=1:12

s(m)=

sum(sum(calendar(2011,m)));

end

bar(s/c)

axis([013

0.80

1.15])

3.5

Another

clock.

Whatdoes

thefollow

ingprogram

do?

clf

set(gcf,’color’,’white’)

axisoff

t=

text(0.0,0.5,’

’,’fontsize’,16,’fontweight’,’bold’);

while1

s=

dec2bin(fix(86400*now));

set(t,’string’,s)

pause(1)

end

Try

helpdec2bin

ifyouneedhelp.

3.6

How

long?

You

should

nottryto

runthefollow

ingprogram.Butifyou

were

torunit,how

longwould

ittake?

(Ifyouinsist

onrunningit,changeboth

3’s

to5’s.)

c=

clock

d=

c(3)

whiled

==

c(3)

c=

clock;

end

3.7

First

datenum.Thefirstcountriesto

adopttheGregoriancalendarwereSpain,

Portugalandmuch

ofItaly.They

did

soonOctober

15,1582,ofthenew

calendar.

Thepreviousday

wasOctober

4,1582,usingtheold,Julian,calendar.

SoOctober

5throughOctober

14,1582,did

notexistin

thesecountries.

WhatistheMatlab

serialdate

number

forOctober

15,1582?

3.8

Future

datenum’s.Use

datestrto

determinewhen

datenumwillreach

750,000.

When

willit

reach

1,000,000?

Page 26: Experiments With MatLab Moled 2011

41

3.9

Yourbirthday.

Onwhichday

oftheweekwereyou

born?In

a400-yearGrego-

riancalendarcycle,whatistheprobabilitythatyourbirthday

occurs

onaSaturday

?W

hichweekday

isthemost

likelyforyourbirthday

?

3.10Opspercentury.W

hichdoes

more

operations,

ahumancomputerdoingon

eoperationper

secondforacentury,oranelectronic

computerdoingon

eoperation

per

microsecondforaminute?

3.11Julianday.

TheJulianDay

Number

(JDN)is

commonly

usedto

date

astro-

nomicalobservations.

FindthedefinitionofJulianDay

ontheWeb

andexplain

why

JDN=

datenum

+1721058.5

Inparticular,

whydoes

theconversionincludean0.5

fractionalpart?

3.12Unix

time.

TheUnix

operatingsystem

andPOSIX

operatingsystem

standard

measure

timein

secondssince

00:00:00UniversaltimeonJanuary

1,1970.There

are

86,400secondsin

oneday.Consequently,

Unix

time,time_t,canbecomputed

inMatlabwith

time_t=

86400*(datenum(y,m,d)

-datenum(1970,1,1))

SomeUnix

system

sstore

thetimein

an32-bit

signed

integer

register.

When

will

time_texceed

231andoverflow

onsuch

system

s.

3.13Easter.

(a)Thecomments

ineaster.m

use

theterm

s“golden

number”,“epact”,an

d“metonic

cycle”.Findthedefinitionsof

theseterm

sontheWeb.

(b)Plotabargraphof

thedatesofEaster

duringthe21-stcentury.

(c)How

manytimes

duringthe21-stcentury

does

Easter

occurin

Marchandhow

manyin

April?

(d)Onhow

manydifferentdatescanEaster

occur?

Whatis

theearliest?W

hatis

thelatest?

(e)Is

thedate

ofEaster

aperiodic

functionoftheyearnumber?

3.14Biorhythms.

(a)Use

biorhythmto

plotyou

row

nbiorhythm,basedonyou

rbirthday

andcentered

aroundthecurrentdate.

(b)Allthreebiorhythm

cycles

start

atzero

when

youwereborn.W

hen

dothey

return

tothis

initialcondition?

Compute

them,theleast

commonmultiple

of23,

28,and33.

m=

lcm(lcm(23,28),33)

Now

try

biorhythm(fix(now)-m)

42Chapter3.

CalendarsandClocks

Whatis

specialaboutthis

biorhythm?

How

old

wereyou,or

willyou

be,

mdays

after

youwereborn?

(c)Is

itpossible

forallthreebiorhythm

cycles

toreach

theirmaxim

um

atexactly

thesametime?

Whyorwhynot?

Try

t=

17003

biorhythm(fix(now)-t)

Whatis

specialaboutthis

biorhythm?How

manyyears

istday

s?Atfirstglan

ce,

itappears

thatallthreecycles

arereachingmaxim

aat

thesametime,t.Butifyou

lookmore

closely

at

sin(2*pi*t./[2328

33])

you

willseethatthevalues

arenotallexactly

1.0.Atwhattimes

neart=

17003

dothethreecycles

actuallyreach

theirmaxim

a?

Thethreetimes

arehow

many

hours

apart?

Are

therean

yother

values

oftbetween0and

theleast

common

multiple,m,from

thepreviousexercise

wherethecycles

comeso

close

toob

taining

asimultaneousmaxim

um?This

codewillhelpyouansw

erthesequestions.

m=

lcm(lcm(23,28),33);

t=

(1:m)’;

find(mod(t,23)==6&

mod(t,28)==7

&mod(t,33)==8)

(d)Is

itpossible

forallthreebiorhythm

cycles

toreach

theirminim

um

atexactly

thesametime?

Whyor

whynot?

When

dothey

nearlyreach

asimultaneous

minim

um?

16−S

ep−2

010

16−S

ep−2

010

16−S

ep−2

010

16−S

ep−2

010

16−S

ep−2

010

16−S

ep−2

010

16−S

ep−2

010

16−S

ep−2

010

16−S

ep−2

010

16−S

ep−2

010

16−S

ep−2

010

16−S

ep−2

010

16−S

ep−2

010

16−S

ep−2

010

16−S

ep−2

010

16−S

ep−2

010

16−S

ep−2

010

16−S

ep−2

010

16−S

ep−2

010

16−S

ep−2

010

16−S

ep−2

010

16−S

ep−2

010

16−S

ep−2

010

16−S

ep−2

010

16−S

ep−2

010

16−S

ep−2

010

Figure

3.3.clockex

3.15clockex.

This

exercise

isabouttheclockexprogram

inourexmtoolbox

and

show

nin

figure

3.3.

(a)W

hydoes

clockexuse

trig

functions?

Page 27: Experiments With MatLab Moled 2011

43

(b)Makeclockexruncounter-clockwise.

(c)W

hydothehourandminute

handsin

clockexmovenearlycontinuouslywhile

thesecondhandmoves

indiscretesteps.

(d)Thesecondhandsometim

eskipstw

omarks.

Why?How

often?

(e)Modifyclockexto

haveadigitaldisplayofyourow

ndesign.

44Chapter3.

CalendarsandClocks

Page 28: Experiments With MatLab Moled 2011

Chapter4

Matrices

Matlabbeganasamatrix

calculator.

TheCartesiancoordinate

system

wasdeveloped

inthe17th

century

bythe

French

mathem

aticianandphilosopher

Ren

eDescartes.A

pair

ofnumberscorre-

spondsto

apointin

theplane.

Wewilldisplaythecoordinatesin

avectoroflength

two.In

order

towork

properly

withmatrix

multiplication,wewan

tto

thinkofthe

vectorasacolumnvector,

So

x=

( x1

x2

)den

otesthepointxwhose

firstcoordinate

isx1andsecondcoordinate

isx2.W

hen

itisinconvenientto

write

avectorin

thisverticalform

,wecananticipate

Matlab

notationanduse

asemicolonto

separate

thetw

ocompon

ents,

x=

(x1;x2)

Forexample,thepointlabeled

xin

figure

4.1hasCartesiancoordinates

x=

(2;

4)

Arithmetic

operationsonthevectors

are

defined

innaturalways.

Additionis

defined

by

x+

y=

( x1

x2

) +

( y 1 y 2

) =

( x1+y 1

x2+y 2

)Multiplicationbyasingle

number,orscalar,

isdefined

by

sx=

( sx1

sx2

)

Copyright

c ©2011CleveMoler

Matlab

R ©is

aregisteredtradem

ark

ofMath

Works,

Inc.

TM

October

4,2011

45

46Chapter4.

Matrices

A2-by-2

matrix

isanarray

offournumbersarranged

intw

orowsan

dtw

ocolumns.

A=

( a1,1

a1,2

a2,1

a2,2

)or

A=

(a1,1

a1,2;a2,1

a2,2

)

Forexample

A=

(4

−3−2

1

)

−10

−8−6

−4−2

02

46

810

−10−8−6−4−20246810

x

Ax

Figure

4.1.Matrix

multiplicationtransform

slines

through

xto

lines

through

Ax.

Matrix-vectormultiplicationbya2-by-2

matrix

Atransform

savectorxto

avectorAx,accordingto

thedefinition

Ax=

( a1,1x1+

a1,2x2

a2,1x1+

a2,2x2

)Forexample

(4

−3−2

1

)(2 4

) =

(4·2

−3·4

−2·2

+1·4

) =

( −4 0

)Thepointlabeled

xin

figure

4.1is

transform

edto

thepointlabeled

Ax.Matrix-

vectormultiplicationsproduce

lineartransform

ations.

This

meansthatforscalars

sandtandvectors

xandy,

A(sx+

ty)=

sAx+

tAy

Page 29: Experiments With MatLab Moled 2011

47

Thisim

plies

thatpoints

nearxare

transform

edto

points

nearAxandthatstraight

lines

intheplanethroughxare

transform

edto

straightlines

throughAx.

Ourdefinitionofmatrix-vectormultiplicationis

theusualon

einvolvingthe

dotproduct

oftherowsofA,denotedai,:,withthevectorx.

Ax=

( a1,:·x

a2,:·x

)

Analternate,andsometim

esmore

revealing,definitionuseslinearcombinationsof

thecolumnsofA,denotedbya:,j.

Ax=

x1a:,1+x2a:,2

For

example

(4

−3−2

1

)(2 4

) =2

(4 −2) +

4

( −3 1

) =

( −4 0

)

Thetranspose

ofacolumnvectoris

arow

vector,

denotedbyxT.Thetran

s-pose

ofamatrix

interchanges

itsrowsandcolumns.

Forexample,

xT=

(2

4)

AT=

(4

−2−3

1

)

Vector-matrix

multiplicationcanbedefined

by

xTA

=A

Tx

Thatisprettycryptic,

soifyouhavenever

seen

itbefore,youmighthaveto

ponder

itabit.

Matrix-m

atrix

multiplication,AB,canbethoughtofas

matrix-vectormulti-

plicationinvo

lvingthematrixAandthecolumnsvectors

from

B,oras

vector-matrix

multiplicationinvo

lvingtherow

vectors

from

Aandthematrix

B.It

isim

portan

tto

realize

thatAB

isnotthesamematrix

asBA.

Matlabstarted

itslife

as“Matrix

Laboratory”,so

itsveryfirstcapabilities

involved

matrices

andmatrix

multiplication.Thesyntaxfollow

sthemathem

atical

notationclosely.Weuse

square

bracketsinsteadofroundparentheses,anasterisk

toden

ote

multiplication,andx’forthetranspose

ofx.

Theforegoingexample

becomes

x=

[2;

4]

A=

[4

-3;

-2

1]

A*x

This

produces

x=

2 4

48Chapter4.

Matrices

A=

4-3

-2

1

ans= -4 0

Thematrices

A’*AandA*A’are

notthesame.

A’*A=

20

-14

-14

10

while A*A’=

25

-11

-11

5

Thematrix

I=

( 10

01

)is

the2-by-2

iden

tity

matrix.It

hastheim

portantproperty

thatforany2-by-2

matrix

A,

IA

=AI=

A

Originally,

Matlabvariable

names

werenotcase

sensitive,

soiandIwere

thesamevariable.

Since

iis

frequentlyusedasasubscript,

aniterationindex,

andsqrt(-1),wecould

not

use

Ifortheidentity

matrix.Instead,wechose

touse

thesound-alikeword

eye.Today,Matlabis

case

sensitiveandhasmanyusers

whose

nativelanguageis

notEnglish,butwecontinueto

use

eye(n,n)to

den

ote

then-by-n

identity.(T

heMetro

inWashington,DC,usesthesamepun–“Istreet”

is“eyestreet”ontheirmaps.)

2-by-2Matrix

Transform

ations

Theexmtoolbox

includes

afunctionhouse.Thestatement

X=

house

producesa2-by-11matrix,

X= -6

-6

-7

07

66

-3

-3

00

-7

21

81

2-7

-7

-2

-2

-7

ThecolumnsofXare

theCartesiancoordinatesof

the11points

show

nin

figure

4.2.

Doyou

remem

ber

the“dotto

dot”

game?

Try

itwiththesepoints.Finishoff

by

connectingthelast

pointback

tothefirst.

Thehouse

infigure

4.2

isconstructed

from

Xby

Page 30: Experiments With MatLab Moled 2011

49

−10

−50

510

−10−8−6−4−20246810

123

4

56 7

8910 11

−10

−50

510

−10−8−6−4−20246810

Figure

4.2.Connectthedots.

dot2dot(X)

Wewantto

investigate

how

matrix

multiplicationtransform

sthis

house.In

fact,ifyouhaveyou

rcomputerhandy,

trythis

now

.

wiggle(X)

Ourgoalis

toseehow

wiggleworks.

Hereare

fourmatrices.

A1

= 1/2

0

01

A2

= 10

01/2

A3

= 01

1/2

0

A4

= 1/2

0

0-1

Figure

4.3usesmatrix

multiplicationA*Xanddot2dot(A*X)to

show

theeff

ectof

theresultinglineartransform

ationsonthehouse.Allfourmatrices

are

diagonal

orantidiagonal,so

they

just

scale

andpossibly

interchangethecoordinates.

The

coordinatesare

notcombined

inanyway.Thefloor

andsides

ofthehouse

remain

at

50Chapter4.

Matrices

−10

010

−10−50510

A1

−10

010

−10−50510

A2

−10

010

−10−50510

A3

−10

010

−10−50510

A4

Figure

4.3.Theeff

ectofmultiplicationby

scalingmatrices.

rightan

glesto

each

other

andparallel

totheaxes.Thematrix

A1shrinksthefirst

coordinate

toreduce

thewidth

ofthehouse

whiletheheightremainsunchanged.

ThematrixA2shrinksthesecondcoordinate

toreduce

theheight,butnotthewidth.

Thematrix

A3interchanges

thetw

ocoordinateswhileshrinkingoneofthem

.The

matrix

A4shrinksthefirstcoordinate

andchanges

thesignof

thesecond.

Thedeterminantofa2-by-2

matrix

A=

( a1,1

a1,2

a2,1

a2,2

)is

thequantity

a1,1a2,2−a1,2a2,1

Ingeneral,determinants

are

notveryusefulin

practicalcomputationbecause

they

haveatrociousscalingproperties.But2-by-2

determinants

canbeusefulin

under-

standingsimple

matrix

properties.If

thedeterminantofamatrix

ispositive,

then

multiplicationbythatmatrix

preserves

left-orright-handedness.

Thefirsttw

oof

ourfourmatrices

havepositivedeterminants,so

thedoorremainson

theleft

side

ofthehouse.Theother

twomatrices

havenegativedeterminants,so

thedoor

istransform

edto

theother

sideof

thehouse.

TheMatlabfunctionrand(m,n)generatesan

m-by-n

matrix

withrandom

entriesbetween0an

d1.Sothestatement

Page 31: Experiments With MatLab Moled 2011

51

R=

2*rand(2,2)

-1

generatesa2-by-2

matrix

withrandom

entriesbetween-1

and1.

Herearefourof

them

. R1

=

0.0323

-0.6327

-0.5495

-0.5674

R2

=

0.7277

-0.5997

0.8124

0.7188

R3

=

0.1021

0.1777

-0.3633

-0.5178

R4

= -0.8682

0.9330

0.7992

-0.4821

−10

010

−10−50510

R1

−10

010

−10−50510

R2

−10

010

−10−50510

R3

−10

010

−10−50510

R4

Figure

4.4.Theeff

ectofmultiplicationby

random

matrices.

52Chapter4.

Matrices

Figure

4.4show

stheeff

ectofmultiplicationbythesefourmatrices

onthehouse.

Matrices

R1andR4havelargeoff

-diagonalentriesan

dnegativedeterminants,so

they

distort

thehouse

quiteabitandflip

thedoorto

therightside.

Thelines

are

still

straight,

butthewallsare

notperpendicularto

thefloor.

Lineartransform

ations

preservestraightlines,butthey

donotnecessarily

preservethean

glesbetweenthose

lines.Matrix

R2is

close

toarotation,whichwewilldiscu

ssshortly.Matrix

R3is

nearlysingular;itsdeterminantisequalto

0.0117.Ifthedeterminantwereexactly

zero,thehouse

wou

ldbeflattened

toaon

e-dim

ensionalstraightline.

Thefollow

ingmatrix

isaplanerotation.

G(θ)=

( cosθ

−sinθ

sinθ

cosθ

)

Weuse

theletter

Gbecause

Wallace

Givenspioneeredtheuse

ofplanerotations

inmatrix

computationin

the1950s.

MultiplicationbyG(θ)rotatespoints

inthe

planethroughanangle

θ.Figure

4.5show

stheeff

ectofmultiplicationbytheplane

rotationswithθ=

15◦ ,

45◦ ,

90◦ ,

and215◦ .

−10

010

−10−50510

G15

−10

010

−10−50510

G45

−10

010

−10−50510

G90

−10

010

−10−50510

G21

5

Figure

4.5.

Theaffectofmultiplication

byplanerotationsthough

15◦ ,

45◦ ,

90◦ ,

and215◦.

G15= 0.9659

-0.2588

Page 32: Experiments With MatLab Moled 2011

53

0.2588

0.9659

G45= 0.7071

-0.7071

0.7071

0.7071

G90=

0-1

10

G215=

-0.8192

0.5736

-0.5736

-0.8192

You

canseethatG45is

fairly

close

totherandom

matrix

R2seen

earlierandthat

itseff

ectonthehouse

issimilar.

Matlabgeneratesaplanerotationforanglesmeasuredin

radianswith

G=

[cos(theta)

-sin(theta);

sin(theta)

cos(theta)]

andforanglesmeasuredin

degrees

with

G=

[cosd(theta)

-sind(theta);

sind(theta)

cosd(theta)]

Ourexmtoolbox

functionwiggleusesdot2dotandplanerotationsto

pro-

duce

ananim

ationofmatrix

multiplication.Hereiswiggle.m,withouttheHandle

Graphicscommands.

functionwiggle(X)

thetamax=

0.1;

delta=

.025;

t=

0;

whiletrue

theta=

(4*abs(t-round(t))-1)

*thetamax;

G=

[cos(theta)

-sin(theta);

sin(theta)

cos(theta)]

Y=

G*X;

dot2dot(Y);

t=

t+

delta;

end

Since

thisversiondoes

nothaveastopbutton,itwou

ldrunforever.Thevariablet

advancessteadilybyincrem

entof

delta.Astincreases,

thequantity

t-round(t)

varies

between−1

/2and1/2

,so

thean

gle

θcomputedby

theta=

(4*abs(t-round(t))-1)

*thetamax;

varies

inasawtooth

fashionbetween-thetamaxandthetamax.Thegraphofθas

afunctionoftis

show

nin

figure

4.6.Each

valueofθproducesacorresponding

planerotationG(θ).

Then

54Chapter4.

Matrices

00.

51

1.5

22.

53

3.5

4

−0.10

0.1

Figure

4.6.Wiggleangleθ

Y=

G*X;

dot2dot(Y)

applies

therotationto

theinputmatrix

Xandplots

thewigglingresult.

Vectors

andMatrices

Hereis

aquicklookatafew

ofthemanyMatlab

operationsinvolvingvectors

andmatrices.Try

topredictwhatoutputwillbeproducedbyeach

ofthefollow

ing

statements.

Youcanseeif

you

arerightbyusingcutan

dpasteto

execute

the

statement,orbyrunning

matrices_recap

Vectors

arecreatedwithsquare

brackets.

v=

[0

1/4

1/2

3/4

1]

Row

sofamatrix

areseparatedbysemicolonsor

new

lines.

A=

[8

16;

35

7;

49

2]

Thereareseveralfunctionsthatcreate

matrices.

Z=

zeros(3,4)

E=

ones(4,3)

I=

eye(4,4)

M=

magic(3)

R=

rand(2,4)

[K,J]=

ndgrid(1:4)

Acoloncreatesuniform

lyspacedvectors.

v=

0:0.25:1

n=

10

y=

1:n

Asemicolonattheendofalinesuppresses

output.

n=

1000;

y=

1:n;

Page 33: Experiments With MatLab Moled 2011

55

Matrix

arithmetic

Matrix

additionandsubtractionare

denotedby+

and-.Theoperations

A+

B

and

A-

B

requireAandBto

bethesamesize,orto

bescalars,whichare

1-by-1

matrices.

Matrix

multiplication,denotedby*,

follow

stherulesoflinearalgebra.The

operation

A*

B

requires

thenumber

ofcolumnsofAto

equalthenumber

ofrow

B,that

is

size(A,2)==

size(B,1)

Rem

ember

thatA*Bis

usuallynotequalto

B*A

Ifpis

aninteger

scalar,

theexpression

A^p

denotesrepeatedmultiplicationofAbyitselfptimes.

Theuse

ofthematrix

divisionoperationsin

Matlab,

A\

B

and

A/

B

isdiscussed

inour“LinearEquations”

chapter

Array

arithmetic

.Weusuallytryto

distinguishbetweenmatrices,whichbehaveaccordingto

therulesoflinearalgebra,an

darrays,which

are

just

rectangularcollectionsof

numbers.

Element-by-elementoperationsarray

operationsaredenotedby+

,-,.*

,./

,.and.^.Forarray

multiplicationA.*Bis

equalto

B.*A

K.*J

v.^2

Anapostrophedenotesthetranspose

ofarealarray

andthecomplexconjugate

transpose

ofacomplexarray.

v=

v’

inner_prod=

v’*v

outer_prod=

v*v’

Z=

[1

2;

3+4i

5]’

Z=

[1

2;

3+4i

5].’

56Chapter4.

Matrices

Figure

4.7.ThecoverofGilbert

Strang’stextbookshowsaquiltby

ChrisCurtis.

Further

Rea

ding

Ofthedozensof

good

book

son

matrices

and

linearalgebra,wewould

liketo

recommendonein

particular.

GilbertStrang,Introductionto

LinearAlgebra,Wellesley-C

ambridge

Press,Wellesley,MA,2003.

http://www.wellesleycambridge.com

Besides

itsexcellenttechnicalcontentandexposition,it

hasaterrificcover.

The

house

thatwehaveusedthroughoutthis

chaptermadeitsdebutin

Strang’s

book

in1993.Thecoverofthefirsteditionlooked

somethinglikeou

rfigure

4.4.Chris

Curtis

saw

thatcoverand

created

agorgeousquilt.

Apicture

ofthequilthas

appearedonthecoverofallsubsequenteditionsofthebook

.

Rec

ap

%%

Matrices

Chapter

Recap

Page 34: Experiments With MatLab Moled 2011

57

%This

is

an

executable

program

that

illustrates

the

statements

%introduced

in

the

Matrices

Chapter

of

"Experiments

in

MATLAB".

%You

can

access

it

with

% %matrices_recap

%edit

matrices_recap

%publish

matrices_recap

% %Related

EXM

Programs

% %wiggle

%dot2dot

%house

%hand

%%Vectors

and

matrices

x=

[2;

4]

A=

[4

-3;

-2

1]

A*x

A’*A

A*A’

%%Random

matrices

R=

2*rand(2,2)-1

%%Build

ahouse

X=

house

dot2dot(X)

%%Rotations

theta=

pi/6

%radians

G=

[cos(theta)

-sin(theta);

sin(theta)

cos(theta)]

theta=

30

%degrees

G=

[cosd(theta)

-sind(theta);

sind(theta)

cosd(theta)]

subplot(1,2,1)

dot2dot(G*X)

subplot(1,2,2)

dot2dot(G’*X)

%%More

on

Vectors

and

Matrices

%Vectors

are

created

with

square

brackets.

v=

[0

1/4

1/2

3/4

1]

%Rows

of

amatrix

are

separated

by

semicolons

or

new

lines.

58Chapter4.

Matrices

A=

[8

16;

35

7;

49

2]

A=

[8

16

357

492]

%%

Creating

matrices

Z=

zeros(3,4)

E=

ones(4,3)

I=

eye(4,4)

M=

magic(3)

R=

rand(2,4)

[K,J]=

ndgrid(1:4)

%%

Colons

and

semicolons

%A

colon

creates

uniformally

spaced

vectors.

v=

0:0.25:1

n=

10

y=

1:n

%A

semicolon

at

the

end

of

aline

suppresses

output.

n=

1000;

y=

1:n;

%%

Matrix

arithmetic.

%Addition

and

subtraction,

+and

-,

are

element-by-element.

%Multiplication,

*,

follows

the

rules

of

linear

algebra.

%Power,

^,

is

repeated

matrix

multiplication.

KJ

=K*J

JK

=J*K

%%

Array

arithmetic

%Element-by-element

operations

are

denoted

by

%+

,-

,.*

,./

,.\

and

.^

.

K.*J

v.^2

%%

Transpose

%An

apostrophe

denotes

the

transpose

of

areal

array

Page 35: Experiments With MatLab Moled 2011

59

%and

the

complex

conjugate

transpose

of

acomplex

array.

v=

v’

inner_prod=

v’*v

outer_prod=

v*v’

Z=

[1

2;

3+4i

5]’

Z=

[1

2;

3+4i

5].’

Exe

rcises

4.1

Multiplication.

(a)W

hich2-by-2

matrices

haveA

2=

I?

(b)W

hich2-by-2

matrices

haveA

TA

=I?

(c)W

hich2-by-2

matrices

haveA

TA

=AA

T?

4.2

Inverse.

Let

A=

( 34

23

)

Findamatrix

Xso

thatAX

=I.

4.3

Powers.

Let

A=

(0.99

0.01

−0.01

1.01

)

Whatis

An?

4.4

Powers.

Let

A=

( 11

10

)

Whatis

An?

4.5

Parametrizedproduct.Let

A=

( 12

x3

)(4

56

7

)

Whichelem

ents

ofA

dep

enduponx?Is

itpossible

tochoose

xso

thatA

=A

T?

4.6

Product

oftwosymmetricmatrices.It

turnsou

tthatanymatrix

istheproduct

oftw

osymmetricmatrices.Let

A=

( 34

810

)

60Chapter4.

Matrices

Express

Aastheproduct

oftw

osymmetricmatrices.

4.7

Given

srotations.

(a)W

hatis

thedeterminantof

G(θ)?

(b)Explain

whyG(θ)2

=G(2θ).

(c)Explain

whyG(θ)n

=G(nθ).

4.8

X8.Findareal2-by-2

matrix

Xso

thatX

8=

−I.

4.9

GT.W

hatis

theeff

ectonpoints

intheplaneofmultiplicationbyG(θ)T

?

4.10G.(a)W

hatis

theeff

ectonpoints

intheplaneofmultiplicationby

G(θ)=

( cosθ

sinθ

sinθ

−cosθ

)

(b)W

hatis

thedeterminantof

G(θ)?

(c)W

hat

hap

pensifyou

modifywiggle.mto

use

Ginsteadof

G?

4.11Goldie.W

hatdoes

thefunctiongoldiein

theexmtoolbox

do?

4.12Transform

ahand.Rep

eattheexperim

ents

inthis

chapterwith

X=

hand

insteadof

X=

house

Figure

4.8

show

s

dot2dot(hand)

4.13Mirrorim

age.Finda2-by-2

matrix

Rso

that

dot2dot(house)

and

dot2dot(R*house)

aswellas

dot2dot(hand)

and

dot2dot(R*hand)

Page 36: Experiments With MatLab Moled 2011

61

−10

−50

510

−10−8−6−4−20246810

Figure

4.8.A

hand.

are

mirrorim

ages

ofeach

other.

4.14Transform

yourownhand.Rep

eattheexperim

ents

inthischapterusingaplot

ofyou

row

nhand.Start

with

figure(’position’,get(0,’screensize’))

axes(’position’,[00

11])

axis(10*[-11

-1

1])

[x,y]=

ginput;

Place

yourhandonthecomputerscreen.Use

themouse

toselect

afewdozenpoints

outliningyourhand.Terminate

theginputwithacarriagereturn.Youmightfind

iteasier

totrace

yourhandonapiece

ofpaper

andthen

putthepaper

onthe

computerscreen.Youshould

beable

toseetheginputcursorthroughthepaper.

Thedata

you

havecollected

form

stw

ocolumn

vectors

with

entriesin

the

rangefrom

-10to

10.You

canarrangethedata

astw

orowsin

asingle

matrix

with

H=

[x

y]’;

Then

youcanuse

dot2dot(H)

dot2dot(A*H)

wiggle(H)

andso

on.

Youcansave

you

rdata

inthefile

myhand.matwith

savemyhandH

andretrieveit

inalaterMatlabsessionwith

loadmyhand

62Chapter4.

Matrices

4.15Wiggler.

Make

wiggler.m,yourow

nversionof

wiggle.m,withtw

osliders

thatcontrolthespeedandam

plitude.

Intheinitialization,replace

thestatements

thetamax=

0.1;

delta=

.025;

with

thetamax=

uicontrol(’style’,’slider’,’max’,1.0,

...

’units’,’normalized’,’position’,[.25.01.25.04]);

delta=

uicontrol(’style’,’slider’,’max’,.05,

...

’units’,’normalized’,’position’,[.60.01.25.04]);

Thequantities

thetamaxanddeltaare

now

thehandlesto

thetw

osliders.

Inthe

bodyoftheloop

,replace

thetamaxby

get(thetamax,’value’);

andreplace

deltaby

get(delta,’value’);

Dem

onstrate

yourwiggleronthehouseandthehand.

Page 37: Experiments With MatLab Moled 2011

Chapter5

Linea

rEquations

Themost

importanttask

intechnicalcomputing.

Iam

thinkingoftw

onumbers.

Theiraverageis

3.W

hatare

thenumbers?

Please

remem

ber

thefirstthingthatpop

sinto

yourhead.Iwillget

back

tothis

problem

inafew

pages.

Solvingsystem

sofsimultaneouslinearequationsis

themost

importanttask

intechnicalcomputing.It

isnotonly

importantin

itsow

nright,

itis

alsoafun-

damental,an

doften

hidden,componentof

other

more

complicatedcomputational

tasks.Theverysimplest

linearequationsinvolveonly

oneunknow

n.Solve

7x=

21

Thean

swer,ofcourse,

is

x=

21 7=

3

Now

solve

ax=

b

Thean

swer,ofcourse,

is

x=

b a

Butwhat

ifa=

0?Then

wehaveto

look

atb.

Ifb�=

0then

thereisnovalue

ofxthatsatisfies

0x=

b

Copyright

c ©2011CleveMoler

Matlab

R ©is

aregisteredtradem

ark

ofMath

Works,

Inc.

TM

October

4,2011

63

64Chapter5.

LinearEquations

Thesolutiondoes

notexist.

Ontheother

hand,ifb=

0then

anyvalueofxsatisfies

0x=

0

Thesolutionis

notunique.

Mathem

aticianshavebeenthinkingab

outexistence

anduniquenessforcenturies.Wewillseethattheseconcepts

are

also

importantin

moderntechnicalcomputing.

Hereis

atoystory

problem.

Alice

buysthreeapples,adozenbananas,andon

ecantaloupefor$2.36.

Bobbuysadozenapplesandtw

ocantaloupes

for$5.26.Carolbuystw

obananasan

dthreecantaloupes

for$2.77.How

much

dosingle

piecesof

each

fruitcost?

Let

x1,x

2,andx3denote

theunknow

nprice

ofeach

fruit.Wehavethreeequations

inthreeunknow

ns.

3x1+12

x2+

x3=

2.36

12x1

+2x3=

5.26

2x2+3x3=

2.77

Because

matrix-vectormultiplicationhasbeendefined

theway

ithas,

theseequa-

tionscanbewritten

⎛ ⎝3

12

112

02

02

3

⎞ ⎠⎛ ⎝x1

x2

x3

⎞ ⎠ =⎛ ⎝2.

365.27

2.77

⎞ ⎠Or,

simply

Ax=

b

whereA

isagiven

3-by-3

matrix,bis

agiven

3-by-1

columnvector,

andx

isa

3-by-1

columnvectorwithunknow

nelem

ents.

Wewantto

solvethis

equation.If

youknow

anythingaboutmatrices,you

know

thattheequationcanbesolved

usingA

−1,theinverseof

A,

x=

A−1b

Thisisafineconcepttheoretically,butnotso

goodcomputationallyWedon’treally

needA

−1,wejust

wantto

findx.

Ifyou

donotknow

anythingaboutmatrices,you

mightbetemptedto

divide

bothsides

oftheequationbyA.

x=

b A

This

isaterrible

idea

theoretically–youcan’t

dividebymatrices

–butit

isthe

beginningofago

odidea

computationally.

Tofindthesolutionto

alinearsystem

ofequationswithMatlab,startby

enteringthematrix

ofcoeffi

cients.

Page 38: Experiments With MatLab Moled 2011

65

A=

[3

12

1;

12

02;

02

3]

Since

alltheelem

ents

ofAare

integers,thematrix

isprintedwithaninteger

form

at.

A=

312

1

12

02

02

3

Next,entertherighthandsideasacolumnvector.

b=

[2.36

5.26

2.77]’

Theelem

ents

ofbare

notintegers,so

thedefaultform

atshow

sfourdigitsafter

the

decim

alpoint.

b=

2.3600

5.2600

2.7700

Matlab

hasan

outputform

atintended

forfinancialcalculations,

likethis

fruit

price

calculation.Thecommand

formatbank

changes

theoutputto

show

only

twodigitsafter

thedecim

alpoint.

b=

2.36

5.26

2.77

InMatlabthesolutionto

thelinearsystem

ofequations

Ax=

b

isfoundusingthebackslash

operator.

x=

A\b

Thinkof

this

as“dividing”bothsides

oftheequationbyA.Theresult

is

x=

0.29

0.05

0.89

Thisgives

usthesolutionto

ourstory

problem

–applescost

29cents

each,bananas

are

anickel

each,an

dcantaloupes

are

89cents

each.

Veryrarely,system

soflinearequationscomein

theform

xA

=b

wherebandxare

row

vectors.In

thiscase,thesolutionisfoundusingtheforw

ard

slash

operator.

66Chapter5.

LinearEquations

x=

b/A

Thetw

ooperationsA\bandb/Aare

sometim

escalled

leftandrightmatrix

division.

Inbothcases,

thecoeffi

cientmatrix

isin

the“d

enominator”.Forscalars,left

and

rightdivisionarethesamething.Thequantities

7\21and21/7are

both

equalto

3. Singularmatrix

Let’s

changeou

rstory

problem

abit.Assumenow

thatCarolbuyssixapplesand

onecantaloupefor$2.77.Thecoeffi

cientmatrix

andrighthandsidebecome

A=

312

1

12

02

60

1

and

b=

2.36

5.26

2.77

Atfirstglance,this

does

notlook

likemuch

ofachange.

How

ever,

x=

A\b

produces

Warning:Matrixis

singular

to

working

precision.

x= NaN

-Inf

Inf

Infand-Infstandforplusandminusinfinityandresultfrom

divisionof

nonzero

numbersbyzero.NaNstandsfor“Not-a-N

umber”andresultsfrom

doingarithmetic

involvinginfinities.

Thesourceof

thediffi

cultyisthatthenew

inform

ationab

outCarol’spurchase

isinconsistentwiththeearlierinform

ationab

outAlice’s

andBob’s

purchases.

We

havesaid

thatCarolboughtexactly

halfasmuch

fruit

asBob.Butshepaid

2.77

when

halfofBob’spay

mentwou

ldhavebeenonly

2.63.Thethirdrow

ofAisequal

toone-halfofthesecondrow,butb(3)is

notequalto

one-halfofb(2).

Forthis

particularmatrix

Aandvectorb,

thesolutionto

thelinearsystem

ofequations

Ax=

bdoes

notexist.

WhatifwemakeCarol’spurchase

price

consistentwithBob’s?

WeleaveA

unchanged

andrevisebwith

b(3)=

2.63

Page 39: Experiments With MatLab Moled 2011

67

so

b=

2.36

5.26

2.63

Now

wedonothaveenoughinform

ation.Ourlast

twoequationsare

scalarmultiples

ofeach

other.

12x1+2x3=

5.26

6x1+

x3=

2.63

Onepossible

solutionis

thesolutionto

theoriginalproblem.

x=

0.29

0.05

0.89

A*x=

2.36

5.26

2.63

Butwecanpickanarbitrary

valueforanycomponentof

thesolutionandthen

use

thefirstequationandoneofthelast

twoequationsto

compute

theother

compo-

nents.Theresultisasolutionto

allthreeequations.

Forexample,hereisasolution

withitsthirdcomponentequalto

zero.

y=

A(1:2,1:2)\b(1:2);

y(3)=

0

y=

0.44

0.09

0.00

A*y=

2.36

5.26

2.63

Thereareinfinitelymanymore.

Forthis

particularmatrix

Aand

vectorb,

thesolution

toAx

=bis

not

unique.

Thefamilyofpossible

solutionsis

generatedbythenullvectorofA.This

isanonzero

vectorzforwhich

Az=

0

Thegeneralform

ofthesolutionis

oneparticularsolution,sayourvectorx,plus

anyarbitrary

parameter

times

thenullvector.

Foranyvalueoftthevector

y=

x+tz

68Chapter5.

LinearEquations

isasolutionto

Ay=

b

InMatlab

z=

null(A)

A*z

t=

rand

y=

x+

t*z

A*y

You

canseethatA*zis

zero

andA*yis

equalto

b.

“Theirave

rageis

three.”

Let’s

return

tothequestionthatIasked

youto

consider

atthebeginningofthis

chapter.

I’m

thinkingof

twonumbers.

Theiraverageis

three.

Whatare

the

numbers?

Whatpop

ped

into

you

rhead?Youprobably

realizedthatIhadn’tgiven

you

enoughinform

ation.Butyoumust

havethoughtof

somesolution.In

myexperi-

ence,themost

frequentresponse

is“2and4”.Let’s

seewhatMatlabresponds.

Myproblem

ison

elinearequationin

twounknow

nsThematrix

andright

handsideare

A=

[1/2

1/2]

b=

3

Wewan

tto

solveAx=

b.Thisisnow

anunderdetermined

system

.Thereare

fewer

equationsthanunknow

ns,

sothereareinfinitelymanysolutions.

Backslash

offersonepossible

solution

x=

A\b

x=

6 0

Ibet

youdidn’tthinkofthis

solution.

Ifwetryinv(A)*bweget

anerrormessagebecause

rectangularmatrices

do

nothaveinverses.Butthereis

somethingcalled

thepseudoinverse.

Wecantry

that. x

=pinv(A)*b

x=

3 3

Page 40: Experiments With MatLab Moled 2011

69

Did

thatsolutionoccurto

you?

Thesetw

ox’s

are

just

twomem

bersoftheinfinitefamilyofsolutions.

Ifwe

wan

tedMatlab

tofindthe[24]’solution,wewould

haveto

pose

aproblem

wherethesolutionis

constrained

tobeapair

ofintegers,

close

toeach

other,but

notequal.

Itis

possible

tosolvesuch

problems,

butthatwould

takeustoofar

afield.

MyRules.

This

chapterillustratestw

ofundamentalfactsabou

ttechnicalcomputing.

•Thehardestquantities

tocompute

are

ones

thatdonotexist.

•Thenexthardestare

ones

thatarenotunique.

Rec

ap

%%Linear

Equations

Chapter

Recap

%This

is

an

executable

program

that

illustrates

the

statements

%introduced

in

the

Linear

Equations

Chapter

of

"Experiments

in

MATLAB".

%You

can

access

it

with

% %linear_recap

%edit

linear_recap

%publish

linear_recap

%%Backslash

formatbank

A=

[3

12

1;

12

02;

02

3]

b=

[2.36

5.26

2.77]’

x=

A\b

%%Forward

slash

x=

b’/A’

%%Inconsistent

singular

system

A(3,:)=

[6

01]

A\b

%%Consistent

singular

system

b(3)=

2.63

%%One

particular

solution

x=

A(1:2,1:2)\b(1:2);

x(3)=

0

A*x

70Chapter5.

LinearEquations

%%

Null

vector

z=

null(A)

A*z

%%

General

solution

t=

rand

%Arbitrary

parameter

y=

x+

t*z

A*y

Exe

rcises

5.1

Two-by-two.Use

backslash

totryto

solveeach

ofthesesystem

sof

equations.

Indicate

ifthesolutionexists,andifitunique.

(a)

( 10

02

) x=

( −1 2

)(b)

( 12

34

) x=

( 1 1

)(c)

( 12

36

) x=

( 1 2

)(d)

( 12

36

) x=

( 1 3

)

5.2

Three-by-three.

Use

backslash

totryto

solveeach

ofthesesystem

sof

equations.

Indicate

ifthesolutionexists,andifitunique.

(a)

⎛ ⎝10

00

20

00

3

⎞ ⎠ x=

⎛ ⎝1 1 1

⎞ ⎠(b)

⎛ ⎝9

−36

30−3

6192

−180

30−1

80180

⎞ ⎠ x=

⎛ ⎝1 0 0

⎞ ⎠

Page 41: Experiments With MatLab Moled 2011

71

(c)

⎛ ⎝12

34

12

67

812

⎞ ⎠ x=

⎛ ⎝3 12

15

⎞ ⎠(d)

⎛ ⎝81

63

57

49

2

⎞ ⎠ x=

⎛ ⎝1 1 1

⎞ ⎠(e)

⎛ ⎝12

34

56

78

9

⎞ ⎠ x=

⎛ ⎝1 1 1

⎞ ⎠(f)

⎛ ⎝12

34

56

78

9

⎞ ⎠ x=

⎛ ⎝1 0 0

⎞ ⎠

5.3

Nullvector.

Findanonzero

solutionzto

⎛ ⎝12

34

56

78

9

⎞ ⎠ z=

⎛ ⎝0 0 0

⎞ ⎠

5.4

Matrix

equations.

Backslash

canbeusedto

solvematrix

equationsoftheform

AX

=B

whereB

hasseveralcolums.

Doyourecognizethesolutionto

thefollow

ingequa-

tion?⎛ ⎝

53

−52

23−2

28

38

−768

−37

⎞ ⎠ X=

⎛ ⎝360

00

0360

00

0360

⎞ ⎠

5.5

More

Fruit.Alice

buysfourap

ples,

twodozenbananas,

andtw

ocantaloupes

for$4.14.Bobbuysadozenapplesandtw

ocantaloupes

for$5.26.Carolbuysa

halfdozenbananasandthreecantaloupes

for$2.97.How

much

dosingle

piecesof

each

fruitcost?(Y

oumightwantto

setformatbank.)

5.6

Truss.Figure

5.1

dep

icts

aplanetruss

hav

ing13mem

bers(thenumbered

lines)

connecting8joints

(thenumbered

circles).Theindicatedloads,in

tons,are

applied

72Chapter5.

LinearEquations

12

56

8

34

7

13

57

911

12

26

1013

48

1015

20

Figure

5.1.A

planetruss.

atjoints

2,5,and6,

andwewan

tto

determinetheresultingforceoneach

mem

ber

ofthetruss.

Forthetruss

tobein

staticequilibrium,theremust

benonet

force,

hor-

izontallyorvertically,

atan

yjoint.

Thus,

wecan

determinethemem

ber

forces

byequatingthehorizontalforces

totheleft

andrightat

each

joint,

andsimilarly

equatingtheverticalforces

upward

and

dow

nward

ateach

joint.

Fortheeight

joints,this

would

give16equations,

whichis

more

thanthe13unknow

nfactors

tobedetermined.Forthetruss

tobestaticallydeterminate,thatis,forthereto

beauniquesolution,weassumethatjoint1is

rigidly

fixed

both

horizontallyand

verticallyandthatjoint8isfixed

vertically.

Resolvingthemem

ber

forces

into

hor-

izontalan

dverticalcomponents

anddefiningα

=1/√ 2

,weobtain

thefollow

ing

system

ofequationsforthemem

ber

forces

f i:

Joint2:

f 2=

f 6,

f 3=

10;

Joint3:

αf 1

=f 4

+αf 5,

αf 1

+f 3

+αf 5

=0;

Joint4:

f 4=

f 8,

f 7=

0;

Joint5:

αf 5

+f 6

=αf 9

+f 1

0,

αf 5

+f 7

+αf 9

=15;

Joint6:

f 10=

f 13,

f 11=

20;

Joint7:

f 8+

αf 9

=αf 1

2,

αf 9

+f 1

1+

αf 1

2=

0;

Joint8:

f 13+αf 1

2=

0.

Solvethis

system

ofequationsto

findthevectorfofmem

ber

forces.

Page 42: Experiments With MatLab Moled 2011

73

5.7

Circuit.Figure

5.2

isthecircuit

diagram

forasm

allnetworkofresistors.

12

3

4

5

r 23r 34 r 45

r 25

r 13

r 12r 14

r 35

v s

i 1

i 2i 3

i 4

Figure

5.2.A

resistornetwork.

Thereare

fivenodes,eightresistors,andon

econstantvoltagesource.

Wewan

tto

compute

thevoltagedropsbetweenthenodes

andthecurrents

aroundeach

of

theloops.

Severaldifferentlinearsystem

sofequationscanbeform

edto

describethis

circuit.

Let

v k,k

=1,...,4,denote

thevoltagedifference

between

each

ofthe

firstfournodes

andnodenumber

5andleti k,k

=1,...,4,denote

theclockwise

currentaroundeach

oftheloop

sin

thediagram.Ohm’s

law

saysthatthevoltage

dropacross

aresistoris

theresistance

times

thecurrent.

Forexample,thebranch

betweennodes

1and2gives

v 1−v 2

=r 1

2(i

2−i 1).

Usingtheconductance,whichisthereciprocaloftheresistance,g k

j=

1/r

kj,Ohm’s

law

becomes

i 2−i 1

=g 1

2(v

1−v 2).

Thevoltagesourceis

included

intheequation

v 3−v s

=r 3

5i 4.

Kirchhoff’s

voltage

law

saysthatthesum

ofthevoltagedifferencesaround

each

loopis

zero.For

example,aroundloop1,

(v1−

v 4)+(v

4−v 5)+(v

5−v 2)+(v

2−v 1)=

0.

Combiningthevoltagelaw

with

Ohm’s

law

leadsto

theloopequationsforthe

currents:

Ri=

b.

Hereiis

thecurrentvector,

i=

⎛ ⎜ ⎝i 1 i 2 i 3 i 4

⎞ ⎟ ⎠,

74Chapter5.

LinearEquations

bis

thesourcevoltagevector,

b=

⎛ ⎜ ⎝0 0 0 v s

⎞ ⎟ ⎠,andR

istheresistance

matrix,

⎛ ⎜ ⎝r 25+r 1

2+r 1

4+r 4

5−r

12

−r14

−r45

−r12

r 23+r 1

2+r 1

3−r

13

0−r

14

−r13

r 14+r 1

3+

r 34

−r34

−r45

0−r

34

r 35+

r 45+

r 34

⎞ ⎟ ⎠.Kirchhoff’s

curren

tlawsaysthatthesum

ofthecurrents

ateach

nodeiszero.

For

example,at

node1,

(i1−i 2)+(i

2−

i 3)+(i

3−i 1)=

0.

Combiningthecurrentlaw

withtheconductance

versionofOhm’slaw

leadsto

the

nodalequationsforthevoltages:

Gv=

c.

Herevis

thevoltagevector,

v=

⎛ ⎜ ⎝v 1 v 2 v 3 v 4

⎞ ⎟ ⎠,cis

thesourcecurrentvector,

c=

⎛ ⎜ ⎝0 0

g 35v s 0

⎞ ⎟ ⎠,andG

istheconductance

matrix,

⎛ ⎜ ⎝g 12+

g 13+g 1

4−g

12

−g13

−g14

−g12

g 12+g 2

3+g 2

5−g

23

0−g

13

−g23

g 13+g 2

3+g 3

4+g 3

5−g

34

−g14

0−g

34

g 14+g 3

4+g 4

5

⎞ ⎟ ⎠.You

cansolvethelinearsystem

obtained

from

theloopequationsto

compute

thecurrents

andthen

use

Ohm’s

law

torecover

thevoltages.

Oryou

cansolve

thelinearsystem

obtained

from

thenodeequationsto

compute

thevoltages

and

then

use

Ohm’slaw

torecover

thecurrents.You

rassignmentisto

verifythatthese

twoap

proaches

produce

thesameresultsforthiscircuit.You

canchooseyou

row

nnumericalvalues

fortheresistancesandthevoltagesource.

Page 43: Experiments With MatLab Moled 2011

Chapter6

FractalFern

Thefractalfern

involves

2-by-2matrices.

Theprogramsfernandfinitefernin

theexmtoolbox

produce

theFractal

Ferndescribed

byMichael

Barnsley

inFractalsEverywhere[?].They

generate

and

plotapotentiallyinfinitesequence

ofrandom,butcarefullychoreographed,points

intheplane.

Thecommand

fern

runsforever,producinganincreasingly

dense

plot.

Thecommand

finitefern(n)

generatesnpoints

andaplotlikeFigure

6.1.Thecommand

finitefern(n,’s’)

show

sthegenerationofthepoints

oneatatime.

Thecommand

F=

finitefern(n);

generates,

butdoes

notplot,

npoints

andreturnsanarray

ofzerosandones

for

use

withsparsematrix

andim

age-processingfunctions.

Theexmtoolbox

also

includes

fern.jpg,a768-by-1024colorim

agewithhalf

amillionpoints

thatyoucanview

withabrowserorapaintprogram.Youcanalso

view

thefile

with

F=

imread(’fern.png’);

image(F)

Copyright

c ©2011CleveMoler

Matlab

R ©is

aregisteredtradem

ark

ofMath

Works,

Inc.

TM

October

4,2011

75

76Chapter6.

Fractal

Fern

Figure

6.1.Fractalfern.

Ifyou

liketheim

age,

youmighteven

choose

tomakeit

yourcomputerdesktop

background.How

ever,you

should

reallyrunfernonyou

row

ncomputerto

seethe

dynamicsoftheem

ergingfern

inhighresolution.

Thefern

isgeneratedbyrepeatedtransform

ationsof

apointin

theplane.

Let

xbeavectorwithtw

ocompon

ents,x1andx2,representingthepoint.

Thereare

fourdifferenttransform

ations,

allof

them

oftheform

x→

Ax+b,

withdifferentmatrices

Aandvectors

b.Theseare

know

nasaffinetransform

ations.

Themost

frequentlyusedtransform

ationhas

A=

( 0.85

0.04

−0.04

0.85

) ,b=

( 0 1.6

) .

This

transform

ationshortensandrotatesxalittle

bit,then

adds1.6

toitssecond

component.

Rep

eatedapplicationof

thistransform

ationmoves

thepointupandto

theright,

headingtoward

theupper

tipofthefern.Everyonce

inawhile,

oneof

theother

threetransform

ationsis

picked

atrandom.Thesetransform

ationsmove

Page 44: Experiments With MatLab Moled 2011

77

thepointinto

thelower

subfern

ontheright,

thelower

subfern

ontheleft,orthe

stem

. Hereis

thecomplete

fractalfern

program.

functionfern

%FERN

MATLABimplementationof

the

Fractal

Fern

%MichaelBarnsley,FractalsEverywhere,AcademicPress,1993

%Thisversionrunsforever,or

until

stop

is

toggled.

%Seealso:FINITEFERN.

shg

clfreset

set(gcf,’color’,’white’,’menubar’,’none’,...

’numbertitle’,’off’,’name’,’FractalFern’)

x=

[.5;

.5];

h=

plot(x(1),x(2),’.’);

darkgreen=

[0

2/3

0];

set(h,’markersize’,1,’color’,darkgreen,’erasemode’,’none’);

axis([-33

010])

axisoff

stop=

uicontrol(’style’,’toggle’,’string’,’stop’,

...

’background’,’white’);

drawnow

p=

[.85

.92

.99

1.00];

A1

=[

.85

.04;

-.04

.85];

b1

=[0;

1.6];

A2

=[

.20

-.26;

.23

.22];

b2

=[0;

1.6];

A3

=[-.15

.28;

.26

.24];

b3

=[0;

.44];

A4

=[

00

;0

.16];

cnt=

1;

tic

while~get(stop,’value’)

r=

rand;

if

r<

p(1)

x=

A1*x

+b1;

elseifr

<p(2)

x=

A2*x

+b2;

elseifr

<p(3)

x=

A3*x

+b3;

else x=

A4*x;

end

set(h,’xdata’,x(1),’ydata’,x(2));

cnt=

cnt

+1;

drawnow

78Chapter6.

Fractal

Fern

end

t=

toc;

s=

sprintf(’%8.0f

points

in

%6.3f

seconds’,cnt,t);

text(-1.5,-0.5,s,’fontweight’,’bold’);

set(stop,’style’,’pushbutton’,’string’,’close’,...

’callback’,’close(gcf)’)

Let’s

examinethis

program

afew

statements

atatime.

shg

standsfor“show

graphwindow

.”It

bringsan

existinggraphicswindow

forw

ard,

orcreatesanew

oneifnecessary.

clfreset

resets

most

ofthefigure

properties

totheirdefault

values.

set(gcf,’color’,’white’,’menubar’,’none’,...

’numbertitle’,’off’,’name’,’FractalFern’)

changes

thebackgroundcolorof

thefigure

window

from

thedefault

gray

towhite

andprovides

acustomized

titleforthewindow

.

x=

[.5;

.5];

provides

theinitialcoordinatesofthepoint.

h=

plot(x(1),x(2),’.’);

plots

asingle

dotin

theplanean

dsavesahandle,h,so

thatwecanlatermodify

theproperties

oftheplot.

darkgreen=

[0

2/3

0];

defines

acolorwheretheredandbluecompon

ents

arezero

andthegreencomponent

istw

o-thirdsofitsfullintensity.

set(h,’markersize’,1,’color’,darkgreen,’erasemode’,’none’);

makes

thedotreferencedbyhsm

aller,changes

itscolor,andspecifies

thattheim

age

ofthedotonthescreen

should

notbeerasedwhen

itscoordinatesare

changed.A

record

oftheseold

points

iskeptbythecomputer’sgraphicshardware(untilthe

figure

isreset),butMatlabitselfdoes

notremem

ber

them

.

axis([-33

010])

axisoff

specifies

thattheplotshould

cover

theregion

−3≤

x1≤

3,0≤

x2≤

10,

butthattheax

esshould

notbedrawn.

Page 45: Experiments With MatLab Moled 2011

79

stop=

uicontrol(’style’,’toggle’,’string’,’stop’,

...

’background’,’white’);

createsatoggle

userinterface

control,

labeled

’stop’andcoloredwhite,

inthe

defaultpositionnearthelower

left

corner

ofthefigure.Thehandle

forthecontrol

issavedin

thevariable

stop.

drawnow

causestheinitialfigure,includingtheinitialpoint,

toactuallybeplotted

onthe

computerscreen.

Thestatement

p=

[.85

.92

.99

1.00];

sets

upavectorofprobabilities.

Thestatements

A1

=[

.85

.04;

-.04

.85];

b1

=[0;

1.6];

A2

=[

.20

-.26;

.23

.22];

b2

=[0;

1.6];

A3

=[-.15

.28;

.26

.24];

b3

=[0;

.44];

A4

=[

00

;0

.16];

definethefouraffinetransform

ations.

Thestatement

cnt=

1;

initializesacounterthatkeepstrack

ofthenumber

ofpoints

plotted.Thestatement

tic

initializesastopwatchtimer.Thestatement

while~get(stop,’value’)

beginsawhileloopthatrunsaslongasthe’value’property

ofthestoptoggle

isequalto

0.Clickingthestoptoggle

changes

thevaluefrom

0to

1andterm

inates

theloop

. r=

rand;

generatesapseudorandom

valuebetween0and1.Thecompoundifstatement

if

r<

p(1)

x=

A1*x

+b1;

elseifr

<p(2)

x=

A2*x

+b2;

elseifr

<p(3)

x=

A3*x

+b3;

else x=

A4*x;

end

80Chapter6.

Fractal

Fern

pickson

eofthefouraffi

netransform

ations.

Because

p(1)is0.85,thefirsttrans-

form

ationis

chosen85%

ofthetime.

Theother

threetransform

ationsare

chosen

relativelyinfrequently.

set(h,’xdata’,x(1),’ydata’,x(2));

changes

thecoordinatesof

thepointhto

thenew

(x1,x

2)andplots

thisnew

point.

Butget(h,’erasemode’)is’none’,so

theold

pointalsoremainson

thescreen.

cnt=

cnt

+1;

counts

onemore

point.

drawnow

tellsMatlabto

takethetimeto

redraw

thefigure,show

ingthenew

pointalong

withalltheold

ones.W

ithoutthiscommand,nothingwould

beplotted

untilstop

istoggled.

end

matches

thewhileatthebeginningoftheloop

.Finally,

t=

toc;

readsthetimer.

s=

sprintf(’%8.0f

points

in

%6.3f

seconds’,cnt,t);

text(-1.5,-0.5,s,’fontweight’,’bold’);

displaystheelapsedtimesince

ticwas

called

andthefinalcountofthenumber

ofpoints

plotted

.Finally,

set(stop,’style’,’pushbutton’,’string’,’close’,...

’callback’,’close(gcf)’)

changes

thecontrolto

apush

buttonthatclosesthewindow

.

Rec

ap

%%

Fern

Chapter

Recap

%This

is

an

executable

program

that

illustrates

the

statements

%introduced

in

the

Fern

Chapter

of

"Experiments

in

MATLAB".

%You

can

access

it

with

% %fern_recap

%edit

fern_recap

%publish

fern_recap

% %Related

EXM

programs

%

Page 46: Experiments With MatLab Moled 2011

81

%fern

%finitefern

%%fern.jpg

F=

imread(’fern.png’);

image(F)

%%A

few

graphics

commands

shg

clfreset

set(gcf,’color’,’white’)

x=

[.5;

.5];

h=

plot(x(1),x(2),’.’);

darkgreen=

[0

2/3

0];

set(h,’markersize’,1,’color’,darkgreen,’erasemode’,’none’);

set(h,’xdata’,x(1),’ydata’,x(2));

axis([-33

010])

axisoff

stop=

uicontrol(’style’,’toggle’,’string’,’stop’,’background’,’white’);

drawnow

cnt=

12345;

t=

5.432;

s=

sprintf(’%8.0f

points

in

%6.3f

seconds’,cnt,t);

text(-1.5,-0.5,s,’fontweight’,’bold’);

set(stop,’style’,’pushbutton’,’string’,’close’,’callback’,’close(gcf)’)

Exe

rcises

6.1

Ferncolor.

Changethefern

colorschem

eto

use

pinkonablack

background.

Don’tforget

thestopbutton.

6.2

Flipthefern.Flipthefern

byinterchangingitsx-an

dy-coordinates.

6.3

Erase

mode.

(a)W

hathappensifyouresize

thefigure

window

whilethefern

isbeinggenerated?

Why?

(b)Theexmprogram

finiteferncanbeusedto

produce

printedoutputofthe

fern.Explain

whyprintingis

possible

withfinitefern.mbutnotwithfern.m.

6.4

Fernstem

.(a)W

hathappensto

thefern

ifyouchangetheon

lynonzero

elem

entin

thematrix

A4?

(b)W

hatarethecoordinatesofthelower

endofthefern’s

stem

?

82Chapter6.

Fractal

Fern

6.5

Fern

tip.

Thecoordinatesof

thepointat

theupper

tipendofthefern

can

becomputedbysolvingacertain

2-by-2

system

ofsimultaneouslinearequations.

Whatis

thatsystem

andwhatarethecoordinatesofthetip?

6.6

Trajectories.Thefern

algorithm

involves

repeatedrandom

choices

from

four

differentform

ulasforad

vancingthepoint.

Ifthekth

form

ula

isusedrepeatedly

byitself,withoutrandom

choices,itdefi

nes

adeterministictrajectory

inthe(x,y)

plane.

Modifyfinitefern.mso

thatplots

ofeach

ofthesefourtrajectories

are

superim

posedontheplotof

thefern.Start

each

trajectory

atthepoint(−

1,5).

Ploto’s

connectedwithstraightlines

forthestepsalongeach

trajectory.Takeas

manystepsas

areneeded

toshow

each

trajectory’slimitpoint.

You

cansuperim

pose

severalplots

with

plot(...)

holdon

plot(...)

plot(...)

holdoff

6.7

Sierpinski’striangle.

Modifyfern.mor

finitefern.mso

thatitproducesSier-

pinski’striangle.

Start

at

x=

( 0 0

) .

Ateach

iterativestep

,thecurrentpointxisreplacedwithAx+b,wherethematrix

Ais

always

A=

( 1/2

00

1/2

)

andthevectorbis

chosenatrandom

withequalprobabilityfrom

amongthethree

vectors b=

( 0 0

) ,b=

( 1/2 0

) ,and

b=

( 1/4

√ 3/4

) .

Page 47: Experiments With MatLab Moled 2011

Chapter7

Google

PageR

ank

Theworld’s

largestmatrix

computation.(T

his

chapteris

outofdate

andneedsa

majoroverhaul.)

OneofthereasonswhyGoogle

TM

issuch

an

effectivesearch

engineis

the

PageR

ank

TM

algorithm

developed

by

Google’s

founders,

Larry

Pageand

Sergey

Brin,when

they

weregraduate

students

atStanford

University.PageR

ankis

de-

term

ined

entirely

bythelinkstructure

oftheWorldW

ideWeb

.It

isrecomputed

aboutonce

amonth

anddoes

notinvo

lvetheactualcontentofanyWeb

pages

orindividualqueries.

Then,foranyparticularquery,

Google

findsthepages

onthe

Web

thatmatchthatqueryandliststhose

pages

intheorder

oftheirPageR

ank.

ImaginesurfingtheWeb,goingfrom

pageto

pagebyrandomly

choosingan

outgoinglinkfrom

onepageto

get

tothenext.

This

can

lead

todead

endsat

pages

with

nooutgoinglinks,

orcycles

around

cliques

ofinterconnected

pages.

So,acertain

fraction

ofthetime,

simply

choose

arandom

pagefrom

theWeb.

This

theoreticalrandom

walk

isknow

nasaMarkovchain

orMarkovprocess.The

limitingprobabilitythatan

infinitelyded

icatedrandom

surfer

visitsan

yparticular

pageis

itsPageR

ank.A

pagehashighrankifother

pages

withhighranklinkto

it.

Let

WbethesetofWeb

pages

thatcanbereached

byfollow

ingachain

of

hyperlinksstartingatsomerootpage,

andletnbethenumber

ofpages

inW

.For

Google,thesetW

actuallyvaries

withtime,

butbyJune2004,nwasover

4billion.

Let

Gbethen-by-n

connectivity

matrix

ofaportionoftheWeb,thatis,g i

j=

1ifthereis

ahyperlinkto

pageifrom

pagejandg i

j=

0otherwise.

Thematrix

Gcanbehuge,

butit

isverysparse.

Itsjthcolumnshow

sthelinksonthejthpage.

Thenumber

ofnonzerosin

Gis

thetotalnumber

ofhyperlinksin

W.

Copyright

c ©2011CleveMoler

Matlab

R ©is

aregisteredtradem

ark

ofMath

Works,

Inc.

TM

October

4,2011

83

84Chapter7.

Goog

lePageR

ank

Let

r iandc j

betherow

andcolumnsumsof

G:

r i=

∑ j

g ij,

c j=

∑ i

g ij.

Thequantities

r jandc j

are

thein-degreeandout-degreeofthejthpage.

Let

pbe

theprobabilitythattherandom

walk

follow

salink.A

typicalvalueis

p=

0.85.

Then

1−pistheprobabilitythatsomearbitrary

pageischosenandδ=

(1−p)/n

istheprobabilitythataparticularrandom

pageis

chosen.Let

Abethen-by-n

matrix

whose

elem

ents

are

aij=

{ pg i

j/c

j+

δ:

c j�=

01/n

:c j

=0.

Notice

thatA

comes

from

scalingtheconnectivitymatrix

byitscolumnsums.

The

jthcolumnis

theprobabilityofjumpingfrom

thejthpageto

theother

pages

ontheWeb

.If

thejthpageis

adeadend,thatis

hasnoou

t-links,

then

weassigna

uniform

probabilityof1/nto

alltheelem

ents

initscolumn.Most

oftheelem

ents

ofA

are

equalto

δ,theprobabilityof

jumpingfrom

onepageto

another

without

follow

ingalink.Ifn=

4·109andp=

0.85,then

δ=

3.75·10−11.

Thematrix

Ais

thetransitionprobabilitymatrix

oftheMarkov

chain.Its

elem

ents

are

allstrictly

betweenzero

andoneanditscolumnsumsare

allequalto

one.

Anim

portantresultin

matrix

theory

know

nas

thePerron–Frobeniustheorem

applies

tosuch

matrices.It

concludes

thatanonzero

solutionof

theequation

x=

Ax

exists

andis

uniqueto

within

ascalingfactor.

Ifthis

scalingfactoris

chosenso

that

∑ i

xi=

1,

then

xis

thestate

vectoroftheMarkov

chain

and

isGoogle’s

PageR

ank.

The

elem

ents

ofxare

allpositiveandless

thanone.

Thevectorxis

thesolutionto

thesingular,

homogeneouslinearsystem

(I−A)x

=0.

For

modestn,an

easy

way

tocompute

xin

Matlabisto

start

withsomeapprox-

imate

solution,such

asthePageR

anksfrom

thepreviousmonth,or

x=

ones(n,1)/n

Then

simply

repeattheassignmentstatement

x=

A*x

untilsuccessivevectors

agreeto

within

aspecified

tolerance.This

isknow

nas

the

power

method

andis

abou

ttheon

lypossible

approach

forverylargen.

Inpractice,

thematrices

GandA

are

never

actuallyform

ed.Onestep

ofthe

pow

ermethodwould

bedonebyonepass

over

adatabase

ofWeb

pages,updating

weightedreference

counts

generatedbythehyperlinksbetweenpages.

Page 48: Experiments With MatLab Moled 2011

85

Thebestway

tocompute

PageR

ankin

Matlabis

totakeadvantageofthe

particularstructure

oftheMarkov

matrix.Hereis

anapproach

thatpreserves

the

sparsityofG.Thetransitionmatrix

canbewritten

A=

pGD

+ez

T

whereD

isthediagonalmatrix

form

edfrom

thereciprocals

oftheoutdegrees,

djj=

{ 1/c j

:c j

�=0

0:

c j=

0,

eis

then-vectorofallon

es,andzis

thevectorwithcomponents

z j=

:c j

�=0

1/n

:c j

=0.

Therank-onematrix

ezT

accounts

fortherandom

choices

ofWeb

pages

thatdo

notfollow

links.

Theequation

x=

Ax

canbewritten

(I−pGD)x

=γe

where γ

=zTx.

Wedonotknow

thevalueof

γbecause

itdep

endsupontheunknow

nvectorx,but

wecantemporarily

takeγ=

1.Aslongaspisstrictly

less

thanone,

thecoeffi

cient

matrix

I−pGD

isnonsingularan

dtheequation

(I−pGD)x

=e

canbesolved

forx.Then

theresultingxcanberescaledso

that

∑ i

xi=

1.

Notice

thatthevectorzis

notactuallyinvolved

inthis

calculation.

Thefollow

ingMatlabstatements

implementthis

approach

c=

sum(G,1);

k=

find(c~=0);

D=

sparse(k,k,1./c(k),n,n);

e=

ones(n,1);

I=

speye(n,n);

x=

(I

-p*G*D)\e;

x=

x/sum(x);

Thepow

ermethodcanalso

beim

plementedin

away

thatdoes

notactually

form

theMarkov

matrix

andso

preserves

sparsity.

Compute

86Chapter7.

Goog

lePageR

ank

G=

p*G*D;

z=

((1-p)*(c~=0)

+(c==0))/n;

Start

with

x=

e/n

Then

repeatthestatement

x=

G*x

+e*(z*x)

untilxsettlesdow

nto

severaldecim

alplaces.

Itis

alsopossible

touse

analgorithm

know

nas

inverseiteration.

A=

p*G*D

+delta

x=

(I

-A)\e

x=

x/sum(x)

Atfirstglance,this

appears

tobeaverydangerousidea.Because

I−

Ais

the-

oreticallysingular,

with

exact

computation

somediagonalelem

entof

theupper

triangularfactorofI−

Ashould

bezero

andthis

computationshould

fail.But

withroundofferror,

thecomputedmatrix

I-

Ais

probably

notexactly

singular.

Even

ifit

issingular,

roundoff

duringGaussianelim

inationwillmost

likelypre-

ventanyexact

zero

diagonalelem

ents.Weknow

thatGaussianelim

inationwith

partialpivotingalwaysproducesasolutionwithasm

allresidual,

relativeto

the

computedsolution,even

ifthematrix

isbadly

conditioned.Thevectorobtained

withthebackslash

operation,(I

-A)\e

,usuallyhasverylargecomponents.If

itis

rescaledbyitssum,theresidualis

scaledbythesamefactorandbecomes

very

small.Consequently,

thetw

ovectors

xandA*xequaleach

other

towithin

roundoff

error.

Inthis

setting,solvingthesingularsystem

withGaussianelim

inationblows

up,butit

blowsupin

exactly

therightdirection.

Figure

7.1

isthegraphforatinyexample,withn=

6insteadof

n=

4·1

09.

Pages

ontheWeb

areidentified

bystringsknow

nas

uniform

resourcelocators,

orURLs.

Most

URLsbegin

withhttpbecause

they

use

thehypertext

transfer

protocol.In

Matlab,wecanstore

theURLsasanarray

ofstringsin

acellarray.

This

example

invo

lves

a6-by-1

cellarray.

U=

{’http://www.alpha.com’

’http://www.beta.com’

’http://www.gamma.com’

’http://www.delta.com’

’http://www.rho.com’

’http://www.sigma.com’}

Twodifferentkindsofindexinginto

cellarraysare

possible.Parentheses

denote

subarray

s,includingindividualcells,

andcu

rlybracesden

ote

thecontents

ofthe

cells.

Ifkisascalar,then

U(k)isa1-by-1

cellarray

consistingofthekth

cellin

U,

whileU{k}isthestringin

thatcell.ThusU(1)isasinglecellandU{1}isthestring

’http://www.alpha.com’.

Thinkofmailbox

eswithad

dresses

onacity

street.

B(502)is

thebox

atnumber

502,whileB{502}is

themailin

thatbox

.

Page 49: Experiments With MatLab Moled 2011

87

alph

a

beta

gam

ma

delta

sigm

arh

o

Figure

7.1.A

tinyWeb.

Wecan

generate

theconnectivitymatrix

byspecifyingthepairsofindices

(i,j)ofthenonzero

elem

ents.Because

thereisalinkto

beta.comfrom

alpha.com,

the(2,1)elem

entofG

isnonzero.Thenineconnectionsare

described

by

i=

[2

63

44

56

11]

j=

[1

12

23

33

46]

Asparsematrix

isstoredin

adata

structure

thatrequires

mem

ory

only

forthe

nonzero

elem

ents

andtheirindices.This

ishardly

necessary

fora6-by-6

matrix

withonly

27zero

entries,

butit

becomes

cruciallyim

portantforlarger

problems.

Thestatements

n=

6

G=

sparse(i,j,1,n,n);

full(G)

generate

thesparserepresentationofann-by-n

matrix

withones

inthepositions

specified

bythevectors

iandjanddisplayitsfullrepresentation.

00

01

01

10

00

00

01

00

00

01

10

00

00

10

00

10

10

00

Thestatement

c=

full(sum(G))

88Chapter7.

Goog

lePageR

ank

computesthecolumnsums

c=

22

31

01

Notice

thatc(5)=

0because

the5th

page,

labeled

rho,hasnoout-links.

Thestatements

x=

(I

-p*G*D)\e

x=

x/sum(x)

solvethesparselinearsystem

toproduce

x=

0.3210

0.1705

0.1066

0.1368

0.0643

0.2007

12

34

56

0

0.050.1

0.150.2

0.250.3

0.35

Page

Ran

k

Figure

7.2.Page

RankforthetinyWeb

Thebargraphof

xisshow

nin

figure

7.2.IftheURLsaresorted

inPageR

ank

order

andlisted

alongwiththeirin-andout-degrees,theresultis

page-rank

in

out

url

10.3210

22

http://www.alpha.com

60.2007

21

http://www.sigma.com

20.1705

12

http://www.beta.com

40.1368

21

http://www.delta.com

30.1066

13

http://www.gamma.com

50.0643

10

http://www.rho.com

Page 50: Experiments With MatLab Moled 2011

89

Weseethatalphahasahigher

PageR

ankthandeltaorsigma,even

thoughthey

allhavethesamenumber

ofin-links.

Arandom

surfer

willvisitalphaover

32%

of

thetimeandrhoonly

about6%

ofthetime.

Forthis

tinyexample

withp=

.85,thesm

allestelem

entof

theMarkov

tran-

sitionmatrix

isδ=

.15/6=

.0250.

A=

0.0250

0.0250

0.0250

0.8750

0.1667

0.8750

0.4500

0.0250

0.0250

0.0250

0.1667

0.0250

0.0250

0.4500

0.0250

0.0250

0.1667

0.0250

0.0250

0.4500

0.3083

0.0250

0.1667

0.0250

0.0250

0.0250

0.3083

0.0250

0.1667

0.0250

0.4500

0.0250

0.3083

0.0250

0.1667

0.0250

Notice

thatthecolumnsumsofAare

allequalto

one.

Theexmtoolbox

includes

theprogram

surfer.A

statementlike

[U,G]=

surfer(’http://www.xxx.zzz’,n)

startsataspecified

URLandtriesto

surf

theWeb

untilit

hasvisited

npages.If

successful,itreturnsann-by-1

cellarrayof

URLsan

dann-by-n

sparseconnectivity

matrix.Thefunctionusesurlread,whichwasintroducedin

Matlab6.5,along

withunderlyingJavautilities

toaccess

theWeb

.SurfingtheWeb

automatically

isadangerousundertakingandthis

functionmust

beusedwithcare.SomeURLs

contain

typographicalerrors

and

illegalcharacters.

Thereis

alist

ofURLsto

avoid

thatincludes

.gif

filesand

Web

sitesknow

nto

cause

diffi

culties.

Most

importantly,

surfercanget

completely

bogged

dow

ntryingto

readapagefrom

asite

thatappears

toberesponding,butthatnever

deliversthecomplete

page.

When

this

happens,

itmay

benecessary

tohavethecomputer’soperatingsystem

ruthlessly

term

inate

Matlab.W

iththeseprecautionsin

mind,youcanuse

surfer

togenerate

yourow

nPageR

ankexamples.

Thestatement

[U,G]=

surfer(’http://www.harvard.edu’,500)

accessesthehomepageofHarvard

University

andgeneratesa500-by-500test

case.

Thegraphgeneratedin

August

2003isavailablein

theexmtoolbox

.Thestatements

loadharvard500

spy(G)

produce

aspyplot(F

igure

7.3)thatshow

sthenonzero

structure

oftheconnectivity

matrix.Thestatement

pagerank(U,G)

computespageranks,

producesabargraph(F

igure

7.4)of

theranks,

andprints

themost

highly

ranked

URLsin

PageR

ankorder.

For

theharvard500data,thedozenmost

highly

ranked

pages

are

90Chapter7.

Goog

lePageR

ank

010

020

030

040

050

0

0 50 100

150

200

250

300

350

400

450

500

nz =

263

6

Figure

7.3.Spyplotoftheharvard500graph.

page-rank

in

out

url

10.0843

195

26

http://www.harvard.edu

10

0.0167

21

18

http://www.hbs.edu

42

0.0166

42

0http://search.harvard.edu:8765/

custom/query.html

130

0.0163

24

12

http://www.med.harvard.edu

18

0.0139

45

46

http://www.gse.harvard.edu

15

0.0131

16

49

http://www.hms.harvard.edu

90.0114

21

27

http://www.ksg.harvard.edu

17

0.0111

13

6http://www.hsph.harvard.edu

46

0.0100

18

21

http://www.gocrimson.com

13

0.0086

91

http://www.hsdm.med.harvard.edu

260

0.0086

26

1http://search.harvard.edu:8765/

query.html

19

0.0084

23

21

http://www.radcliffe.edu

TheURL

wherethesearchbegan,www.harvard.edu,dominates.

Likemost

uni-

versities,Harvardis

organized

into

variouscolleges

HarvardMedicalSchool,the

HarvardBusinessSchool,an

dtheRadcliffeInstitute.Youcanseethatthehome

pages

oftheseschools

havehighPageR

ank.W

ithadifferentsample,such

asthe

onegeneratedbyGoogle

itself,therankswou

ldbedifferent.

Page 51: Experiments With MatLab Moled 2011

91

050

100

150

200

250

300

350

400

450

500

0

0.00

2

0.00

4

0.00

6

0.00

8

0.01

0.01

2

0.01

4

0.01

6

0.01

8

0.02

Page

Ran

k

Figure

7.4.PageRankoftheharvard500graph.

Further

Rea

ding

Further

readingonmatrix

computationincludes

book

sbyDem

mel

[?],Goluban

dVan

Loan

[?],Stewart

[?,?],andTrefethen

andBau[?].Thedefinitivereferenceson

Fortranmatrix

computationsoftware

are

theLAPACK

Users’GuideandWeb

site

[?].TheMatlabsparsematrix

data

structure

andoperationsare

described

in[?].

Inform

ationavailable

onWeb

sitesab

outPageR

ankincludes

abrief

explanationat

Google[?],atechnicalreport

byPage,Brin,andcolleagues

[?],andacomprehensive

survey

byLangville

andMeyer

[?].

Rec

ap

%%

PageRank

Chapter

Recap

%Thisis

an

executable

program

that

illustrates

the

statements

%introducedin

the

Page

Rank

Chapter

of

"Experiments

in

MATLAB".

%Youcan

access

it

with

% %pagerank_recap

%edit

pagerank_recap

%publish

pagerank_recap

% %Related

EXM

programs

% %surfer

%pagerank

%%

Sparsematrices

92Chapter7.

Goog

lePageR

ank

n=

6

i=

[2

63

44

56

11]

j=

[1

12

23

33

46]

G=

sparse(i,j,1,n,n)

spy(G)

%%

Page

Rank

p=

0.85;

delta=

(1-p)/n;

c=

sum(G,1);

k=

find(c~=0);

D=

sparse(k,k,1./c(k),n,n);

e=

ones(n,1);j

I=

speye(n,n);

x=

(I

-p*G*D)\e;

x=

x/sum(x)

%%

Conventional

power

method

z=

((1-p)*(c~=0)

+(c==0))/n;

A=

p*G*D

+e*z;

x=

e/n;

oldx=

zeros(n,1);

whilenorm(x-

oldx)

>.01

oldx=

x;

x=

A*x;

end

x=

x/sum(x)

%%

Sparse

power

method

G=

p*G*D;

x=

e/n;

oldx=

zeros(n,1);

whilenorm(x-

oldx)

>.01

oldx=

x;

x=

G*x

+e*(z*x);

end

x=

x/sum(x)

%%

Inverse

iteration

x=

(I

-A)\e;

x=

x/sum(x)

%%

Bar

graph

bar(x)

title(’PageRank’)

Page 52: Experiments With MatLab Moled 2011

93

Exe

rcises

7.1

Use

surferandpagerankto

compute

PageR

anksforsomesubsetoftheWeb

thatyou

choose.Doyouseeanyinterestingstructure

intheresults?

7.2

Suppose

thatU

and

Gare

theURL

cell

array

and

theconnectivity

matrix

producedbysurferandthatkis

aninteger.Explain

what

U{k},U(k),G(k,:),G(:,k),U(G(k,:)),U(G(:,k))

are.

7.3

Theconnectivitymatrix

fortheharvard500data

sethasfoursm

all,alm

ost

entirely

nonzero,submatrices

thatproduce

dense

patches

nearthediagonalofthe

spyplot.

Youcanuse

thezoom

buttonto

findtheirindices.Thefirstsubmatrix

hasindices

around

170and

theother

threehaveindices

inthe200sand

300s.

Mathem

atically,

agraphwitheverynodeconnectedto

everyother

nodeis

know

nas

aclique.

Identify

theorganizationswithin

theHarvard

community

thatare

responsible

forthesenearcliques.

7.4

AWeb

connectivitymatrix

Ghasg i

j=

1ifit

ispossible

toget

topageifrom

pagejwithoneclick.Ifyoumultiply

thematrix

byitself,theentriesofthematrix

G2countthenumber

ofdifferentpathsof

length

twoto

pageifrom

pagej.

The

matrix

pow

erG

pshow

sthenumber

ofpathsof

length

p.

(a)Fortheharvard500data

set,findthepow

erpwherethenumber

ofnonze-

rosstopsincreasing.In

other

words,foranyqgreaterthanp,nnz(G^q)isequalto

nnz(G^p).

(b)W

hatfraction

oftheentriesin

Gpare

nonzero?

(c)Use

subplotandspyto

show

thenonzerosin

thesuccessivepow

ers.

(d)Is

thereasetofinterconnectedpages

thatdonotlinkto

theother

pages?

7.5

Thefunctionsurferusesasubfunction,hashfun,to

speedupthesearchfora

possibly

new

URLin

thelist

ofURLsthathavealreadybeenprocessed.Findtw

odifferentURLsonTheMathWorkshomepagehttp://www.mathworks.comthat

havethesamehashfunvalue.

7.6

Figure

7.5

isthegraphofanother

six-nodesubsetoftheWeb.In

thisexample,

thereare

twodisjointsubgraphs.

(a)W

hatis

theconnectivitymatrix

G?

(b)W

hatarethePageR

anksifthehyperlinktransitionprobabilitypis

the

defaultvalue0.85?

(c)Describewhathappenswiththisexample

toboth

thedefinitionofPageR

-ankandthecomputationdonebypagerankin

thelimit

p→

1.

7.7

Thefunctionpagerank(U,G)computesPageR

anksbysolvingasparselinear

94Chapter7.

Goog

lePageR

ank

alph

a

beta

gam

ma

delta

sigm

arh

o

Figure

7.5.Another

tinyWeb.

system

.It

then

plots

abargraphan

dprints

thedominantURLs.

(a)Create

pagerank1(G)bymodifyingpagerankso

thatitjust

computesthe

PageR

anks,

butdoes

notdoan

yplottingorprinting.

(b)Create

pagerank2(G)bymodifyingpagerank1to

use

inverse

iteration

insteadof

solvingthesparselinearsystem

.Thekey

statements

are

x=

(I

-A)\e

x=

x/sum(x)

Whatshould

bedonein

theunlikelyeventthatthebackslash

operationinvo

lves

adivisionbyzero?

(c)Create

pagerank3(G)bymodifyingpagerank1to

use

thepow

ermethod

insteadof

solvingthesparselinearsystem

.Thekey

statements

are

G=

p*G*D

z=

((1-p)*(c~=0)

+(c==0))/n;

whiletermination_test

x=

G*x

+e*(z*x)

end

Whatis

anappropriate

test

forterm

inatingthepow

eriteration?

(d)Use

you

rfunctionsto

compute

thePageR

anksof

thesix-nodeexample

discussed

inthetext.

Makesure

you

getthecorrectresultfrom

each

ofyou

rthree

functions.

7.8

Hereis

yet

another

functionforcomputingPageR

ank.This

versionusesthe

pow

ermethod,butdoes

notdoan

ymatrix

operations.

Only

thelinkstructure

of

theconnectivitymatrix

isinvo

lved.

function[x,cnt]=

pagerankpow(G)

Page 53: Experiments With MatLab Moled 2011

95

%PAGERANKPOW

PageRank

by

power

method.

%x

=pagerankpow(G)

is

the

PageRank

of

the

graph

G.

%[x,cnt]

=pagerankpow(G)

%counts

the

number

of

iterations.

%Link

structure

[n,n]=

size(G);

forj

=1:n

L{j}=

find(G(:,j));

c(j)=

length(L{j});

end

%Power

method

p=

.85;

delta=

(1-p)/n;

x=

ones(n,1)/n;

z=

zeros(n,1);

cnt=

0;

whilemax(abs(x-z))>

.0001

z=

x;

x=

zeros(n,1);

forj

=1:n

if

c(j)

==

0

x=

x+

z(j)/n;

else x(L{j})=

x(L{j})

+z(j)/c(j);

end

end

x=

p*x

+delta;

cnt=

cnt+1;

end (a)How

dothestoragerequirem

ents

andexecutiontimeofthisfunctioncom-

pare

withthethreepagerankfunctionsfrom

thepreviousexercise?

(b)Use

thisfunctionasatemplate

towrite

afunctionthatcomputesPageR

-ankin

someother

programminglanguage.

96Chapter7.

Goog

lePageR

ank

Page 54: Experiments With MatLab Moled 2011

Chapter8

Exp

onen

tialFunction

Thefunctionez.

Ihopeyou

havealiveMatlab

and

theexm

functionshandy.

Enterthe

statement

expgui

Click

onthebluelinewithyourmouse.Moveituntilthegreen

lineisontopofthe

blueline.

Whatis

theresultingvalueofa?

Theexponentialfunctionisdenotedmathem

aticallybyet

andin

Matlabby

exp(t).This

functionis

thesolutionto

theworld’s

simplest,an

dperhapsmost

important,differentialequation,

y=

ky

Thisequationisthebasisforanymathem

aticalmodeldescribingthetimeevolution

ofaquantity

witharate

ofproductionthatis

proportionalto

thequantity

itself.

Such

modelsincludepopulations,

investm

ents,feedback,an

dradioactivity.

We

are

usingtfortheindep

endentvariable,yforthedep

endentvariable,kforthe

proportionality

constant,and

y=

dy dt

fortherate

ofgrowth,or

derivative,

withrespectto

t.Weare

lookingforafunction

thatis

proportionalto

itsow

nderivative.

Let’s

start

byexaminingthefunction

y=

2t

Copyright

c ©2011CleveMoler

Matlab

R ©is

aregisteredtradem

ark

ofMath

Works,

Inc.

TM

October

4,2011

97

98Chapter8.

Exp

onential

Function

00.

20.

40.

60.

81

1.2

1.4

1.6

1.8

20

0.51

1.52

2.53

3.54

Figure

8.1.Thebluecurveis

thegraphofy=

2t.Thegreencurveis

the

graphoftherate

ofgrowth,y=

dy/dt.

Weknow

what2t

meansiftis

aninteger,2t

isthet-th

pow

erof2.

2−1=

1/2,

20=

1,

21=

1,22

=4,...

Wealsoknow

what2t

meansif

t=

p/qis

arationalnumber,theratiooftw

ointegers,

2p/qis

theq-th

rootofthep-thpow

erof2.

21/2=

√ 2=

1.4142...,

25/3=

3√ 25=

3.1748...,

2355/113=

113√ 2

355=

8.8250

...

Inprincipal,forfloatingpointarithmetic,this

isallweneedto

know

.Allfloating

pointnumbersare

ratiosof

twointegers.

Wedonothaveto

beconcerned

yet

about

thedefinitionof2t

forirrationalt.

IfMatlabcancompute

pow

ersan

droots,we

canplotthegraphof2t,thebluecu

rvein

figure

8.1

Whatisthederivativeof2t?May

beyou

havenever

considered

thisquestion,

ordon’t

remem

ber

theansw

er.

(Becareful,

itis

nott2

t−1.)

Wecan

plotthe

graphoftheapproxim

ate

derivative,usingastep

size

ofsomethinglike0.0001.The

follow

ingcodeproducesfigure

8.1,thegraphsofbothy=

2tanditsapproxim

ate

derivative,y.

t=

0:.01:2;

h=

.00001;

y=

2.^t;

ydot=

(2.^(t+h)

-2.^t)/h;

plot(t,[y;ydot])

Thegraphofthederivative

hasthesameshapeasthegraphoftheoriginal

function.Let’s

lookattheirratio,y(t)/y(t).

Page 55: Experiments With MatLab Moled 2011

99

00.

20.

40.

60.

81

1.2

1.4

1.6

1.8

20.

5

0.550.6

0.650.7

0.750.8

0.850.9

Figure

8.2.Theratio,y/y

.

plot(t,ydot./y)

axis([02

.5

.9])

Weseethattheratioofthederivativeto

thefunction,show

nin

figure

8.2,hasa

constantvalue,

y/y=

0.6931...,thatdoes

notdep

endupont.

Now

,if

you

are

follow

ingalongwith

aliveMatlab,repeatthepreceding

calculationswithy=

3tinsteadof

y=

2t.Youshould

findthattheratiois

again

indep

endentoft.

This

timey/y=

1.0986....Betteryet,experim

entwithexpgui.

Ifwetakeanyvalueaandlook

aty=

at,wefindthat,

numericallyatleast,

theratioy/yis

constant.

Inother

words,

yis

proportionalto

y.

Ifa=

2,the

proportionality

constantis

less

thanone.

Ifa=

3,theproportionality

constantis

greaterthanone.

Canwefindanaso

thaty/yis

actuallyequalto

one?

Ifso,we

havefoundafunctionthatis

equalto

itsow

nderivative.

Theapproxim

ate

derivative

ofthefunctiony(t)=

atis

y(t)=

at+

h−at

h

This

canbefactoredandwritten

y(t)=

ah−1

hat

Sotheratioofthederivative

tothefunctionis

y(t)

y(t)=

ah−1

h

Theratiodep

endsuponh,butnotupon

t.If

wewanttheratioto

beequalto

1,

weneedto

findaso

that

ah−

1

h=

1

100

Chapter8.

Exp

onential

Function

Solvingthis

equationfora,wefind

a=

(1+

h)1

/h

Theap

proxim

ate

derivative

becomes

more

accurate

ash

goes

tozero,so

weare

interested

inthevalueof

(1+h)1

/h

ash

approaches

zero.

This

involvestakingnumbersveryclose

to1and

raising

them

toverylargepow

ers.

Thesurprisingfact

isthatthis

limitingprocess

defi

nes

anumber

thatturnsoutto

beon

eofthemost

importantquantities

inmathem

atics

e=

lim

h→

0(1

+h)1

/h

Hereis

thebeginningandendofatable

ofvalues

generatedbyrepeatedly

cutting

hin

half.

formatlong

formatcompact

h=

1;

whileh

>2*eps

h=

h/2;

e=

(1

+h)^(1/h);

disp([he])

end

0.500000000000000

2.250000000000000

0.250000000000000

2.441406250000000

0.125000000000000

2.565784513950348

0.062500000000000

2.637928497366600

0.031250000000000

2.676990129378183

0.015625000000000

2.697344952565099

...

...

0.000000000000014

2.718281828459026

0.000000000000007

2.718281828459036

0.000000000000004

2.718281828459040

0.000000000000002

2.718281828459043

0.000000000000001

2.718281828459044

0.000000000000000

2.718281828459045

Thelast

lineof

outputinvolves

avalueofhthatisnotzero,butisso

smallthatit

prints

asastringofzeros.

Weare

actuallycomputing

(1+2−

51)2

51

whichis (1+

1

2251799813685248

)2251799813685248

Page 56: Experiments With MatLab Moled 2011

101

Theresultgives

usthenumericalvalueofecorrectto

16significantdecim

aldigits.

It’s

easy

toremem

ber

therepeatingpatternofthefirst10

significantdigits.

e=

2.718281828...

Let’s

deriveamore

usefulrepresentationoftheexponentialfunction.Start

byputtingtback

inthepicture.

et=

(lim

h→

0(1

+h)1

/h)t

=lim

h→

0(1

+h)t/h

Hereis

theBinomialTheorem.

(a+b)

n=

an+

nan−1b+

n(n

−1)

2!an−2b2

+n(n

−1)(n−2)

3!

an−3b3

+...

Ifnisaninteger,thisterm

inatesafter

n+1term

swithbn.Butifnisnotaninteger,

theexpansionisaninfiniteseries.Apply

thebinonim

ialtheorem

witha=

1,b=

handn=

t/h.

(1+

h)t/h

=1+(t/h)h

+(t/h)(t/h−1)

2!

h2+

(t/h)(t/h−1)(t/h−2)

3!h3+

...

=1+

t+

t(t−h)

2!

+t(t−h)(t−2h

)

3!

+...

Now

lethgoto

zero.Weget

thepow

erseries

fortheexponentialfunction.

et=

1+t+

t2 2!+

t3 3!+

...+

tn n!+...

This

series

isarigorousmathem

aticaldefinitionthatapplies

toan

yt,

positiveor

negative,

rationalorirrational,realor

complex.Then+

1-stterm

istn/n!.

As

nincreases,

thetn

inthenumeratoris

eventuallyoverwhelmed

bythen!in

the

denominator,so

theterm

sgoto

zero

fast

enoughthattheinfiniteseries

converges.

Itisalm

ost

possibleto

use

thispow

erseries

foractualcomputationof

et.Here

isanexperim

entalMatlabprogram.

functions

=expex(t)

%EXPEX

Experimental

version

of

EXP(T)

s=

1;

term=

1;

n=

0;

r=

0;

whiler

~=

s

r=

s;

n=

n+

1;

term=

(t/n)*term;

s=

s+

term;

end

102

Chapter8.

Exp

onential

Function

Notice

thatthereare

nopow

ersor

factorials.

Each

term

isobtained

from

the

previousoneusingthefact

that

tn n!=

t n

tn−1

(n−1)!

Thepotentiallyinfiniteloopis

term

inatedwhen

r==s,thatis

when

thefloating

pointvalues

oftw

osuccessivepartialsumsareequal.

Thereare“only”tw

othingswrongwith

this

program

–itsspeed

and

its

accuracy.Theterm

sin

theseries

increase

aslongas

|t/n|≥

1,then

decrease

after

nreaches

thepointwhere|t/

n|<

1.Soif|t|

isnottoolarge,

say|t|

<2,everything

isOK;only

afew

term

sare

required

andthesum

iscomputedaccurately.

But

larger

values

oftrequiremore

term

sandtheprogram

requires

more

time.

This

isnotaveryseriousdefectiftis

realandpositive.

Theseries

converges

sorapidly

thattheextratimeis

hardly

noticeable.

How

ever,iftisrealandnegativethecomputedresultmay

beinaccurate.The

term

salternate

insignandcanceleach

other

inthesum

toproduce

asm

allvalue

foret.

Take,forexample,t=

−20.

Thetruevalueofe−

20is

roughly

2·1

0−9.

Unfortunately,thelargestterm

sin

theseries

are(−

20)1

9/19!and

(−20)2

0/20!,

whichareoppositein

signandboth

ofsize

4·107.Thereis16ordersofmagnitude

difference

betweenthesize

ofthelargestterm

san

dthesize

ofthefinalsum.W

ith

only

16digitsofaccuracy,welose

everything.Thecomputedvalueob

tained

from

expex(-20)is

completely

wrong.

For

real,

negativetit

ispossible

togetanaccurate

result

from

thepow

erseries

byusingthefact

that

et=

1 e−t

For

complext,

thereis

nosuch

easy

fixfortheaccuracy

diffi

cultiesofthepow

erseries. In

contrast

toitsmore

famouscousin,π,theactualnumericalvalueofeis

notveryim

portant.

It’s

theexpon

entialfunction

et

that’sim

portant.

Infact,Matlabdoesn’thavethevalueofebuiltin.Nevertheless,

wecanuse

e=

expex(1)

tocompute

anap

proxim

ate

valuefore.

Only

seventeen

term

sare

required

toget

floatingpointaccuracy.

e=

2.718281828459045

After

computinge,youcould

then

use

e^t,butexp(t)is

preferable.

Logarithms

Thelogarithm

istheinversefunctionoftheexponential.If

y=

et

Page 57: Experiments With MatLab Moled 2011

103

then

log e(y)=

t

Thefunctionlog e(y)isknow

nasthenaturallogarithm

andisoftendenotedbylny.

More

generally,

if

y=

at

then

log a(y)=

t

Thefunctionlog 1

0(y)is

know

nasthecommon

logarithm.Matlabuseslog(y),

log10(y),an

dlog2(y)forloge(y),log 1

0(y),andlog 2(y).

Exp

onen

tialGrowth

Theterm

exponen

tialgrowth

isoften

usedinform

allyto

describean

ykindof

rapid

growth.Mathem

atically,

theterm

refers

toanytimeevolution,y(t),wheretherate

ofgrowth

isproportionalto

thequantity

itself.

y=

ky

Thesolutionto

this

equationis

determined

foralltbyspecifyingthevalueof

yat

oneparticulart,usuallyt=

0.

y(0)=

y 0

Then

y(t)=

y 0ek

t

Suppose,attimet=

0,wehaveamillionE.colibacteria

inatest

tubeunder

ideallaboratory

conditions.

Twenty

minuteslatereach

bacterium

hasfissioned

toproduce

another

one.

Soatt=

20,thepopulationistw

omillion.Every20minutes

thepopulationdoubles.

Att=

40,it’s

fourmillion.Att=

60,it’s

eightmillion.

Andso

on.Thepopulation,measuredin

millionsofcells,

y(t),is

y(t)=

2t/

20

Let

k=

ln2/20=

.0347.Then,withtmeasuredin

minutesan

dthepopulationy(t)

measuredin

millions,

wehave

y=

ky,

y(0)=

1

Consequently

y(t)=

ekt

Thisisexpon

entialgrow

th,butitcannotgo

onforever.Eventually,

thegrowth

rate

isaffectedbythesize

ofthecontainer.Initiallyatleast,thesize

ofthepop

ulation

ismodelledbytheexpon

entialfunction.

104

Chapter8.

Exp

onential

Function

Suppose,attimet=

0,youinvest

$1000in

asavingsaccountthatpay

s5%

interest,compou

nded

yearly.

Ayearlater,

att=

1,thebankadds5%

of$1000

toyou

raccount,

givingyouy(1)=

1050.Another

yearlateryou

get5%

of1050,

whichis

52.50,givingy(2)=

1102.50.If

y(0)=

1000is

you

rinitialinvestment,

r=

0.05istheyearlyinterest

rate,tismeasuredin

years,andhisthestep

size

for

thecompou

ndinterest

calculation,wehave

y(t+h)=

y(t)+

rhy(t)

Whatiftheinterest

iscompounded

monthly

insteadof

yearly?

Attheendofthe

each

month,you

get.05/12times

yourcurrentbalance

added

toyouraccount.

The

sameequation

applies,butnow

with

h=

1/1

2instead

ofh

=1.

Rew

rite

the

equationas

y(t+

h)−

y(t)

h=

ry(t)

andlethtendto

zero.Weget

y(t)=

ry(t)

This

defines

interest

compounded

continuously.

Theevolutionof

yourinvestment

isdescribed

by

y(t)=

y(0)e

rt

HereisaMatlabprogram

thattabulatesthegrow

thof

$1000invested

at5%

over

a20

yearperiod,withinterest

compounded

yearly,

monthly,andcontinuously.

formatbank

r=

0.05;

y0

=1000;

fort

=0:20

y1

=(1+r)^t*y0;

y2

=(1+r/12)^(12*t)*y0;

y3

=exp(r*t)*y0;

disp([ty1

y2

y3])

end

Thefirstfew

andlast

few

lines

ofoutputare

tyearly

monthly

continuous

01000.00

1000.00

1000.00

11050.00

1051.16

1051.27

21102.50

1104.94

1105.17

31157.63

1161.47

1161.83

41215.51

1220.90

1221.40

51276.28

1283.36

1284.03

..

.......

.......

.......

16

2182.87

2221.85

2225.54

Page 58: Experiments With MatLab Moled 2011

105

17

2292.02

2335.52

2339.65

18

2406.62

2455.01

2459.60

19

2526.95

2580.61

2585.71

20

2653.30

2712.64

2718.28

Compoundinterest

actuallyqualifies

asexponentialgrowth,althoughwithmodest

interest

rates,

most

people

would

notuse

thatterm

.Let’s

borrow

money

tobuyacar.

We’lltakeouta$20,000carloanat10%

per

yearinterest,makemonthly

pay

ments,an

dplanto

pay

offtheloanin

3years.

Whatis

ourmonthly

pay

ment,

p?

Each

monthly

transactionaddsinterest

toour

currentbalance

andsubtractsthemonthly

pay

ment.

y(t+

h)=

y(t)+

rhy(t)−p

=(1

+rh

)y(t)−

p

Apply

this

repeatedly

fortw

o,three,

then

nmonths.

y(t+2h)=

(1+

rh)y(t+h)−p

=(1

+rh

)2y(t)−

((1+

rh)+1)p

y(t+3h)=

(1+

rh)3y(t)−

((1+

rh)2

+(1

+rh

)+1)p

y(t+

nh)=

(1+

rh)ny(0)−((1+

rh)n

−1+...+(1

+rh

)+1)p

=(1

+rh

)ny(0)−((1+

rh)n

−1)/(1+rh

−1)p

Solveforp

p=

(1+

rh)n/((1+

rh)n

−1)rh

y 0

Use

Matlabto

evaluate

this

forourcarloan.

y0

=20000

r=

.10

h=

1/12

n=

36

p=

(1+r*h)^n/((1+r*h)^n-1)*r*h*y0

Wefindthemonthly

pay

mentwould

be

p=

645.34

Ifwedidn’t

haveto

pay

interest

ontheloanandjust

made36monthly

pay

ments,

they

would

be

y0/n

=555.56

It’shard

tothinkaboutcontinuouscompoundingforaloanbecause

wewould

have

tofigure

outhow

tomakeinfinitelymanyinfinitelysm

allpay

ments.

106

Chapter8.

Exp

onential

Function

Complexex

ponen

tial

Whatdowemeanbyez

ifziscomplex?Thebehav

iorisverydifferentfrom

etfor

realt,butequallyinterestingandim

portant.

Let’sstart

withapurely

imaginary

zandsetz=

iθwhereθisreal.Wethen

makethedefi

nition

eiθ=

cosθ+

isinθ

This

form

ula

isremarkab

le.It

defines

theexpon

entialfunctionforan

imaginary

argumentin

term

sof

trig

functionsof

arealargument.

Thereare

severalreasons

whythisisareasonabledefintion.First

ofall,itbehaves

likean

exponentialshould.

Weexpect

eiθ+iψ

=ei

θei

ψ

This

behav

ioris

aconsequence

ofthedouble

angle

form

ulasfortrig

functions.

cos(θ+ψ)

=cosθcosψ−sinθsinψ

sin(θ

+ψ)

=cosθsinψ+sinθcosψ

Secondly,derivativesshould

behaveasexpected.

d dθei

θ=

ieiθ

d2

dθ2

eiθ

=i2ei

θ=

−eiθ

Inwords,

thesecondderivativeshould

bethenegativeof

thefunctionitself.This

worksbecause

thesameistrueofthetrig

functions.

Infact,thiscould

bethebasis

forthedefintionbecause

theinitialconditionsarecorrect.

e0=

1=

cos0+

isin0

Thepow

erseries

isan

other

consideration.Replace

tbyiθ

inthepow

erseries

for

et.Rearrangingterm

sgives

thepow

erseries

forcosθandsinθ.

For

Matlabespecially,

thereisanim

portantconnectionbetweenmultiplica-

tionbyacomplexexpon

entialan

dtherotationmatrices

thatweconsidered

inthe

chapteron

matrices.Let

w=

x+

iybeanyother

complexnumber.W

hatis

eiθw

?Let

uandvbetheresultofthe2-by-2

matrix

multiplication

( u v

) =

( cosθ

−sinθ

sinθ

cosθ

)(x y

)

Then

eiθw

=u+iv

Thissaysthatmultiplicationof

acomplexnumber

byei

θcorrespondsto

arotation

ofthatnumber

inthecomplexplanebyan

angle

θ.

Page 59: Experiments With MatLab Moled 2011

107

Figure

8.3.Twoplots

ofei

θ.

When

theMatlabplotfunctionsees

acomplexvectorasitsfirstargument,

itunderstandsthecompon

ents

tobepoints

inthecomplexplane.

Sotheoctagon

intheleft

halfoffigure

8.3

canbedefined

andplotted

usingei

θwith

theta=

(1:2:17)’*pi/8

z=

exp(i*theta)

p=

plot(z);

Thequantity

pis

thehandle

totheplot.

This

allowsusto

complete

thegraphic

with set(p,’linewidth’,4,’color’,’red’)

axissquare

axisoff

Anexercise

asksyouto

modifythis

codeto

produce

thefive-pointedstarin

the

righthalfofthefigure.

Once

wehavedefined

eiθforrealθ,

itis

clearhow

todefineez

forageneral

complexz=

x+

iy,

ez=

ex+iy

=exei

y

=ex(cosy+

isiny)

Finally,

settingz=

iπ,wegetafamousrelationship

invo

lvingthreeofthe

most

importantquantities

inmathem

atics,e,

i,an

eiπ=

−1Let’s

checkthatMatlabandtheSymbolicToolbox

get

this

right.

>>

exp(i*pi)

ans=

-1.0000+

0.0000i

108

Chapter8.

Exp

onential

Function

>>

exp(i*sym(pi))

ans=

-1

Rec

ap

%%

Exponential

Chapter

Recap

%This

is

an

executable

program

that

illustrates

the

statements

%introduced

in

the

Exponential

Chapter

of

"Experiments

in

MATLAB".

%You

can

access

it

with

% %exponential_recap

%edit

exponential_recap

%publish

exponential_recap

% %Related

EXM

programs

% %expgui

%wiggle

%%

Plot

a^t

and

its

approximate

derivative

a=

2;

t=

0:.01:2;

h=

.00001;

y=

2.^t;

ydot=

(2.^(t+h)

-2.^t)/h;

plot(t,[y;ydot])

%%

Compute

e

formatlong

formatcompact

h=

1;

whileh

>2*eps

h=

h/2;

e=

(1

+h)^(1/h);

disp([he])

end

%%

Experimental

version

of

exp(t)

t=

rand

s=

1;

term=

1;

n=

0;

r=

0;

whiler

~=

s

Page 60: Experiments With MatLab Moled 2011

109

r=

s;

n=

n+

1;

term=

(t/n)*term;

s=

s+

term;

end

exp_of_t=

s

%%Value

of

e

e=

expex(1)

%%Compound

interest

fprintf(’

tyearly

monthly

continuous\n’)

formatbank

r=

0.05;

y0

=1000;

fort

=0:20

y1

=(1+r)^t*y0;

y2

=(1+r/12)^(12*t)*y0;

y3

=exp(r*t)*y0;

disp([ty1

y2

y3])

end

%%Payments

for

acar

loan

y0

=20000

r=

.10

h=

1/12

n=

36

p=

(1+r*h)^n/((1+r*h)^n-1)*r*h*y0

%%Complex

exponential

theta=

(1:2:17)’*pi/8

z=

exp(i*theta)

p=

plot(z);

set(p,’linewidth’,4,’color’,’red’)

axissquareoff

%%Famous

relation

between

e,

iand

pi

exp(i*pi)

%%Use

the

Symbolic

Toolbox

exp(i*sym(pi))

110

Chapter8.

Exp

onential

Function

Exe

rcises

8.1

ecubed.Thevalueof

e3is

close

to20.How

close?

Whatis

thepercentage

error?

8.2

expgui.

(a)W

ithexpgui,thegraphof

y=

at,theblueline,

alwaysintercep

tsthey-axisat

y=

1.W

heredoes

thegraphofdy/dx,thegreen

line,

intercep

tthey-axis?

(b)W

hat

hap

pensifyou

replace

plotbysemilogyin

expgui?

8.3

Computinge.

(a)Ifwetryto

compute

(1+h)1

/hforsm

allvalues

ofhthatare

inversepow

ersof10,

itdoesn’tworkverywell.Since

inversepow

ersof10cannotberepresentedexactly

asbinary

floatingpointnumbers,

theportionofhthateff

ectivelygets

added

to1

isdifferentthanthevalueinvolved

inthecomputationof1/h.That’swhyweused

inversepow

ersof2in

thecomputationshow

nin

thetext.

Try

this:

formatlong

formatcompact

h=

1;

whileh

>1.e-15

h=

h/10;

e=

(1

+h)^(1/h);

disp([he])

end

How

close

doyou

getto

computingthecorrectvalueof

e?(b)Now

trythis

instead:

formatlong

formatcompact

h=

1;

whileh

>1.e-15

h=

h/10;

e=

(1

+h)^(1/(1+h-1));

disp([he])

end

How

welldoes

this

work?W

hy?

8.4

expex.

Modifyexpexbyinserting

disp([terms])

asthelast

statementinsidethewhileloop.

Changetheoutputyou

seeatthe

commandline.

Page 61: Experiments With MatLab Moled 2011

111

formatcompact

formatlong

Explain

whatyouseewhen

youtryexpex(t)forvariousrealvalues

oft.

expex(.001)

expex(-.001)

expex(.1)

expex(-.1)

expex(1)

expex(-1)

Try

someim

aginary

values

oft.

expex(.1i)

expex(i)

expex(i*pi/3)

expex(i*pi)

expex(2*i*pi)

Increase

thewidth

oftheoutputwindow

,changetheoutputform

atandtrylarger

values

oft.

formatlonge

expex(10)

expex(-10)

expex(10*pi*i)

8.5

Instrumen

texpex.

Investigate

both

thecost

andtheaccuracy

ofexpex.Modify

expexso

thatitreturnsboth

thesum

sandthenumber

ofterm

srequired

n.Assess

therelativeerrorbycomparingtheresult

from

expex(t)withtheresult

from

the

built-in

functionexp(t).

relerr=

abs((exp(t)

-expex(t))/exp(t))

Makeatable

show

ingthatthenumber

ofterm

srequired

increasesandtherelative

errordeterioratesforlarget,particularlynegativet.

8.6

Complexwiggle.

Revisewiggleanddot2dotto

create

wigglezanddot2dotz

thatuse

multiplicationbyei

θinsteadof

multiplicationbytw

o-by-twomatrices.The

cruxofwiggleis

G=

[cos(theta)

sin(theta);

-sin(theta)

cos(theta)];

Y=

G*X;

dot2dot(Y);

Inwigglezthis

willbecome

w=

exp(i*theta)*z;

dot2dotz(w)

112

Chapter8.

Exp

onential

Function

Youcanuse

wigglezwithascaledoctogon.

theta=

(1:2:17)’*pi/8

z=

exp(i*theta)

wigglez(8*z)

Or,

withourhouseexpressed

asacomplexvector.

H=

house;

z=

H(1,:)

+i*H(2,:);

wigglez(z)

8.7

Make

thestar.

Recreate

thefive-pointedstarin

therighthalfoffigure

8.3.The

points

ofthestarcanbetraversedin

thedesired

order

with

theta=

(0:3:15)’*(2*pi/5)

+pi/2

Page 62: Experiments With MatLab Moled 2011

Chapter9

TPuzzle

Aclassic

puzzle

dem

onstratescomplexarithmetic.

Figure

9.1.Thewooden

Tpuzzle.Photo

courtesyofShopNew

Zeland,

http://www.shopnewzealand.co.nz.

Ifirstsaw

thewooden

Tpuzzle

show

nin

figure

9.1atPuzzlingWorld

in

Copyright

c ©2011CleveMoler

Matlab

R ©is

aregisteredtradem

ark

ofMath

Works,

Inc.

TM

October

4,2011

113

114

Chapter9.

TPuzzle

Wan

aka,New

Zealand.They

told

methatitwas

theirmost

pop

ularpuzzle.Ihave

since

learned

thatit

was

awell-know

ntoyin

the1800sand

anad

vertisingtool

intheearly1900s.

Theunderlyingmathem

atics

involves

geometry,trigonometry,

andarithmetic

withcomplexnumbers.

Thet_puzzleprogram

intheexmtoolbox

dem

onstratessomeusefulprogrammingtechniques.

Figure

9.2.Thefourpieces.

Figure

9.2show

stheelectronic

versionofthefourpieces.

They

allhavethe

samewidth,butdifferentheights.Oneof

them

hasanunshapelychunkcutou

tof

it,resultingin

anirregularpentagon.

Figure

9.3.TheT.

Itturnsou

tto

bepossible

toarrangethefourpiecesto

form

thecapital“T”

shapeshow

nin

figure

9.3,as

wellas

thearrow

andtherhombusshapes

show

nin

figure

4.4.W

hathappened

tothose

allof

those

45◦

anglesandwhathappened

tothatchunk?

Ifyou

doaGoogle

searchon

“T-puzzle”you

canquickly

seehow

tosolvethe

puzzle

andform

theT,butplease

tryt_puzzleforawhilebefore

yougosurfing

forthesolution.Ifyouclicknearthecenterof

oneofthefourpieces,you

canmove

Page 63: Experiments With MatLab Moled 2011

115

Figure

9.4.Thearrow

andtherhombus.

ithorizontallyandvertically.

Ifyouclicknearoneofthevertices,

you

canrotate

apiece

aboutitscenter.

Ifyou

clickwiththerightmouse

button,or,

onaone-

buttonmouse,hold

dow

nthecontrolkey

whileyouclick,you

canflip

apiece

over

horizontally,

changingitsright/left-handed

orientation.If

youclickin

thesubplot

onthelower

left

ofthewindow

,youcancyclethroughim

ages

ofthethreeshapes.

Thekey

toeff

ectivecomputationinvo

lvingtheT-puzzle

piecesis

theuse

of

complexarithmetic.A

complexnumber

isform

edfrom

apair

ofrealnumbersand

theim

aginary

uniti=

√ −1.For

example,

z=

3+4i

Therealpart

is3andtheim

aginary

part

is4.ThisistheCartesianrepresentation

ofacomplexnumber.

Additionofcomplexnumberssimply

involves

additionoftherealpartsand

oftheim

aginary

parts.

(3+4i)+(5

−i)

=(3

+5)

+(4i−i)

=8+

3i

Multiplicationofcomplexnumbersis

more

interestingbecause

itmakes

use

ofthefact

thati2

=−1

.

(3+4i)·(5−

i)

=(3

·5+(4i)·(−i

))+(3

·(−i

)+(4i)·5)

=(15+

4)+(−

3+20)i

=19+

17i

Afundamentalfact

involvingcomplexnumbersis

Euler’sform

ula.

eiφ=

cosφ+isinφ

Ifyouare

notfamiliarwitheorEuler’sform

ula,seeourchapteronthe“Expon

ential

Function”an

dtheW

ikiped

iaentryon“Euler’sIdentity”.Or,

youcanjust

accept

theform

ula

asconvenientnotation.

116

Chapter9.

TPuzzle

Settingφ=

πleadsto

eiπ

=cosπ+isinπ

=−1

Mov

ingthe−1

totheleft

handsideproducesabeautifulequationinvolvingfive

basicmathem

aticalquantities,e,

i,π,1,

and0.

eiπ+1=

0

Thepolarform

ofacomplexnumber

is

z=

x+iy

=re

where r

=|z|

=√ x

2+

y2

x=

rcosφ

y=

rsinφ

OurT

puzzle

program

usesthefact

thatmultiplicationbyei

θrotatesacom-

plexnumber

throughan

angle

θ.Toseethis,let

w=

eiθ

z=

reiφ

then

w·z

=ei

θ·rei

φ=

rei(θ+φ)

InMatlabtheletter

iis

canbeusedin

anyof

threedifferentroles.

Itcan

beaniterationcounter,

fori

=1:10

orasubscript,

A(i,k)

ortheim

aginary

unit.

z=

3+

4i

Thepolarform

ofacomplexnumber

zisobtained

withtheMatlabfunctions

abs(z)andangle(z).Thequan

tity

eiφis

written

exp(i*phi).Forexample

z=

3+

4i

r=

abs(z)

phi=

angle(z)

w=

r*exp(i*phi)

produces

Page 64: Experiments With MatLab Moled 2011

117

z=

3.0000+

4.0000i

r=

5

phi= 0.9273

w=

3.0000+

4.0000i

−10

12

0123

Figure

9.5.

Thecomplexcoordinatesofthevertices

are

0+

0i,1+

0i,

1+2i,

and0+3i.

ThelargestofthefourpiecesoftheT

puzzle

canberepresentedin

Matlab

bythestatement

z=

[0

11+2i

3i

0]

Thevectorzhasfivecomplexentires.

Thefirsttw

oelem

ents

are

0and1;

their

imaginary

partsare

zero.

Thethirdelem

entis

1+

2i;itsrealpart

is1andits

imaginary

part

is2.After

thatcomes

3i;itsrealpart

iszero

anditsim

aginary

part

is3.Thelast

elem

entofzis

arepeatof

thefirstso

thatthelinedrawnbythe

statement

line(real(z),imag(z))

returnsto

theorigin.Theresult

isfigure

9.5.

Withthisrepresentation,thetranslationsandrotationsrequired

bythegraph-

icsin

t_puzzlecanbeprogrammed

easily

andeffi

ciently.

Translationisveryeasy.

Thestatement

z=

z-

(3-i)/2

repositionsthepiece

infigure

9.5

atoneofthecorners.

Doyouseewhichcorner?

Rotationsarealsoeasily

done.

Thestatements

118

Chapter9.

TPuzzle

−10

12

0123

Figure

9.6.Rotatingthrough

multiplesofninedegrees.

mu

=mean(z(1:end-1))

theta=

pi/20

omega=

exp(i*theta)

z=

omega*(z

-mu)

+mu

rotate

thepiece

aboutitscenterthrough9◦

inthecounterclockwisedirection.Fig-

ure

9.6show

stheresult

ofrepeatingthesestatements

severaltimes.Let’s

look

ateach

step

more

carefully.

Thestatement

mu

=mean(z(1:end-1))

dropsthelast

elem

entof

zbecause

itisarepeatofthefirstan

dthen

computesthe

complexaverageofthecoordinatesofthevertices.

This

gives

thecoordinatesof

whatwecancallthecenterof

thepolygon.Theangle

θ=

π/20

is9◦in

radians.

Thestatements

omega=

exp(i*theta)

z=

omega*(z

-mu)

+mu

translate

thepiece

sothatitscenteris

attheorigin,doacomplexscalartimes

vectormultiplicationto

produce

therotation,andthen

translate

theresultback

toitsoriginalcenter.

Rec

ap

%%

TPuzzle

Chapter

Recap

%This

is

an

executable

program

that

illustrates

the

statements

%introduced

in

the

TPuzzle

Chapter

of

"Experiments

in

MATLAB".

%You

can

access

it

with

Page 65: Experiments With MatLab Moled 2011

119

% %puzzle_recap

%edit

puzzle_recap

%publish

puzzle_recap

% %Related

EXM

programs

% %t_puzzle

%%The

TPuzzle

closeall

figure

t_puzzle

%%Polar

Form

of

aComplex

Number.

z=

3+

4i

r=

abs(z)

phi=

angle(z)

z_again=

r*exp(i*phi)

%%A

Puzzle

Piece.

figure

z=

[0

11+2i

3i

0]

line(real(z),imag(z),’color’,’red’)

axis([-2.51.5-.54.0])

%%Translation.

z=

z-

(3-i)/2

line(real(z),imag(z),’color’,’blue’)

%%Rotation.

mu

=mean(z(1:end-1));

theta=

pi/10;

omega=

exp(i*theta);

z=

omega*(z

-mu)

+mu

line(real(z),imag(z),’color’,’green’)

Exe

rcises

9.1

Complexnumbers.Express

each

ofthesenumbersin

polarform

.

i −4 3−4i

120

Chapter9.

TPuzzle

8+15i

Express

each

ofthesenumbersin

Cartesianform

.

e−iπ

eiπ/3

ei e3

9.2

Stopsign

.Try

this

forn=8andforother

smallinteger

values

ofn.Describe

andexplain

theresults.

n=

8

z=

exp(2*pi*i*(0:n)’/n)

plot(z,’-o’)

axissquare

s=

sum(z)

9.3

Strip.How

manydifferentwaysare

thereto

form

theshapein

figure

9.7

with

theT-puzzle

pieces?

Figure

9.7.A

strip.

9.4

Area.If

thewidth

ofeach

oftheT-puzzle

piecesis

oneunit,whatare

their

areas?

9.5

Sym

metry.W

hichoneof

ourthreeshapes

–T,arrow

andrhombus–does

not

haveanaxis

ofsymmetry?

9.6

Jumpyrotation.Click

nearavertexofoneof

theT-puzzle

piecesandrotate

thepiece

slow

ly.Youshould

seethattherotationis

notsm

ooth,butproceedsin

discretejumps.

Why?

How

largearethejumps?

How

does

t_puzzleaccomplish

this?

9.7

Snappytranslation.Dragon

eoftheT-puzzle

piecesuntilitisclose

to,butnot

exactly

touching,another.W

hen

you

release

themouse

buttonyousometim

essee

thepiece

snapinto

place.Under

whatcircumstancesdoes

this

happen?How

does

t_puzzleaccomplish

it?

Page 66: Experiments With MatLab Moled 2011

121

9.8

Rotation.Reproduce

figure

9.6.

9.9

Differen

tpuzzles.

DoaGoogle

searchon“T-puzzle”.Includethequotesan

dhyphen

inthesearchstringso

thatyouget

anexact

match.SomeoftheWeb

pages

havepieceswithdifferentsizesthantheon

eswehavedescribed

here.

(a)How

manydifferentversionsoftheT-puzzle

arethereontheWeb?

(b)Canyou

makeallthreeof

ourshapes

–theT,arrow

,andrhombus–withthe

piecesshow

non

theseWeb

sites.

(c)Modifyou

rt_puzzleto

use

thesetofpiecesfrom

oneoftheWeb

sites.

122

Chapter9.

TPuzzle

Page 67: Experiments With MatLab Moled 2011

Chapter10

Magic

Squares

Withoriginsin

centuries

old

recreationalmathem

atics,magicsquaresdem

onstrate

Matlabarrayoperations.

Figure

10.1.LoShu.(T

hanks

toByerlyWiser

Cline.)

Magic

squarespredate

recorded

history.AnancientChineselegendtellsofa

turtle

emergingfrom

theLoriver

duringaflood.Theturtle’s

shellshow

edavery

unusualpattern–athree-by-threegridcontainingvariousnumbersofspots.Of

Copyright

c ©2011CleveMoler

Matlab

R ©is

aregisteredtradem

ark

ofMath

Works,

Inc.

TM

October

4,2011

123

124

Chapter10

.Magic

Squares

course,

wedonothavean

yeye-witnessaccounts,so

wecanonly

imaginethatthe

turtle

looked

likefigure

10.1.Each

ofthethreerows,

thethreecolumns,

andthe

twodiagonals

contain

atotalof15spots.Referencesto

LoShuan

dtheLoShu

numericalpatternoccurthroughoutChinesehistory.Today,itisthemathem

atical

basisforFen

gShui,

thephilosophyof

balance

andharm

onyin

oursurroundings

andlives.

An

n-by-n

magic

square

isan

arraycontainingtheintegersfrom

1to

n2,

arranged

sothateach

oftherows,

each

ofthecolumns,

and

thetw

oprincipal

diagonals

havethesamesum.

Foreach

n>

2,therearemanydifferentmagic

squaresof

order

n,buttheMatlabfunctionmagic(n)generatesaparticularone.

Matlabcangenerate

LoShuwith

A=

magic(3)

whichproduces

A=

81

6

35

7

49

2

Thecommand

sum(A)

sumstheelem

ents

ineach

columnto

produce

15

15

15

Thecommand

sum(A’)’

transposesthematrix,sumsthecolumnsofthetranspose,

andthen

transposes

the

resultsto

produce

therow

sums

15

15

15

Thecommand

sum(diag(A))

sumsthemain

diagonalofA,whichrunsfrom

upper

left

tolower

right,to

produce

15

Theop

posite

diagonal,whichrunsfrom

upper

rightto

lower

left,is

less

important

inlinearalgeb

ra,so

findingitssum

isalittle

trickier.

Oneway

todoit

makes

use

ofthefunctionthat“flips”

amatrix

“upside-dow

n.”

Page 68: Experiments With MatLab Moled 2011

125

sum(diag(flipud(A)))

produces 15

This

verifies

thatAhasequalrow,column,an

ddiagonalsums.

Whyis

themagic

sum

equalto

15?Thecommand

sum(1:9)

tellsusthatthesum

oftheintegersfrom

1to

9is45.Iftheseintegersare

allocated

to3columnswithequalsums,

thatsum

must

be

sum(1:9)/3

whichis15.

Thereareeightpossible

waysto

place

atransparency

onan

overheadprojec-

tor.

Sim

ilarly,

thereare

eightmagic

squaresoforder

threethatare

rotationsand

reflectionsofA.Thestatements

fork

=0:3

rot90(A,k)

rot90(A’,k)

end

displayalleightof

them

.

81

68

34

35

71

59

49

26

72

67

24

92

15

93

57

83

48

16

29

42

76

75

39

51

61

84

38

43

86

18

95

17

53

27

62

94

Theseare

allthemagic

squaresoforder

three.

The5is

alwaysin

thecenter,

the

other

oddnumbersare

alwaysin

thecenters

oftheedges,andtheeven

numbers

are

alwaysin

thecorners.

MelancholiaIis

afamousRenaissance

engravingbytheGermanartistand

amateurmathem

aticianAlbrechtDurer.

Itshow

smanymathem

aticalobjects,

in-

cludingasphere,

atruncatedrhombohedron,an

d,in

theupper

righthandcorner,

amagic

square

oforder

4.Youcanseetheengravingin

ourfigure

10.2.Betteryet,

issuetheseMatlabcommands

126

Chapter10

.Magic

Squares

..

Figure

10.2.Albrect

Durer’sMelancolia,1514.

loaddurer

whos

Youwillsee

X648x509

2638656

doublearray

caption

2x28

112

chararray

map

128x3

3072

doublearray

Theelem

ents

ofthearray

Xare

indices

into

thegray

-scale

colormapnamed

map.

Theim

ageis

displayedwith

image(X)

colormap(map)

axisimage

Click

themagnifyingglass

witha“+

”in

thetoolbaranduse

themouse

tozoom

inonthemagic

square

intheupper

right-handcorner.Thescanningresolution

becomes

evidentas

youzoom

in.Thecommands

loaddetail

Page 69: Experiments With MatLab Moled 2011

127

..

Figure

10.3.Detailfrom

Melancolia.

image(X)

colormap(map)

axisimage

displaythehigher

resolutionscanof

theareaaroundthemagic

square

thatwehave

infigure

10.3.

Thecommand

A=

magic(4)

producesa4-by-4

magic

square.

A=

16

23

13

511

10

8

97

612

414

15

1

Thecommands

sum(A),sum(A’),sum(diag(A)),sum(diag(flipud(A)))

yield

enough34’s

toverifythatAis

indeedamagic

square.

The4-by-4

magic

square

generatedbyMatlabis

notthesameasDurer’s

magic

square.Weneedto

interchangethesecondandthirdcolumns.

A=

A(:,[1

32

4])

128

Chapter10

.Magic

Squares

changes

Ato

A=

16

32

13

510

11

8

96

712

415

14

1

Interchangingcolumnsdoes

notchangethecolumnsumsortherowsums.

Itusually

changes

thediagonalsums,butin

thiscase

bothdiagonalsumsare

still34.Sonow

ourmagic

square

matches

theon

ein

Durer’setching.Durerprobably

chose

this

particular4-by-4

square

because

thedate

hedid

thework,1514,occurs

inthe

middle

ofthebottom

row.

Theprogram

durerperminterchanges

rowsandcolumnsin

theim

ageproduced

from

detailbyinterchanginggroupsofrowsandcolumnsin

thearrayX.This

isnotespeciallyim

portantor

useful,butitprovides

aninterestingexercise.

Wehaveseen

twodifferent4-by-4

magic

squares.

Itturnsou

tthatthereare

880differentmagic

squaresoforder

4and

275305224differentmagic

squaresof

order

5.Determiningthenumber

ofdifferentmagic

squaresoforder

6orlarger

isanunsolved

mathem

aticalproblem.

For

amagic

square

oforder

n,themagic

sum

is

μ(n)=

1 n

n2 ∑ k=1

k

whichturnsoutto

be

μ(n)=

n3+

n

2.

Hereis

thebeginningofatable

ofvalues

ofthemagic

sum.

nμ(n)

315

434

565

6111

7175

8260

You

cancompute

μ(n)in

Matlabwitheither

sum(diag(magic(n)))

or

(n^3+

n)/2

Thealgorithmsforgeneratingmatrix

square

fallinto

threedistinct

cases:

Page 70: Experiments With MatLab Moled 2011

129

odd,nis

odd.

singly-even

,nis

divisible

by2,butnotby4.

doubly-even

,nis

divisible

by4.

Thebestknow

nalgorithm

forgeneratingmagic

squaresofoddorder

isdeLa

Loubere’smethod.Sim

ondeLaLouberewas

theFrench

ambassadorto

Siam

inthe

late

17th

century.Isometim

esreferto

his

methodasthe”nor’easter

algorithm”,

after

thewinterstorm

sthatmovenortheasterly

upthecoast

ofNew

England.You

canseewhyifyoufollow

theintegerssequentiallythroughmagic(9).

47

58

69

80

112

23

34

45

57

68

79

911

22

33

44

46

67

78

810

21

32

43

54

56

77

718

20

31

42

53

55

66

617

19

30

41

52

63

65

76

16

27

29

40

51

62

64

75

5

26

28

39

50

61

72

74

415

36

38

49

60

71

73

314

25

37

48

59

70

81

213

24

35

Theintegersfrom

1to

n2are

inserted

alongdiagonals,startingin

themiddle

offirstrowan

dheadingin

anortheasterly

direction.W

hen

you

gooff

anedgeofthe

array,whichyoudoattheveryfirststep,continuefrom

theop

posite

edge.

When

youbumpinto

acellthatis

alreadyoccupied,dropdow

nonerow

andcontinue.

Weusedthis

algorithm

inMatlabformanyyears.Hereis

thecode.

A=

zeros(n,n);

i=

1;

j=

(n+1)/2;

fork

=1:n^2

is

=i;

js

=j;

A(i,j)=

k;

i=

n-

rem(n+1-i,n);

j=

rem(j,n)

+1;

if

A(i,j)

~=

0

i=

rem(is,n)

+1;

j=

js;

end

end

Abig

diffi

cultywiththis

algorithm

andresultingprogram

isthatit

inserts

theelem

ents

oneatatime–itcannotbevectorized.

Afew

years

agowediscoveredanalgorithm

forgeneratingthesamemagic

squaresofoddorder

asdeLaLoubere’smethod,butwithjust

fourMatlabmatrix

operations.

[I,J]=

ndgrid(1:n);

130

Chapter10

.Magic

Squares

A=

mod(I+J+(n-3)/2,n);

B=

mod(I+2*J-2,n);

M=

n*A

+B

+1;

Let’s

seehow

this

workswithn

=5.Thestatement

[I,J]=

ndgrid(1:n)

producesapair

ofmatrices

whose

elem

ents

arejust

therow

andcolumnindices,i

andj. I

=

11

11

1

22

22

2

33

33

3

44

44

4

55

55

5

J=

12

34

5

12

34

5

12

34

5

12

34

5

12

34

5

Usingtheseindices,wegenerate

twomore

matrices.Thestatements

A=

mod(I+J+1,n)

B=

mod(I+2*J-2,n)

produce

A=

34

01

2

40

12

3

01

23

4

12

34

0

23

40

1

B=

13

02

4

24

13

0

30

24

1

41

30

2

02

41

3

Both

AandBare

fledglingmagicsquares.

They

haveequalrow,columnan

ddiagonal

sums.

Buttheirelem

ents

arenottheintegersfrom

1to

n2.Each

hasduplicated

elem

ents

between0an

dn−

1.Thefinalstatement

Page 71: Experiments With MatLab Moled 2011

131

M=

n*A+B+1

producesamatrix

whose

elem

ents

are

integersbetween1an

dn2andwhichhas

equalrow,columnan

ddiagonalsums.

Whatis

notobvious,

butis

true,

isthat

therearenoduplicates.

SoMmust

contain

alloftheintegersbetween1andn2and

consequentlyis

amagic

square.

M=

17

24

18

15

23

57

14

16

46

13

20

22

10

12

19

21

3

11

18

25

29

Thedoubly-even

algorithm

isalsoshort

andsw

eet,andtricky.

M=

reshape(1:n^2,n,n)’;

[I,J]=

ndgrid(1:n);

K=

fix(mod(I,4)/2)

==

fix(mod(J,4)/2);

M(K)=

n^2+1

-M(K);

Let’s

look

atou

rfriendmagic(4).Thematrix

Mis

initiallyjust

theintegers

from

1to

16storedsequentiallyin

4rows.

M=

12

34

56

78

910

11

12

13

14

15

16

Thelogicalarray

Kis

trueforhalfoftheindices

andfalsefortheother

halfin

apatternlikethis.

K=

10

01

01

10

01

10

10

01

Theelem

ents

whereKis

false,

thatis

0,are

left

alone.

.2

3.

5.

.8

9.

.12

.14

15

.

Theelem

ents

whereKis

true,

thatis

1,are

reversed.

16

..

13

.11

10

.

.7

6.

4.

.1

132

Chapter10

.Magic

Squares

Thefinalresult

merges

thesetw

omatrices

toproduce

themagic

square.

Thealgorithm

forsingly

even

order

isthemost

complicatedandso

wewillgive

just

aglimpse

ofhow

itworks.

Ifnis

singly

even

,then

n/2is

oddandmagic(n)

canbeconstructed

from

fourcopiesofmagic(n/2).

Forexample,magic(10)is

obtained

from

A=

magic(5)byform

ingablock

matrix.

[A

A+50

A+75

A+25]

Thecolumnsumsareallequalb

ecause

sum(A)+

sum(A+75)equalssum(A+50)+

sum(A+25).

Buttherowssumsare

notquiteright.

Thealgorithm

must

finishbydoingafew

swapsof

piecesofrowsto

cleanuptherow

sums.

For

thedetails,

issuethecom-

mand. typemagic 9

10

1112

Figure

10.4.Surf

plots

ofmagicsquaresoforder

9,10,11,12.

Let’s

concludethis

chapterwithsomegraphics.

Figure

10.4

show

s

surf(magic(9))

surf(magic(10))

surf(magic(11))

surf(magic(12))

You

canseethethreedifferentcases–on

theleft,theupper

right,

andthelower

right.

Ifyou

increase

ofeach

oftheordersby4,you

getmore

cells,

buttheglobal

shapes

remain

thesame.

Theoddncase

ontheleft

remindsmeofOrigami.

Page 72: Experiments With MatLab Moled 2011

133

Further

Rea

ding

ThereasonswhyMatlabhasmagic

squarescanbetracedback

tomyjuniorhigh

schoolday

swhen

Idiscoveredaclassic

book

byW

.W

.Rouse

Ball,Mathem

atical

RecreationsandEssays.Balllived

from

1850until1925.Hewas

afellow

ofTrinity

College,

Cambridge.

Thefirstedition

ofhis

book

on

mathem

aticalrecreations

was

published

in1892andthetenth

editionin

1937.Latereditionswererevised

andupdatedbyanother

famousmathem

atician,H.S.M

Cox

eter.Thethirteenth

edition,published

byDover

in1987,is

available

from

manybooksellers,

including

Pow

ells

andAmazon.

http://www.powells.com/cgi-bin/biblio?inkey=17-0486253570-0

http://www.amazon.com/Mathematical-Recreations-Essays-Dover-Books/

dp/0486253570

TherearedozensofinterestingWeb

pages

abou

tmagic

squares.

Hereare

afew

authors

andlinksto

theirpages.

MutsumiSuzu

ki

http://mathforum.org/te/exchange/hosted/suzuki/MagicSquare.html

EricWeisstein

http://mathworld.wolfram.com/MagicSquare.html

KwonYou

ngShin

http://user.chollian.net/~brainstm/MagicSquare.htm

WalterTrump

http://www.trump.de/magic-squares

Rec

ap

%%Magic

Squares

Chapter

Recap

%This

is

an

executable

program

that

illustrates

the

statements

%introduced

in

the

Magic

Squares

Chapter

of

"Experiments

in

MATLAB".

%You

can

access

it

with

% %magic_recap

%edit

magic_recap

%publish

magic_recap

% %Related

EXM

programs

% %magic

%ismagical

%%A

Few

Elementary

Array

Operations.

formatshort

A=

magic(3)

sum(A)

134

Chapter10

.Magic

Squares

sum(A’)’

sum(diag(A))

sum(diag(flipud(A)))

sum(1:9)/3

fork

=0:3

rot90(A,k)

rot90(A’,k)

end

%%

Durer’s

Melancolia

clearall

closeall

figure

loaddurer

whos

image(X)

colormap(map)

axisimage

%%

Durer’s

Magic

Square

figure

loaddetail

image(X)

colormap(map)

axisimage

A=

magic(4)

A=

A(:,[1

32

4])

%%

Magic

Sum

n=

(3:10)’;

(n.^3+

n)/2

%%

Odd

Order

n=

5

[I,J]=

ndgrid(1:n);

A=

mod(I+J+(n-3)/2,n);

B=

mod(I+2*J-2,n);

M=

n*A

+B

+1

%%

Doubly

Even

Order

n=

4

M=

reshape(1:n^2,n,n)’;

[I,J]=

ndgrid(1:n);

K=

fix(mod(I,4)/2)

==

fix(mod(J,4)/2);

M(K)=

n^2+1

-M(K)

Page 73: Experiments With MatLab Moled 2011

135

%%Rank

figure

forn

=3:20

r(n)=

rank(magic(n));

end

bar(r)

axis([221

020])

%%Ismagical

helpismagical

forn

=3:10

ismagical(magic(n))

end

%%Surf

Plots

figure

forn

=9:12

subplot(2,2,n-8)

surf(rot90(magic(n)))

axistightoff

text(0,0,20,num2str(n))

end

set(gcf,’color’,’white’)

Exe

rcises

10.1

ismagic.

Write

aMatlab

functionismagic(A)thatchecksifAis

amagic

square.

10.2

Magicsum.Show

that

1 n

n2 ∑ k=1

k=

n3+

n

2.

10.3

durerperm.Investigate

thedurerpermprogram.Click

ontw

odifferentelem

ents

tointerchangerowsan

dcolumns.

Dotheinterchanges

preserverow

andcolumn

sums?

Dotheinterchanges

preservethediagonalsums?

10.4

Colorm

aps.

Try

this.

clear

loaddetail

whos

136

Chapter10

.Magic

Squares

You

willseethreematrices

inyou

rworkspace.

You

can

lookatall

ofmapand

caption.

map

caption

Thematrix

Xis

359-by-371.That’s133189elem

ents.Look

atjust

apiece

ofit.

X(101:130,101:118)

Theelem

ents

ofXare

integersin

therange

min(min(X))

max(max(X))

Thecommands

image(X)

axisimage

produce

aprettycolorfuldisplay.

That’sbecause

theelem

ents

ofXare

beingused

asindices

into

thedefault

colorm

ap,jet(64).Youcanuse

theintended

colorm

ap

instead.

colormap(map)

Thearray

mapis

a64-by-3

array.Each

row,map(k,:),specifies

intensities

ofred,

green

andblue.

Thecolorusedatpoint(i,j)ismap(X(i,j),:).In

thiscase,the

colorm

apthatcomes

withdetailhasallthreecolumnsequalto

each

other

andso

isthesameas

colormap(gray(64))

Now

experim

entwithother

colorm

aps

colormap(hot)

colormap(cool)

colormap(copper)

colormap(pink)

colormap(bone)

colormap(flag)

colormap(hsv)

You

caneven

cyclethrough101colorm

aps.

forp

=0:.001:1

colormap(p*hot+(1-p)*pink)

drawnow

end

You

canplotthethreecolorcompon

ents

ofacolorm

aplikehotwith

Page 74: Experiments With MatLab Moled 2011

137

rgbplot(hot)

This

iswhatTV

mov

iechannelsdowhen

they

colorize

old

black

andwhitefilm

s.

10.5

Knight’stour.

Doyou

know

how

aknightisallow

edto

moveon

achessboard?

Theexmfunctionknightstourgen

eratesthis

matrix,K.

K=

50

11

24

63

14

37

26

35

23

62

51

12

25

34

15

38

10

49

64

21

40

13

36

27

61

22

952

33

28

39

16

48

760

120

41

54

29

59

445

853

32

17

42

647

257

44

19

30

55

358

546

31

56

43

18

Ifyou

follow

theelem

ents

innumericalorder,youwillbetaken

onakn

ight’stour

ofK.Even

thestep

from

64back

to1is

aknight’smove.

IsKamagic

square?W

hyorwhynot?

Try

this.

image(K)

colormap(pink)

axissquare

Selectthedata

cursoricononthefigure

tourbar.

Now

use

themouse

totakethe

knight’stourfrom

dark

tolightontheim

age.

10.6

ismagical.Theexmfunctionismagicalchecksforfourdifferentmagicalprop-

erties

ofsquare

array

s.Sem

imagic:allofthecolumnsandallofrowshavethesamesum.

Magic:allofthecolumns,

allofrowsandboth

principaldiagonals

havethesame

sum.

Panmagic:allofthecolumns,

allofrowsandallofthediagonals,includingthe

broken

diagonals

inboth

directions,

havethesamesum.

Associative:allpairsof

elem

ents

onopposite

sides

ofthecenterhavethesamesum.

For

example,this

matrix

thathasallfourproperties.

M=

10

18

114

22

11

24

720

3

17

513

21

9

23

619

215

412

25

816

Hereis

oneof

thebroken

diagonals.Itssum

isμ(5)=

65.

138

Chapter10

.Magic

Squares

..

.14

.

..

..

3

17

..

..

.6

..

.

..

25

..

Allof

thebroken

diagonalsin

both

directionshavethesamesum,so

Mispanmagic.

Onepairof

elem

ents

onop

posite

sides

ofthecenteris24

and2.Theirsum

istw

ice

thecentervalue.

Allpairsof

elem

ents

onop

posite

sides

ofthecenterhavethissum,

soMis

associative.

(a)Use

ismagicalto

verifythatMhasallfourproperties.

(b)Use

ismagicalto

investigate

themagicalproperties

ofthematrices

generated

bytheMatlabmagicfunction.

(c)Use

ismagicalto

investigate

themagicalproperties

ofthematrices

generated

bythis

algorithm

forvariousoddnandvariousvalues

ofa0andb0,

a0

=...

b0

=...

[I,J]=

ndgrid(1:n);

A=

mod(I+J-a0,n);

B=

mod(I+2*J-b0,n);

M=

n*A

+B

+1;

(d)Use

ismagicalto

investigate

themagicalproperties

ofthematrices

generated

bythis

algorithm

forvariousoddnandvariousvalues

ofa0andb0,

a0

=...

b0

=...

[I,J]=

ndgrid(1:n);

A=

mod(I+2*J-a0,n);

B=

mod(I+3*J-b0,n);

M=

n*A

+B

+1;

10.7

Inverse.

Ifyou

havestudiedmatrix

theory,youhaveheard

ofmatrix

inverses.

Whatis

thematrix

inverseofamagic

square

oforder

n?

Itturnsoutto

dep

end

uponwhether

nisoddoreven

.Foroddn,thematrices

magic(n)are

nonsingular.

Thematrices

X=

inv(magic(n))

donothavepositive,

integer

entries,butthey

dohaveequalrow

andcolumnsums.

But,

foreven

n,thedeterminant,det(magic(n)),is

0,andtheinverse

does

notexist.

IfA=

magic(4)tryingto

compute

inv(A)producesanerrormessage.

10.8

Rank.

Ifyou

havestudiedmatrix

theory,youknow

thattherankof

amatrix

isthenumber

oflinearlyindep

endentrowsandcolumns.

Ann-by-n

matrix

issingular

ifitsrank,r,

isnotequalto

itsorder.This

codecomputestherankof

themagic

squaresupto

order

20,generatedwith

Page 75: Experiments With MatLab Moled 2011

139

forn

=3:20

r(n)=

rank(magic(n));

end

Theresultsare

n=

34

56

78

910

11

12

13

14

15

16

17

18

19

20

r=

33

55

73

97

11

313

915

317

11

19

3

Doyouseethepattern?May

bethebargraphin

figure

10.5

willhelp.Youcansee

24

68

1012

1416

1820

02468101214161820 Figure

10.5.Rankofmagicsquares.

thatthethreedifferentalgorithmsusedto

generate

magicsquaresproduce

matrices

withdifferentrank.

nrank

odd

n

even,notdivisibleby

4n/2+2

divisibleby

43

140

Chapter10

.Magic

Squares

Page 76: Experiments With MatLab Moled 2011

Chapter11

TicTacT

oeMagic

Threesimple

games

are

relatedin

asurprisingway.

And,theprogrammingofthe

gameplayis

instructive.

Thefirstofthethreegames

isPick15.Harold

Stark,whowas

then

atthe

University

ofMichigan,told

meab

outthegamein

thelate

1960s.

Isuspectthat

this

isthefirsttimeyouhaveheard

ofit.

Thegameinvo

lves

twoplayers.Youstart

bylistingthesingle

digit

numbers

from

1to

9.Youthen

taketurnsselectingnumbersfrom

thelist,attem

ptingto

acquirethreenumbersthataddupto

15.Each

number

canbechosenonly

once.

Youmay

eventuallyacquiremore

thanthreenumbers,

butyoumust

use

exactly

threeof

them

tototal15.If

neither

playercanachieve

thedesired

total,thegame

isadraw.

Forexample,suppose

thatGreen

andBlueare

playing.They

start

withthe

list.

List

:1

23

45

67

89

Green

:

Blue

:

Suppose

Green

hasthefirstmoveandchooses8.Then

Bluechooses

4an

dGreen

chooses2.Now

Blueshould

respondbychoosing5to

preventGreen

from

getting

2+5+8=

15.Hereis

thesituationafter

thefirsttw

orounds.

List

:1

2/3

4/5/

67

8/9

Green

:2

8

Blue

:4

5

Copyright

c ©2011CleveMoler

Matlab

R ©is

aregisteredtradem

ark

ofMath

Works,

Inc.

TM

October

4,2011

141

142

Chapter11

.TicTacToeMagic

Now

Green

chooses

6to

block

4+

5+

6=

15from

Blue.

This

isactually

an

advantageousmoveforGreen

because

itgives

her

twodifferentway

sto

win,1+6+8

and2+

6+7.

Bluecannotblock

both.If

Bluechooses7,then

Green

chooses

1to

win.If

Bluechooses

1,then

Green

chooses

7to

win.Thefinalpositionmightbe

List

:1/

2/3

4/5/

6/7/

8/9

Green

:2

67

8

Blue

:1

45

Note

thatGreen

alsohas7+8=

15,butthisdoes

notcountbecause

thereare

only

twonumbersin

thesum.

Figure

11.1

show

sthestartingpositionforthePick15op

tionin

ourMatlab

tictactoeprogram.W

hen

youplayagainst

thecomputer,

yourmoves

are

show

nin

green

andtheresponsesfrom

theprogram

are

show

nin

blue.

Figure

11.1.StartingpositionforPick15.

Figure

11.2

show

sthepositionforourexample

gameaftertw

omoves

from

each

player.

Green

now

hasto

choose6to

block

Blue.

Figure

11.2.Positionafter

twomovesfrom

each

player.

Figure

11.3

show

sthefinalpositionforourexample

game.

Green

haswon

with2+6+7=

15.

Figure

11.3.FinalpositionforPick15.

Please

taketimeoutfrom

readingthis

chapterto

trythis

gameafew

times

you

rself,playingagainst

afriendonpaper

oragainst

ourMatlabprogram.Ithink

you

willfindthatPick15is

more

challengingthanit

soundsatfirst.

Thesecondofourthreegames

isfamiliarworldwide.

Itiscalled

“TicTacT

oe”

intheUnited

States,“Noughts

andCrosses”in

GreatBritain,andhasmanyother

names

inmanyother

countriesan

dlanguages.Ourprogram

tictactoeusesgreen

andblueinsteadofX’s

andO’s.Theobjective,

ofcourse,

isto

get

yourcoloron

allthreesquaresin

arow,column,or

diagonal.Figure

11.6

show

stypicalou

tput.

Page 77: Experiments With MatLab Moled 2011

143

Figure

11.4.Typicaloutputfrom

agameofTicTacT

oe.Green

haswon

withthethirdcolumn.

Ourprogram

tictactoeusesanaivethree-step

strategy.

•Ifpossible,makeawinningmove.

•Ifnecessary,block

apossible

winningmovebytheopponent.

•Otherwise,

pickarandom

empty

square.

This

strategywillleadto

awin

only

when

theop

ponentmakes

aerror.

And,even

thoughit

ispossible

fortheplayerwiththesecondmoveto

alwaysforceadraw,

this

strategywillnotaccomplish

that.

Ourthirdgame,

Magic15,introducestheLo-Shu3-by-3

magic

square.Now

weseethatPick15is

actuallyTicTacT

oeplayed

onamagic

square.

Therows,

columnsandmain

diagonalsofthemagic

square

provideallpossible

waysofhav

ing

threedistinct

numbersthatsum

to15.W

inningmoves

inPick15correspondto

winningmoves

inTicTacToe.

Allthreegames

are

actuallythesamegamewith

differentdisplays.

Figure

11.5.InitialconfigurationforagameofMagic3.

144

Chapter11

.TicTacToeMagic

Figure

11.6.Green

haswonwith6+7+2=

15in

thethirdcolumn.

GamePlay

Thetictactoeprogram

operatesthreedifferentviewsofthesamegame.

You

are

thegreenplayerandthecomputeris

theblueplayer.

Thestate

ofthegameis

carriedin

a3-by-3

matrix

Xwhose

entriesare

+1forcellsoccupiedbygreen,-1

forcellsoccupiedbyblue,

and0foras

yet

unoccupiedcells.

Obviously,

thegame

beginswithX=

zeros(3,3)

Hereis

theportionofmain

program

thatis

executedwhen

you,as

thegreen

player,

clickon

oneofthebuttonsorcells.

Itretrieves

iandj,thematrix

indices

correspondingto

theactivebuttonandthen

checksifthecurrentgamealreadyhas

awinner.If

not,

itmakes

yourmovebysettingX(i,j)=

1andrecu

rsivelycalls

tictactoeto

letbluetakeaturn.

switch

case’green’

[i,j]=

find(gcbo

==

B);

ifwinner(X)

return

end

X(i,j)=

1;

tictactoe(’blue’)

Hereis

thecorrespondingblueportionof

themain

program.If

thecurrent

gamedoes

notalreadyhaveawinner,it

callsthestrategyfunctionto

get

the

indices

foramoveandmakes

thatmove.

case’blue’

ifwinner(X)

return

end

[i,j]=

strategy(X,-1);

X(i,j)=

-1;

...

end

Page 78: Experiments With MatLab Moled 2011

145

Briefl

y,then

,thegreen

moves

are

determined

byuserbuttonclicksandthe

bluemoves

are

determined

bythestrategyfunction.

Hereis

thefunctionthatchecksto

seeifthereis

awinner.It

looksforany

column,row,ordiagonalwhose

elem

ents

sum

to3*pwherep=1forgreen

and

p=-1forblue.

Theon

lyway

asum

canbe3*pis

ifallthreeelem

ents

are

equal

top. functionp

=winner(X)

%p

=winner(X)

returns

%p

=0,

no

winner

yet,

%p

=-1,

blue

has

won,

%p

=1,

green

has

won,

%p

=2,

game

is

adraw.

forp

=[-1

1]

s=

3*p;

win=

any(sum(X)

==

s)

||

any(sum(X’)

==

s)

||

...

sum(diag(X))==

s||

sum(diag(fliplr(X)))

==

s;

if

win

return

end

end

p=

2*all(X(:)

~=

0);

Hereis

thenaive,

butfairly

effectivestrategythatthecomputerusesagainst

you

.It

firstchecksto

seeifit

canmakeawinningmove.

Ifnot,

itthen

checksto

seeifit

needsto

block

you

rpendingwinningmove.

Itneither

ofthesehappen

s,it

simply

choosesarandom

empty

cell.Thiscrudestrategymakes

theplayinteresting.

Itis

possible

foryouto

beatthecomputerifitsrandom

choices

are

notoptimal.

Theexercisessuggestsomeim

provements

inthis

strategy.

function[i,j]=

strategy(X,p);

%[i,j]

=strategy(X,p)

is

abetter,

but

not

perfect,

move

for

player

p.

%Appear

to

think.

pause(0.5)

%If

possible,

make

awinning

move.

[i,j]=

winningmove(X,p);

%Block

any

winning

move

by

opponent.

if

isempty(i)

[i,j]=

winningmove(X,-p);

end

%Otherwise,

make

arandom

move.

if

isempty(i)

146

Chapter11

.TicTacToeMagic

[i,j]=

find(X

==

0);

m=

ceil(rand*length(i));

i=

i(m);

j=

j(m);

end Finally,

hereis

thefunctionthatseeksawinningmovebyeither

player.

Itlooksforrows,

columns,

ordiagonals

withsumsequalto

2*pforeither

valueofp.

function[i,j]=

winningmove(X,p);

%[i,j]

=winningmove(X,p)

finds

any

winning

move

for

player

p.

s=

2*p;

if

any(sum(X)

==

s)

j=

find(sum(X)

==

s);

i=

find(X(:,j)

==

0);

elseifany(sum(X’)==

s)

i=

find(sum(X’)

==

s);

j=

find(X(i,:)

==

0);

elseifsum(diag(X))==

s

i=

find(diag(X)

==

0);

j=

i;

elseifsum(diag(fliplr(X)))==

s

i=

find(diag(fliplr(X))

==

0);

j=

4-

i;

else i=

[];

j=

[];

end Theremainder

ofthetictactoefunctionis

responsible

forthegu

i.Let’sseehow

allthisworksonanexample.Webegin

withthepositionshow

nin

figure

11.2,after

twomoves

byeach

player.

Thestate

ofthegameat

this

point

is

X=

10

0

0-1

0

-1

01

Itis

green’s

move.

Green

needsto

clickthe6buttonto

preventbluefrom

hav

ing

4+5+6=

15.Or,

itis

probably

easier

tolookatM

=magic(3)

M=

81

6

35

7

49

2

Page 79: Experiments With MatLab Moled 2011

147

You

seethat4and5are

ontheantidiagonal,so

greenneedsthe6to

preventawin

intheTicTacToeversionofthisgame.

Either

way,thiscorrespondsto

(i,j)=

(1,3)

andsettingX(i,j)=

1.

X=

10

1

0-1

0

-1

01

Now

itisblue’sturn.Both

thefirstrow

andthethirdcolumnofXhavesums

equalto

2,correspondingto

thefact

thatgreenhastw

opendingwinningmoves.

Withp=-1,thestrategyfunctionlooksforablock

bycallingwinningmove(X,-p).

Theresultis(i,j)=

(2,3),althoughitjust

aswellcould

havebeen(i,j)=

(1,2)

ifwinningmovemadeitschecksin

another

order.This

leadsto

X=

10

1

0-1

-1

-1

01

Onthenextturn,green

findsthatthesum

alongthefirstrow

is2,an

dso

sets

X(1,2)=

1to

makethesum

3.This

gives

X=

11

1

0-1

-1

-1

01

andgreenproclaim

sawin.

Itwould

bepossible

toim

plementrecursivebacktrackingstrategieslikewe

describein

theSudokuchapter.

Butthereare

only

afew

hundredpossible

games,

sothebacktrackingwould

beexhaustive.

Andboring–allthegames

would

be

draws.

Rec

ap

%%TicTacToe

Chapter

Recap

%This

is

an

executable

program

that

illustrates

the

statements

%introduced

in

the

TicTacToe

Chapter

of

"Experiments

in

MATLAB".

%You

can

access

it

with

% %tictactoe_recap

%edit

tictactoe_recap

%publish

tictactoe_recap

% %Related

EXM

programs

% %tictactoe

148

Chapter11

.TicTacToeMagic

%%

tictactoe/winner

%function

p=

winner(X)

%%

p=

winner(X)

returns

%%

p=

0,

no

winner

yet,

%%

p=

-1,

blue

has

won,

%%

p=

1,

green

has

won,

%%

p=

2,

game

is

adraw.

% %for

p=

[-1

1]

%s

=3*p;

%win

=any(sum(X)

==

s)

||

any(sum(X’)

==

s)

||

...

%sum(diag(X))==

s||

sum(diag(fliplr(X)))

==

s;

%if

win

%return

%end

%end

%p

=2*all(X(:)

~=

0);

%%

tictactoe/strategy

%function

[i,j]

=strategy(X,p);

%%

[i,j]

=strategy(X,p)

is

amove

for

player

p.

% %%

Appear

to

think.

%pause(0.5)

% %%

If

possible,

make

awinning

move.

%[i,j]

=winningmove(X,p);

% %%

Block

any

winning

move

by

opponent.

%if

isempty(i)

%[i,j]

=winningmove(X,-p);

%end

% %%

Otherwise,

make

arandom

move.

%if

isempty(i)

%[i,j]

=find(X

==

0);

%m

=ceil(rand*length(i));

%i

=i(m);

%j

=j(m);

%end

%%

tictactoe/winningmove

Page 80: Experiments With MatLab Moled 2011

149

%function

[i,j]

=winningmove(X,p);

%%

[i,j]

=winningmove(X,p)

finds

any

winning

move

for

player

p.

% %s

=2*p;

%if

any(sum(X)

==

s)

%j

=find(sum(X)

==

s);

%i

=find(X(:,j)

==

0);

%elseif

any(sum(X’)

==

s)

%i

=find(sum(X’)

==

s);

%j

=find(X(i,:)

==

0);

%elseif

sum(diag(X))

==

s

%i

=find(diag(X)

==

0);

%j

=i;

%elseif

sum(diag(fliplr(X)))

==

s

%i

=find(diag(fliplr(X))

==

0);

%j

=4

-i;

%else

%i

=[];

%j

=[];

%end

Exe

rcises

11.1

Traditional.

Modifytictactoe.mso

thatitusestraditionalX’s

andO’s.

11.2

Win.Is

itpossible

towin

against

tictactoewithitsnaivestrategy?

11.3

First

move.Modifytictactoeso

thatthecomputertakes

thefirstmove.

11.4

Cen

tersquare.Modifythestrategyusedbytictactoe.mso

that,before

taking

arandom

move,

ittakes

thecentersquare

ifit

isavailable.Does

this

improve

the

program’s

chancesofwinningorforcingadraw?

11.5

xkcd.Im

plementthecomplete

tictactocstrategyavailable

from

theWeb

comic

stripxkcdbyRandalMunroeat

http://xkcd.com/832

11.6

Computerversuscomputer.

Modifytictactoe.mso

thatthecomputerplays

against

itself.Countthenumber

ofdrawsan

dwinsforboth

sides.Runalarge

number

ofgames,withandwithoutthead

ditionofthecentersquare

strategy.

150

Chapter11

.TicTacToeMagic

Page 81: Experiments With MatLab Moled 2011

Chapter12

GameofLife

Conway’sGameofLifemakesuse

ofsparsematrices.

The“GameofLife”

wasinvented

byJohn

Horton

Conway,aBritish-born

mathem

aticianwhoisnow

aprofessorat

Princeton.Thegamemadeitspublicdebut

intheOctober

1970issueofScien

tificAmerican,in

the“Mathem

aticalGames”

columnwritten

byMartin

Gardner.Atthetime,

Gardner

wrote

Thismonth

weconsider

Conway’slatest

brainchild,afantastic

solitaire

pastim

ehecalls“life”.Because

ofitsanalogieswiththerise,falland

alternationsofasocietyoflivingorganisms,itbelongsto

agrowingclass

ofwhatare

called

“simulationgames”–games

thatresemble

real-life

processes.Toplaylife

youmust

haveafairly

largecheckerboard

anda

plentifulsupply

offlatcounters

oftw

ocolors.

Ofcourse,

today

wecanrunthesimulationson

ourcomputers.

Theuniverse

isaninfinite,

two-dim

ensionalrectangulargrid.Thepopulation

isacollection

ofgrid

cellsthatare

marked

asalive.

Thepop

ulationevolvesat

discretetimestep

sknow

nasgenerations.

Ateach

step,thefate

ofeach

cell

isdetermined

bythevitality

ofitseightnearest

neighbors

andthis

rule:

•A

livecellwithtw

oliveneighbors,

oranycellwiththreeliveneighbors,

isalive

atthenextstep

.

ThefascinationofConway’sGameofLifeisthatthisdeceptivelysimple

rule

leads

toanincredible

varietyofpatterns,

puzzles,

andunsolved

mathem

aticalproblems

–just

likereallife.

Iftheinitialpopulationconsistsofon

lyoneortw

olivecells,itexpires

inone

step.Iftheinitialpopulationconsistsofthreelivecellsthen,because

ofrotational

Copyright

c ©2011CleveMoler

Matlab

R ©is

aregisteredtradem

ark

ofMath

Works,

Inc.

TM

October

4,2011

151

152

Chapter12

.Gam

eof

Life

Figure

12.1.A

pre-block

andablock.

andreflexivesymmetries,thereare

only

twodifferentpossibilities–thepopulation

iseither

L-shaped

orI-shaped.Theleft

halfoffigure

12.1

show

sthreelivecellsin

anL-shape.

Allthreecellshavetw

oliveneighbors,

sothey

survive.

Thedeadcell

thatthey

alltouch

hasthreeliveneighbors,

soit

springsto

life.Noneof

theother

deadcellshaveenoughliveneighborsto

cometo

life.Sotheresult,afteronestep,

isthepopulationshow

nin

therighthalfoffigure

12.1.This

four-cellpopulation,

know

nastheblock,

isstationary.Each

ofthelivecellshasthreeliveneighborsand

solives

on.Noneof

theother

cellscancometo

life.

Figure

12.2.A

blinkerblinking.

Theother

three-cellinitialpop

ulationis

I-shaped.Thetw

opossible

orienta-

tionsareshow

nin

firsttw

ostepsof

figure

12.2.Ateach

step,tw

oendcellsdie,the

middle

cellstay

salive,

andtw

onew

cellsare

born

togivetheorientationshow

nin

thenextstep

.If

nothingdisturbsit,this

blinkerkeepsblinkingforever.It

repeats

itselfin

twostep

s;this

isknow

nasitsperiod.

Onepossible

four-cellinitialpopulationis

theblock.Discoveringthefate

of

theother

four-cellinitialpop

ulationsis

left

toanexercise.

Thebeginningoftheevolutionofthemost

importantfive-cellinitialpop

ula-

tion,know

nastheglider,isshow

nin

figure

12.3.Ateach

step

twocellsdie

andtw

onew

ones

areborn.After

fourstepstheoriginalpop

ulationreappears,butit

has

moved

diagonallydow

nandacross

thegrid.It

continues

tomovein

this

direction

forever,eventuallydisappearingoutof

ourfieldofview,butcontinuingto

existin

theinfiniteuniverse.

ThefascinationoftheGameof

Lifecannotbecapturedin

thesestaticfig-

ures.

Computergraphicslets

you

watchthedynamic

development.

Wewillshow

just

more

onestaticsnapshotoftheevolutionofanim

portantlarger

population.

Figure

12.4

istheglider

gundeveloped

byBillGosper

atMIT

in1970.Theportion

ofthepopulationbetweenthetw

ostaticblocksoscillatesback

andforth.Every30

steps,aglider

emerges.Theresultisaninfinitestream

ofglidersthatflyou

tofthe

fieldofview.

Page 82: Experiments With MatLab Moled 2011

153

Figure

12.3.A

glider

gliding.

Figure

12.4.Gosper’s

glider

gun.

Matlabisaconvenientenvironmentforim

plementingtheGameofLife.

The

universe

isamatrix.Thepopulationis

thesetofnonzero

elem

ents

inthematrix.

Theuniverse

isinfinite,

butthepopulationis

finiteandusuallyfairly

small.So

wecanstore

thepopulationin

afinitematrix,most

ofwhose

elem

ents

arezero,

andincrease

thesize

ofthematrix

ifnecessary

when

thepopulationexpands.

This

istheidealsetupforasparsematrix.Conventionalstorageofann-by-n

matrix

requires

n2mem

ory.Butsparsestorageofamatrix

Xrequires

just

threevectors,

oneinteger

andonefloatingpointvectoroflength

nnz(X)–thenumber

ofnonzero

154

Chapter12

.Gam

eof

Life

elem

ents

inX–an

doneinteger

vectoroflength

n,not

n2,to

representthestart

ofeach

column.Forexample,thesnapshotof

theGosper

glider

gunin

figure

12.4

isrepresentedbyan

85-by-85matrix

with68

nonzero

entries.

Conventionalfull

matrix

storagewou

ldrequire852

=7225elem

ents.Sparsematrix

storagerequires

only

2·65+85

=221elem

ents.Thisad

vantageofsparseover

fullstorageincreases

asmore

glidersarecreated,thepopulationexpands,

andnincreases.

Theexm

toolbox

includes

aprogram

called

lifex.

(Matlab

itself

hasa

simplerdem

oprogram

called

life.)

Theinitialpop

ulation

isrepresented

bya

matrix

of0’s

and1’s.For

example,

G=

[1

11;

10

0;

01

0]

producesasingle

glider

G=

11

1

10

0

01

0

Theuniverse

isrepresentedbyasparsen-by-n

matrix

Xthatis

initiallyallzero.

Wemightstart

withn=

23so

therewillbea10

cellwideborder

arou

nda3-by-3

center.

Thestatements

n=

23;

X=

sparse(n,n)

produce

X=

Allzerosparse:23-by-23

Theinitialpopulationis

injected

inthecenteroftheuniverse.withthestatement

X(11:13,11:13)=

G

This

producesalist

ofthenonzero

elem

ents

X= (11,11)

1

(12,11)

1

(11,12)

1

(13,12)

1

(11,13)

1

Weare

now

readyto

takethefirststep

inthesimulation.W

hether

cellsstay

alive,

die,orgenerate

new

cellsdep

endsuponhow

manyof

theireightneighborsare

alive.

Thestatements

n=

size(X,1);

p=

[1

1:n-1];

q=

[2:n

n];

Page 83: Experiments With MatLab Moled 2011

155

generate

index

vectors

thatincrease

ordecrease

thecenteredindex

byon

e,thereby

accessingneighbors

totheleft,right,up,dow

n,an

dso

on.Thestatement

Y=

X(:,p)

+X(:,q)

+X(p,:)

+X(q,:)

+...

X(p,p)+

X(q,q)

+X(p,q)

+X(q,p)

producesasparsematrix

withinteger

elem

ents

between0an

d8thatcounts

how

manyoftheeightneighbors

ofeach

interiorcellare

alive.

Inourexample

withthe

firststep

oftheglider,thecellswithnonzero

counts

are

Y=

(9,9)

1(10,9)

2

(11,9)

2(12,9)

1

(9,10)

2(10,10)

2

(11,10)

3(12,10)

2

(13,10)

1(9,11)

3

(10,11)

3(11,11)

5

(12,11)

1(13,11)

1

(9,12)

2(10,12)

1

(11,12)

3(12,12)

1

(13,12)

1(9,13)

1

(10,13)

1(11,13)

1

Thebasicrule

ofLifeis

Alivecellwithtw

oliveneighbors,or

anycellwiththreeliveneighbors,

isaliveatthenextstep

.

This

isim

plementedwiththesingle

Matlabstatement

X=

(X

&(Y

==

2))

|(Y

==

3)

Thetw

ocharacters’==’mean“isequalto”.The’&’character

means“and”.The

’|’means“or”.Theseoperationsare

doneforallthecellsin

theinteriorofthe

universe.In

thisexample,therearefourcellswhereYisequalto

3,so

they

survive

orcomealive.

Thereis

onecellwhereXis

equalto

1andYis

equal

to2,

soit

survives.Theresult

is

X= (11,11)

1

(12,11)

1

(10,12)

1

(11,12)

1

(12,13)

1

Ourglider

hastaken

itsfirststep.

Oneway

touse

lifexis

toprovideyourow

ninitialpopulation,aseither

afullor

asparsematrix.Forexample,youcreate

yourow

nfleetofglidersfleetwith

G=

[1

11;

10

0;

01

0]

156

Chapter12

.Gam

eof

Life

S=

sparse(15,15);

fori

=0:6:12

forj

=0:6:12

S(i+(1:3),j+(1:3))=

G;

end

end

lifex(S)

TheWeb

page

http://www.argentum.freeserve.co.uk/lex_home.htm

isthehomeof

the“LifeLexicon”,maintained

byStephen

Silver.Amongthousands

ofthefactsofLife,

this

160-pagedocumentlistsnearly450differentinitialpopu-

lations,

together

withtheirhistory

andim

portantproperties.Wehaveincluded

atextcopyoftheLexiconwiththeexmtoolbox

inthefile

exm/lexicon.txt

Lifexcanreadinitialpop

ulationsfrom

theLexicon.Callinglifexwithno

arguments,

lifex

picksarandom

initialpop

ulationfrom

theLexicon.Either

lifex(’xyz’)

or

lifexxyz

willlookforapop

ulationwhose

namebeginswithxyz.Forexample,thestatements

lifexpre-block

lifexblock

lifexblinker

lifexglider

start

with

thesimple

populationsthatwehaveused

inthis

introduction.

The

statement

lifexGosper

provides

Gosper’s

glider

gun.

Bydefault,theinitialpop

ulationis

surrounded

byastripof

20deadborder

cellsto

provideaviewingwindow

.Youcanchangethis

touse

bborder

cellswith

lifex(’xyz’,b)

Ifthepopulationexpandsduringthesimulationandcellstravelbeyondthisviewing

window

,they

continueto

livean

dparticipate

even

thoughthey

cannotbeseen.

Page 84: Experiments With MatLab Moled 2011

157

Further

Rea

ding

TheW

ikiped

iaarticle

isagoodintroduction.

http://en.wikipedia.org/wiki/Conway’s_Game_of_Life

Another

goodintroductionisavailablefrom

Math.com,althoughthereare

annoy

ing

pop

upsandad

s.

http://www.math.com/students/wonders/life/life.html

Ifyou

findyourselfatallinterested

intheGameofLife,

takeagoodlookatthe

Lexicon,either

byreadingourtextversionorbyvisitingtheWeb

page.

http://www.argentum.freeserve.co.uk/lex_home.htm

Rec

ap

%%Life

Chapter

Recap

%This

is

an

executable

program

that

illustrates

the

statements

%introduced

in

the

Life

Chapter

of

"Experiments

in

MATLAB".

%You

can

access

it

with

% %life_recap

%It

does

not

work

so

well

with

edit

and

publish.

% %Related

EXM

programs

% %lifex

%Generate

arandom

initial

population

X=

sparse(50,50);

X(21:30,21:30)=

(rand(10,10)

>.75);

p0

=nnz(X);

%Loop

over

100

generations.

fort

=1:100

spy(X)

title(num2str(t))

drawnow

%Whether

cells

stay

alive,

die,

or

generate

new

cells

depends

%upon

how

many

of

their

eight

possible

neighbors

are

alive.

%Index

vectors

increase

or

decrease

the

centered

index

by

one.

n=

size(X,1);

p=

[1

1:n-1];

158

Chapter12

.Gam

eof

Life

q=

[2:n

n];

%Count

how

many

of

the

eight

neighbors

are

alive.

Y=

X(:,p)

+X(:,q)

+X(p,:)

+X(q,:)

+...

X(p,p)+

X(q,q)

+X(p,q)

+X(q,p);

%A

live

cell

with

two

live

neighbors,

or

any

cell

with

%three

live

neigbhors,

is

alive

at

the

next

step.

X=

(X

&(Y

==

2))

|(Y

==

3);

end

p100=

nnz(X);

fprintf(’%5d%5d%8.3f\n’,p0,p100,p100/p0)

Exe

rcises

12.1

life

vs.

lifex

TheMatlab

dem

ostoolbox

hasan

oldprogram

called

life,

withoutan

x.In

whatwaysisitthesameas,an

din

whatwaysdoes

itdiffer

from,

ourexmguilifex?

12.2

Four-cellinitialpopulations.

Whatare

allofthepossible

four-cellinitialpop

u-

lations,andwhataretheirfates?

You

cangenerate

oneof

thefour-cellpopulations

with

L=

[1

11;

10

0];

lifex(L,4)

12.3

Lexicon.Describethebehav

iorof

each

ofthesepop

ulationsfrom

theLexicon.

Ifanyis

periodic,whatis

itsperiod?

ants

B-52

blinkerpuffer

diehard

Canadagoose

glidersby

the

dozen

Kok’sgalaxy

rabbits

R2D2

spacefiller

wasp

washerwoman

Page 85: Experiments With MatLab Moled 2011

159

12.4

Glider

collisions.

Whathappenswhen:

Aglider

collides

head-onwithablock?

Aglider

side-sw

ipes

ablock?

Twogliderscollidehead-on?

Twoglidersclip

each

otherswings?

Fourgliderssimultaneouslyleavethecornersofasquare

andheadto-

wardsitscenter?

See

also:lifex(’4-8-12’).

12.5

Factory.How

manystepsdoes

ittakethefactoryto

makeoneglider?

12.6

R-pen

tomino.Ofallthepossible

five-cellinitialpopulations,theonly

onethat

requires

acomputerto

determineitsultim

ate

behav

ioris

theonethatConway

dubbed

theR-pen

tomino.It

isshow

nin

figure

12.5

andcanbegeneratedby

R=

[0

11;

11

0;

01

0]

Figure

12.5.TheR-pen

tomino.

Asthesimulationproceeds,

thepopulationthrowsoff

afew

gliders,

butotherwise

remainsbounded.Ifyou

makeblargeenough,thestatement

lifex(R,b)

show

sallofthebounded

behav

ior.

How

largedoes

this

bhaveto

be?

Whatis

themaxim

um

pop

ulationduringtheevolution?

How

manyglidersare

produced?

How

manystepsdoes

ittakeforthepop

ulationto

stabilize?

How

manyblinkers

are

presentin

thestabilized

pop

ulation?W

hatissize

ofthestabilized

pop

ulation?

12.7

Executiontime.

Displayactualcomputerexecutiontimebyinsertingticand

tocin

lifex.m.Place

thesingle

statement

tic

before

thestart

oftheinner

loop.Changethecallofcaptionto

caption(t,nnz(X),toc)

Maketheap

propriate

modificationsin

thecaption

subfunction

attheend

of

lifex.m.Dem

onstrate

yourmodified

program

onafew

interestingexamples.

12.8

TheArk.Run

160

Chapter12

.Gam

eof

Life

lifex(’ark’,128)

forafew

minutes.

Abouthow

much

timedoes

ittakeonyou

rcomputerto

doone

step?Accordingto

theLexicon,thearkrequires

736692stepsto

stabilize.

About

how

much

timewillittakeonyou

rcomputerforthearkto

stabilize?

12.9

Houses.

Checkou

t

lifex(houses)

12.10Checkerboards.

This

codegeneratesan

n-by-n

checkerboard

of0’sand1’s.

[I,J]=

meshgrid(1:n);

C=

(mod(I+J,2)==0);

Whatare

thestabilization

times

and

finalpopulationsforn-by-n

checkerboard

initialpopulationswith3<=

n<=

30?

12.11Earlyexit.W

hereshould

thesecodesegments

Xsave=

X;

and

if

isequal(X,Xsave)

break

end

beinserted

inlife_recap?

12.12Sym

metry.W

hatis

theeff

ectofinsertingthestatement

X=

(X

+X’

>0)

after

thegenerationofX

atthebeginningoflife_recap.

12.13Liveordie?

Insert

thesestatements

before

thefirstexecutable

statementof

life_recap.

P=

zeros(10000,2);

fors

=1:10000

Insert

thesestatements

after

thelast

executable

statement.

P(s,:)=

[p0

p100];

end

Deactivateorremovethespy,title,pauseandfprintfstatements.

Runthe

resultingprogram

andthen

generate

histogramsof

theresults.

Page 86: Experiments With MatLab Moled 2011

161

R=

P(:,2)./P(:,1);

hist(P(:,1),30)

hist(P(:,2),30)

hist(R,30)

(a)Is

thetypicalpopulationgrow

ingordecliningafter100generations?

(b)Doyourecognizetheshapeofthehistogram

oftheinitialpopulation,P(:,1)?

Whatismean(P(:,1))?W

hy?

(c)Idon’t

know

enoughab

outprobabilityto

describethedistributionofthefinal

population,P(:,2).Cananybodyhelpmeou

t?

12.14

Gosper’s

glider

gun.

Replace

therandom

initialpop

ulation

generatorin

life_recapbythis

code:

%Gosper

glider

gun

gun=

[’

+’

’+

+’

’++

++

++’

’+

+++

++’

’++

++

++

’++

++

++

++

’+

++

’+

+’

’++

’];

X=

sparse(76,76);

X(34:42,20:57)=

(gun==’+’);

spy(X)

(a)How

manystepsdoes

ittakeforthegunto

emitaglider?

(b)W

hathappenswhen

aglider

meets

thebou

ndary?

How

isthis

differentfrom

lifex(’gosper’)?

162

Chapter12

.Gam

eof

Life

Page 87: Experiments With MatLab Moled 2011

Chapter13

MandelbrotSet

Fractals,topology,complexarithmetic

andfascinatingcomputergraphics.

Benoit

MandelbrotwasaPolish/French/American

mathem

atician

whohas

spentmost

ofhiscareer

attheIB

MWatsonResearchCenterin

YorktownHeights,

N.Y

.Hecoined

theterm

fractalandpublished

averyinfluentialbook

,TheFractal

Geometry

ofNature,in

1982.Anim

ageofthenow

famousMandelbrotsetappeared

onthecoverofScien

tificAmericanin

1985.Thiswas

abou

tthetimethatcomputer

graphicaldisplayswerebecomingwidelyavailable.Since

then,theMandelbrotset

hasstim

ulateddeepresearchtopicsin

mathem

atics

andhasalsobeenthebasisfor

anuncountable

number

ofgraphicsprojects,

hardwaredem

os,

andWeb

pages.

Toget

inthemoodfortheMandelbrotset,consider

theregionin

thecomplex

planeof

trajectories

generatedbyrepeatedsquaring,

z k+1=

z2 k,

k=

0,1,...

For

whichinitialvalues

z 0does

this

sequence

remain

bounded

ask→

∞?

Itis

easy

toseethatthis

setis

simply

theunit

disc,

|z 0|<

=1,

show

nin

figure

13.1.

If|z 0

|<=

1,thesequence

z kremainsbounded.Butif|z 0

|>1,thesequence

isunbou

nded.Theboundary

oftheunit

discis

theunit

circle,|z 0

|=1.Thereis

nothingverydiffi

cult

orexcitinghere.

Thedefinition

istheMandelbrotsetis

only

slightlymore

complicated.

Itinvolves

repeatedly

addingin

theinitialpoint.

TheMandelbrotsetistheregionin

thecomplexplaneconsistingofthevalues

z 0forwhichthetrajectories

defi

ned

by

z k+1=

z2 k+z 0,

k=

0,1,...

remain

bou

nded

atk→

∞.That’sit.That’stheentire

defi

nition.It’s

amazing

thatsuch

asimple

definitioncanproduce

such

fascinatingcomplexity.

Copyright

c ©2011CleveMoler

Matlab

R ©is

aregisteredtradem

ark

ofMath

Works,

Inc.

TM

October

4,2011

163

164

Chapter13

.Mandelbrot

Set

−1.5

−1−0.5

00.5

11.5

−1.5−1

−0.50

0.51

1.5

Figure

13.1.Theunit

discis

shownin

red.Theboundary

issimply

the

unitcircle.Thereis

nointricate

fringe.

−2−1

.5−1

−0.5

00.

51

−1.5−1

−0.50

0.51

1.5

Figure

13.2.TheMandelbrotsetis

shownin

red.Thefringe

just

outside

theset,shownin

black,is

aregionofrich

structure.

Page 88: Experiments With MatLab Moled 2011

165

Figure

13.3.Twotrajectories.z0

=.25-.54igeneratesacycleoflength

four,

whilenearbyz0

=.22-.54igeneratesanunbounded

trajectory.

Figure

13.2

show

stheoverallgeometry

oftheMandelbrotset.

How

ever,this

view

does

nothavetheresolutionto

show

therichly

detailed

structure

ofthefringe

just

outsidetheboundary

oftheset.

Infact,thesethastinyfilaments

reachinginto

thefringeregion,even

thoughthefringeappears

tobesolidblack

inthefigure.It

hasrecentlybeenprovedthattheMandelbrotsetismathem

aticallyconnected,but

theconnectedregionis

sometim

esso

thin

thatwecannotresolveit

onagraphics

screen

oreven

compute

itin

areasonable

amountoftime.

Toseehow

thedefinitionworks,

enter

z0

=.25-.54i

z=

0

into

Matlab.Then

use

theup-arrow

key

torepeatedly

execute

thestatement

z=

z^2

+z0

Thefirstfew

lines

ofoutputare

0.2500-

0.5400i

0.0209-

0.8100i

-0.4057-

0.5739i

0.0852-

0.0744i

0.2517-

0.5527i

...

Thevalues

eventuallysettle

into

acycle

0.2627-

0.5508i

0.0156-

0.8294i

-0.4377-

0.5659i

0.1213-

0.0446i

166

Chapter13

.Mandelbrot

Set

0.2627-

0.5508i

...

This

cyclerepeats

forever.Thetrajectory

remainsbounded

.This

tellsusthatthe

startingvaluevalue,

z0=

.25-.54i,is

intheMandelbrotset.

Thesamecycleis

show

nin

theleft

halfoffigure

13.3.

Ontheother

hand,start

with

z0

=.22-.54i

z=

0

andrepeatedly

execute

thestatement

z=

z^2

+z0

Youwillsee

0.2200-

0.5400i

-0.0232-

0.7776i

-0.3841-

0.5039i

0.1136-

0.1529i

0.2095-

0.5747i

...

Then,after24iterations,

...

1.5708-

1.1300i

1.4107-

4.0899i

-14.5174-12.0794i

6.5064e+001+3.5018e+002i

-1.1840e+005+4.5568e+004i

Thetrajectory

isblowinguprapidly.After

afew

more

iterations,thefloatingpoint

numbersoverflow

.Sothisz0is

notin

theMandelbrotset.

Thesameunbou

nded

trajectory

isshow

nin

therighthalf

offigure

13.3.

Weseethatthefirstvalue,

z0

=.25-.54i,is

intheMandelbrotset,

whilethesecondvalue,

z0

=.22-.54i,

whichis

nearby,

isnot.

Thealgorithm

doesn’t

haveto

wait

untilzreachsfloatingpointoverflow

.As

soonaszsatisfies

abs(z)>=

2

subsequentiterationswillessentialsquare

thevalueof|z|

andit

willbeh

avelike

22k

.Try

ityourself.

Putthesestatements

ononeline.

z0

=...

z=

0;

whileabs(z)<

2

z=

z^2+z0;

disp(z),

end

Page 89: Experiments With MatLab Moled 2011

167

Use

theuparrow

andbackspace

keysto

retrievethestatementandchangez0to

differentvalues

near.25-.54i.

Ifyouhaveto

hit

<ctrl>-cto

breakou

tofan

infiniteloop,then

z0isin

theMandelbrotset.

Ifthewhileconditioniseventually

falseandtheloopterm

inateswithoutyourhelp,then

z0is

notin

theset.

Thenumber

ofiterationsrequired

forzto

escapethediscofradius2provides

thebasisforshow

ingthedetailin

thefringe.

Let’s

addaniterationcounterto

the

loop.A

quantity

wecalldepthspecifies

themaxim

um

interationcountan

dthereby

determines

boththelevelofdetailandtheoverallcomputationtime.

Typicalvalues

ofdepthare

severalhundredorafew

thousand.

z0

=...

z=

0;

k=

0;

whileabs(z)<

2&&

k<

depth

z=

z^2+z0;

k=

k+

1;

end

Themaxim

um

valueof

kis

depth.If

thevalueof

kis

less

thandepth,then

z0

isoutsidetheset.

Largevalues

ofkindicate

thatz0is

inthefringe,

close

tothe

bou

ndary.Ifkreaches

depththen

z0is

declaredto

beinsidetheMandelbrotset.

Hereisasm

alltable

ofiterationcounts

sz0ranges

over

complexvalues

near

0.22-0.54i.Wehavesetdepth=

512.

0.2050.2100.2150.2200.2250.2300.2350.2400.245

-0.520

512

512

512

512

512

512

44

512

512

-0.525

512

512

512

512

512

36

51

512

512

-0.530

512

512

512

512

35

31

74

512

512

-0.535

512

512

512

512

26

28

57

512

512

-0.540

512

139

113

26

24

73

56

512

512

-0.545

512

199

211

21

22

25

120

512

512

-0.550

33

25

21

20

20

25

63

85

512

-0.555

34

20

18

18

19

21

33

512

512

-0.560

62

19

17

17

18

33

162

40

344

Weseethatabouthalfof

thevalues

are

less

thandepth;they

correspondto

points

outsideof

theMandelbrotset,

inthefringeneartheboundary.Theother

halfof

thevalues

are

equalto

depth,correspondingto

points

thatare

regarded

asin

the

set.

Ifwewereto

redothecomputationwithalarger

valueof

depth,theentries

thatare

less

than512in

this

table

would

notchange,

butsomeoftheentriesthat

are

now

capped

at512mightincrease.

Theiterationcounts

canbeusedasindices

into

anRGB

colormapof

size

depth-by-3.Thefirstrow

ofthis

mapspecifies

thecolorassigned

toanypoints

onthez0gridthatlieoutsidethediscofradius2.Thenextfew

rowsprovidecolors

forthepoints

onthez0gridthatgenerate

trajectories

thatescapequickly.The

last

row

ofthemapis

thecolorof

thepoints

thatsurvivedepthiterationsandso

are

intheset.

168

Chapter13

.Mandelbrot

Set

Themapusedin

figure

13.2

emphasizesthesetitselfan

ditsboundary.The

maphas12rowsofwhiteat

thebeginning,on

erow

ofdark

redattheend,and

black

inbetween.Im

ages

thatem

phasize

thestructure

inthefringeareachieved

when

thecolormapvaries

cyclicly

over

afew

dozencolors.Oneoftheexercises

asksyou

toexperim

entwithcolormaps.

Figure

13.4.Im

provingresolution.

Array

operations.

Ourscriptmandelbrot_recapshow

show

Matlabarray

arithmeticoperatesagrid

ofcomplexnumberssimultaneouslyandaccumulatesan

arrayof

iterationcounters,

producingim

ages

likethose

infigure

13.4

Thecodebeginsbydefiningtheregion

inthecomplexplaneto

besampled.A

step

size

of0.05gives

thecoarseresolution

show

non

therightin

thefigure.

x=

0:

0.05:

0.80;

y=

x’;

Thenextsectionof

codeusesanelegant,buttricky,

bitofMatlabindexing

know

nasTony’s

Trick.Thequantities

xandyare

one-dim

ensionalrealarray

sof

length

n,on

eacolumnvectorandtheother

arow

vector.

Wewantto

create

atw

o-

dim

ensionaln-by-n

array

withelem

ents

form

edfrom

allpossible

sumsof

elem

ents

from

xandy.

z k,j=

xk+

y ji,

i=

√ −1,k,j

=1,...,n

Thiscanbedonebygeneratingavectoreoflength

nwithallelem

ents

equalto

one.

Then

thequantity

x(e,:)isatw

o-dim

ensionalarray

form

edbyusingx,whichisthe

sameasx(1,:),ntimes.Sim

ilarly,

y(:,e)is

atw

o-dim

ensionalarrraycontaining

ncopiesofthecolumnvectory.

Page 90: Experiments With MatLab Moled 2011

169

n=

length(x);

e=

ones(n,1);

z0

=x(e,:)

+i*y(:,e);

Ifyoufindithard

toremem

ber

Ton

y’sindexingtrick,thefunctionmeshgrid

does

thesamethingin

twostep

s.

[X,Y]=

meshgrid(x,y);

z0

=X

+i*Y;

Now

initialize

twomore

array

s,on

eforthecomplexiteratesan

doneforthe

counts.

z=

zeros(n,n);

c=

zeros(n,n);

HereistheMandelbrotiterationrepeateddepthtimes.W

itheach

iterationwealso

keeptrack

oftheiteratesthatare

stillwithin

thecircle

ofradius2.

depth=

32;

fork

=1:depth

z=

z.^2

+z0;

c(abs(z)<

2)

=k;

end

Weare

now

finished

withz.Theactualvalues

ofzare

notim

portant,

only

the

counts

are

needed

tocreate

theim

age.

Ourgridissm

allenoughthatwecanactually

printoutthecounts

c.

c

Theresultsare

c= 32

32

32

32

32

32

11

76

54

33

32

22

32

32

32

32

32

32

32

96

54

33

32

22

32

32

32

32

32

32

32

32

75

43

33

22

2

32

32

32

32

32

32

32

32

27

54

33

32

22

32

32

32

32

32

32

32

32

30

64

33

32

22

32

32

32

32

32

32

32

32

13

74

33

32

22

32

32

32

32

32

32

32

32

14

75

33

22

22

32

32

32

32

32

32

32

32

32

17

43

32

22

2

32

32

32

32

32

32

32

16

818

43

32

22

2

32

32

32

32

32

32

32

11

65

43

32

22

2

32

32

32

32

32

32

32

19

65

43

22

22

2

32

32

32

32

32

32

32

23

84

43

22

22

2

32

32

32

19

11

13

14

15

14

43

22

22

22

22

32

12

32

77

714

64

32

22

22

2

12

98

75

55

17

43

32

22

22

1

32

76

55

44

43

32

22

22

11

17

75

44

44

33

22

22

22

11

170

Chapter13

.Mandelbrot

Set

Weseethatpoints

intheupper

left

ofthegrid,withfairly

smallinitialz0values,

havesurvived

32iterationswithoutgoingoutsidethecircle

ofradiustw

o,while

points

inthelower

right,withfairly

largeinitialvalues,havelasted

only

oneortw

oiterations.

Theinterestinggridpoints

are

inbetween,they

are

onthefringe.

Now

comes

thefinalstep,makingtheplot.

Theimagecommanddoes

the

job,even

thoughthisisnotan

imagein

theusualsense.Thecountvalues

incare

usedasindices

into

a32-by-3

array

ofRGB

colorvalues.In

this

example,thejet

colorm

apisreversedto

givedark

redas

itsfirstvalue,

pass

throughshades

ofgreen

andyellow,andfinishwithdark

blueasits32-ndandfinalvalue.

image(c)

axisimage

colormap(flipud(jet(depth)))

Exercisesask

youto

increase

theresolutionbydecreasingthestep

size,thereby

producingtheother

halfof

figure

13.4,to

investigate

theeff

ectofchangingdepth,

andto

invesigate

other

colormaps.

MandelbrotGUI

Theexmtoolbox

functionmandelbrotis

yourstartingpointforexplorationofthe

Mandelbrotset.

Withnoarguments,thestatement

mandelbrot

provides

thumbnailiconsofthetw

elve

regionsfeaturedin

this

chapter.

Thestate-

ment

mandelbrot(r)

withrbetween1and12startswithther-thregion.Thestatement

mandelbrot(center,width,grid,depth,cmapindx)

explorestheMandelbrotsetin

asquare

regionof

thecomplexplanewiththespeci-

fied

centerandwidth,usingagrid-by-gridgrid,an

iterationlimitofdepth,and

thecolormapnumber

cmapindx.Thedefaultvalues

oftheparametersare

center=

-0.5+0i

width=

3

grid=

512

depth=

256

cmapindx=

1

Inother

words,

mandelbrot(-0.5+0i,3,

512,

256,

1)

generatesfigure

13.2,butwiththejetscolormap.Changingthelast

argument

from

1to

6generatestheactualfigure

13.2

withthefringecolormap.Onmy

laptop,thesecomputationseach

takeabouthalfasecond.

Asimple

estimate

oftheexecutiontimeis

proportionalto

Page 91: Experiments With MatLab Moled 2011

171

grid^2*

depth

Sothestatement

mandelbrot(-0.5+0i,3,

2048,

1024,

1)

could

take

(2048/512)2

·(1024/256)=

64

times

aslongasthedefault.How

ever,this

isanoverestimate

andtheactualexe-

cutiontimeis

about11

seconds.

Most

ofthecomputationaltimerequired

tocompute

theMandelbrotsetis

spentupdatingtw

oarray

szandkzbyrepeatedly

executingthestep

z=

z.^2

+z0;

j=

(abs(z)

<2);

kz(j)=

d;

Thiscomputationcanbecarriedoutfaster

bywritingafunctionmandelbrot_step

inC

andcreatingasaMatlabexecutableor

c-mex

file.Differentmachines

and

operatingsystem

srequiredifferentversionsof

amex

file,so

youshould

seefiles

withnames

likemandelbrot_step.mexw32andmandelbrot_step.glnx64in

the

exmtoolbox

.ThemandelbrotguiturnsontheMatlabzoom

feature.Themouse

pointer

becomes

asm

allmagnifyingglass.You

canclickandrelease

onapointto

zoom

by

afactoroftw

o,oryoucanclickanddragto

delineate

anew

region.

Themandelbrotguiprovides

severaluicontrols.Try

theseasyoureadalong.

Thelistboxatthebottom

oftheguiallow

syouto

select

anyof

thepredefined

region

sshow

nin

thefigu

resin

this

chapter.

depth.Increase

thedepth

byafactorof3/2or

4/3.

grid.

Refinethegrid

byafactorof3/2or4/3.

Thedep

than

dgrid

size

are

alwaysapow

eroftw

oor

threetimes

apow

eroftw

o.Twoclicksonthedepthor

gridbuttondoublestheparameter.

color.

Cyclethroughseveralcolormaps.

jetsandhotsare

cyclic

repetitions

ofshort

copiesof

thebasicMatlabjetandhotcolormaps.

cmykcycles

through

eightbasiccolors,blue,

green,red,cyan

,magenta,yellow,gray,

andblack.fringe

isanoncyclic

mapusedforim

ages

likefigure

13.2.

exit.Close

thegu

i.

TheMandelbrotsetis

selfsimilar.

Smallregionsin

thefringerevealfeatures

thatare

similarto

theoriginalset.

Figure

13.6,whichwehavedubbed

“Mandelbrot

172

Chapter13

.Mandelbrot

Set

Figure

13.5.Thefiguresin

this

chapter,

andthepredefi

ned

regionsin

our

mandelbrotprogram,show

theseregionsin

thefringe

just

outsidetheMandelbrot

set.

Junior”,is

oneexample.Figure

13.7,whichwecallthe“‘Plaza”,usesourflag

colorm

apto

revealfinedetailin

red,whitean

dblue.

Theportionoftheboundary

oftheMandelbrotsetbetweenthetw

olarge,

nearlycircularcentralregionsis

know

nas“TheValleyof

theSeahorses”.

Fig-

ure

13.8

show

stheresult

ofzoomingin

onthepeninsula

betweenthetw

onearly

circularregionsof

theset.

Thefigure

canbegenerateddirectlywiththecommand

mandelbrot(-.7700-.1300i,0.1,1024,512)

Wedecided

tonametheim

agein

figure

13.9

the“WestW

ing”because

itresembles

theX-w

ingfighterthatLukeSkywalker

fliesin

StarWars

andbecause

itislocated

neartheleftmost,orfarwestern,portionof

theset.

Themagnificationfactoris

arelativelymodest104,so

depthdoes

notneedto

beverylarge.

Thecommandto

gen

erate

theWestW

ingis

mandelbrot(-1.6735-0.0003318i,1.5e-4,1024,160,1)

Oneof

thebestknow

nexamplesof

selfsimilarity,the“Buzzsaw”,isshow

nin

figure

13.11.It

canbegeneratedwith

mandelbrot(0.001643721971153+0.822467633298876i,...

Page 92: Experiments With MatLab Moled 2011

173

4.0e-11,1024,2048,2)

Takingwidth=

4.0e-11correspondsto

amagnificationfactorofalm

ost

101

1.To

appreciate

thesize

ofthis

factor,

iftheoriginalMandelbrotsetfillsthescreen

onyou

rcomputer,

theBuzzsaw

issm

aller

thantheindividualtransistors

inyou

rmachine’smicroprocessor.

Wecallfigure

13.12“Nebula”because

itremindsusofinterstellardust.It

isgeneratedby

mandelbrot(0.73752777-0.12849548i,4.88e-5,1024,2048,3)

Thenextthreeim

ages

are

obtained

bycarefullyzoomingonon

elocation.We

callthem

the“Vortex”,the“M

icrobug”,andthe“Nucleus”.

mandelbrot(-1.74975914513036646-0.00000000368513796i,...

6.0e-12,1024,2048,2)

mandelbrot(-1.74975914513271613-0.00000000368338015i,...

3.75e-13,1024,2048,2)

mandelbrot(-1.74975914513272790-0.00000000368338638i,...

9.375e-14,1024,2048,2)

Themost

intricate

andcolorfulim

ageamongourexamplesis

figure

13.16,

the“Geode”.It

invo

lves

afinegridandalargevalueofdepthandconsequently

requires

afew

minutesto

compute.

mandelbrot(0.28692299709-0.01218247138i,6.0e-10,2048,4096,1)

Theseexamplesare

just

atinysamplingof

thestructure

oftheMandelbrot

set.

Further

Rea

ding

Wehighly

recommend

arealtimefractalzoomer

called

“XaoS”,developed

by

ThomasMarsh,JanHubicka

andZoltanKovacs,assistedbyaninternationalgroup

ofvolunteers.

See

http://wmi.math.u-szeged.hu/xaos/doku.php

IfyouareexpertatusingyourWeb

browserandpossibly

dow

nloadingan

obscure

video

codec,takealook

attheW

ikiped

iavideo

http://commons.wikimedia.org/wiki/...

Image:Fractal-zoom-1-03-Mandelbrot_Buzzsaw.ogg

It’s

terrificto

watch,butitmay

bealotoftrouble

togetworking.

Rec

ap

%%Mandelbrot

Chapter

Recap

%This

is

an

executable

program

that

illustrates

the

statements

174

Chapter13

.Mandelbrot

Set

%introduced

in

the

Mandelbrot

Chapter

of

"Experiments

in

MATLAB".

%You

can

access

it

with

% %mandelbrot_recap

%edit

mandelbrot_recap

%publish

mandelbrot_recap

% %Related

EXM

programs

% %mandelbrot

%%

Define

the

region.

x=

0:

0.05:

0.8;

y=

x’;

%%

Create

the

two-dimensional

complex

grid

using

Tony’s

indexing

trick.

n=

length(x);

e=

ones(n,1);

z0

=x(e,:)

+i*y(:,e);

%%

Or,

do

the

same

thing

with

meshgrid.

[X,Y]=

meshgrid(x,y);

z0

=X

+i*Y;

%%

Initialize

the

iterates

and

counts

arrays.

z=

zeros(n,n);

c=

zeros(n,n);

%%

Here

is

the

Mandelbrot

iteration.

depth=

32;

fork

=1:depth

z=

z.^3

+z0;

c(abs(z)<

2)

=k;

end

%%

Create

an

image

from

the

counts.

c image(c)

axisimage

%%

Colors

colormap(flipud(jet(depth)))

Page 93: Experiments With MatLab Moled 2011

175

Exe

rcises

13.1

Explore.Use

themandelbrotguito

findsomeinterestingregionsthat,

asfar

asyou

know

,havenever

beenseen

before.Givethem

yourow

nnames.

13.2

depth.Modifymandelbrot_recapto

reproduce

ourtable

ofiterationcounts

forx

=.205:.005:.245andy=

-.520:-.005:-.560.First,use

depth=

512.

Then

use

larger

values

ofdepthandseewhichtable

entrieschange.

13.3

Resolution.Reproduce

theim

agein

therighthalfoffigure

13.4.

13.4

Big

picture.Modifymandelbrot_recapto

displaytheentire

Mandelbrotset.

13.5

Colormaps.

Investigate

colormaps.

Use

mandelbrot_recapwithasm

aller

step

size

andalargevalueofdepthto

produce

anim

age.

Findhow

mandelbrot

computesthecyclic

colormapscalled

jets,hotsandsepia.Then

use

those

maps

onyourim

age.

13.6

p-thpower.In

either

mandelbrot_recaporthemandelbrotgui,changethe

pow

erin

theMandelbrotiterationto

z k+1=

zp k+

z 0

forsomefixed

p�=

2.If

youwan

tto

tryprogrammingHandle

Graphics,

adda

buttonto

mandelbrotthatlets

you

setp.

13.7

Too

much

magn

ification.W

hen

thewidth

oftheregiongetsto

besm

aller

than

about10−15,ourmandelbrotguidoes

notwork

verywell.W

hy?

13.8

Spin

thecolormap.Thismightnotwork

verywellon

yourcomputerbecause

itdep

endsonwhatkindofgraphicshardwareyouhave.

When

youhaveaninteresting

regionplotted

inthefigure

window

,bringupthecommandwindow

,resize

itso

that

itdoes

notcoverthefigure

window

,andenterthecommand

spinmap(10)

Iwon’ttryto

describewhathappens–youhaveto

seeitforyourself.

Theeff

ectis

most

dramaticwiththe“seahorses2”region.Enter

helpspinmap

formore

details.

176

Chapter13

.Mandelbrot

Set

Figure

13.6.

Region

#2,“MandelbrotJunior”.

Thefringe

aroundthe

Mandelbrotsetin

self

similar.

Small

versionsofthesetappearatall

levels

of

magn

ification.

Figure

13.7.Region#3,“Plaza”,withtheflagcolormap.

Page 94: Experiments With MatLab Moled 2011

177

Figure

13.8.Region#4.“Valley

oftheSeahorses”.

Figure

13.9.Region#5.Our“WestWing”

islocatedjust

offtherealaxis

inthethin

farwestern

portionoftheset,nearreal(z)

=-1.67.

178

Chapter13

.Mandelbrot

Set

Figure

13.10.Region#6.“DuelingDragons”.

Figure

13.11.Region#7.The“Buzzsaw”requires

amagn

ificationfactor

of10

11to

revealatinycopyoftheMandelbrotset.

Page 95: Experiments With MatLab Moled 2011

179

Figure

13.12.Region#8.“Nebula”.Interstellardust.

Figure

13.13.Region#9.A

vortex,notfarfrom

theWestWing.

Zoom

inononeofthecircular“microbugs”neartheleftedge.

180

Chapter13

.Mandelbrot

Set

Figure

13.14.

Region#10.A

1013magn

ificationfactorreveals

a“mi-

crobug”

within

thevortex.

Figure

13.15.Region#11.Thenucleusofthemicrobug.

Page 96: Experiments With MatLab Moled 2011

181

Figure

13.16.Region#12.“Geode”.This

colorfulim

age

requires

a2048-

by-2048grid

anddepth

=8192.

182

Chapter13

.Mandelbrot

Set

Page 97: Experiments With MatLab Moled 2011

Chapter14

Sudoku

Humanslookforpatterns,

butmachines

use

backtracking.

Thefascinationthatpeople

haveforsolvingSudoku

puzzleswithoutacom-

puterderives

from

thediscoveryandmasteryofamyriadof

subtlecombinations

andpatternsthatprovidetipstoward

thesolution.TheWeb

hashundredsof

sites

describingthesepatterns,

whichhavenames

like“h

idden

quads”,“X-w

ing”an

d“squirmbag”.

Itisnotourintentionto

describeaMatlabprogram

thatduplicatesthesehu-

manpatternrecognitioncapabilities.

Instead,ourprogram,likemost

other

Sudoku

computercodes,takes

averydifferentapproach,onethatrelies

onthemachine’s

alm

ost

limitless

capacity

tocarry

outbrute

forcetrialand

error.

Weuse

only

onepattern,singletons,

together

withafundamentalcomputerscience

technique,

recursivebacktracking.

IntheSudokuworld,backtrackingisregardingas“guessing”an

disconsidered

badform

.Butas

acomputationaltechnique,

itis

easy

tounderstand,straightfor-

wardto

implementan

dguaranteed

tosucceed.

Inthis

chapter,wewilldescribefiveMatlabprogramsforexperim

ents

with

Sudoku.

•sudoku.Aninteractiveprogram

thatlets

you

follow

thecomputersolution

process.

•sudoku_basic.Thesamesolutionprocess

assudoku,butwithoutthegraph-

icsinterface.

Much

easier

toread,an

dmuch

faster

ifyou

just

wantthe

solution.

•sudoku_all.

Enumerate

all

solutionsto

aSudoku

puzzle.

Avalid

puzzle

should

haveonly

onesolution.

Copyright

c ©2011CleveMoler

Matlab

R ©is

aregisteredtradem

ark

ofMath

Works,

Inc.

TM

October

4,2011

183

184

Chapter14

.Sudoku

•sudoku_assist.

Aninteractiveprogram

thatlets

you

controlthesolution

process,asyou

would

byhandonpaper.

•sudoku_puzzle.A

collectionof

interestingpuzzles.

Sudoku

isactuallyanAmericaninvention.It

firstappeared,withthename

Number

Place,in

theDellPuzzle

Magazinein

1979.

Thecreatorwas

probably

How

ardGarns,

anarchitectfrom

Indianapolis.

AJapanesepublisher,Nikoli,took

thepuzzle

toJapanin

1984andeventuallygaveit

thenameSudoku,whichis

akindof

kanjiacronym

for“numbersshould

besingle,unmarried.”

TheTim

esof

Londonbeganpublishingthepuzzle

intheUK

in2004andit

wasnotlongbefore

itspreadback

totheUSan

daroundtheworld.

8 3 4 1

1 5 9 2

6 7 2 3

1 8 3 4

1 5 9

6 7 2 3

1 8 3 4

8 1 5 9

3 6 7 2

Figure

14.1.A

Sudoku

puzzle

featuringLo-Shu,themagicsquare

oforder

3.

You

probably

alreadyknow

therulesofSudoku.Figure

20isan

exampleofan

initial9-by-9

grid,withafew

specified

digitsknow

nastheclues.This

particular

puzzle

reflects

ourinterest

inmagic

squares.

Itis

thesum

ofthetw

omatrices

show

nin

figure

20.

Thematrix

ontheleft

isgenerated

bythefunctionskron,

which

computessomethingknow

nastheKroneckerproduct,an

dmagic,which

generatesmagic

squares.

X=

kron(eye(3),magic(3))

Inthis

case,aKroneckerproduct

involvingtheidentity

matrix

producesablock

matrix

withthreecopiesofmagic(3)onthediagonal.

Byitself,this

array

isnot

avalidSudokupuzzle,because

thereis

more

thanoneway

tocomplete

it.The

solutionis

notunique.

Inorder

togetapuzzle

withauniquesolution,wehave

added

thematrix

ontherightin

figure

20.

Figure

14.3

isthefinalcompleted

grid.

Each

row,each

column,and

each

major3-by-3

block,must

contain

exactly

thedigits1through9.

Incontrast

to

Page 98: Experiments With MatLab Moled 2011

185

8 3 4

1 5 9

6 7 2

8 3 4

1 5 9

6 7 2

8 3 4

1 5 9

6 7 21

2

3

1

3

1

8

3

Figure

14.2.OurLo-Shubasedpuzzle

isthesum

ofthesetwomatrices.

8 3 4 2 9 7 5 6 1

1 5 9 4 8 6 7 2 3

6 7 2 3 1 5 9 4 8

5 6 1 8 3 4 2 9 7

7 2 3 1 5 9 4 8 6

9 4 8 6 7 2 3 1 5

2 9 7 5 6 1 8 3 4

4 8 6 7 2 3 1 5 9

3 1 5 9 4 8 6 7 2

Figure

14.3.Thecompletedpuzzle.Thedigitshave

been

inserted

sothat

each

row,each

column,andeach

major3-by-3blockcontains1through

9.

The

originalclues

are

shownin

blue.

magic

squaresandother

numeric

puzzles,

noarithmetic

isinvolved

.Theelem

ents

inaSudoku

gridcould

just

aswellbeninelettersofthealphabet,oranyother

distinct

symbols.

186

Chapter14

.Sudoku

1

2

3

4

Figure

14.4.Shidoku

1 2

4

3 4

3

3 4

4 2 1 3

2

4 3 1 1 2

2

1 2

1 3 4

Figure

14.5.Candidates

1 2

4

4 3

3 4

4 2 1

2

4 3 1 1 2

2

1 2

1 3 4

Figure

14.6.Insert

singleton

1 2 4 3

3 4 2 1

4 3 1 2

2 1 3 4

Figure

14.7.Solution

Shidoku

Toseehow

oursudokuprogram

works,

wecan

use

Shidoku

instead

ofSudoku.

“Shi”

isJapanesefor“four”.Thepuzzlesuse

a4-by-4

gridandarealm

ost

trivialto

solvebyhand.Figure

20isou

rfirstShidoku

puzzle

andthenextthreefiguresshow

stepsin

itssolution.In

figure

20,thepossible

entries,

orcandidates,

are

show

nby

smalldigits.

For

example,row

twocontainsa3an

dcolumnonecontainsa1so

the

candidatesin

position(2,1)are

2and4.

Fourof

thecellshaveonly

onecandidate

each.Theseare

thesingletons,

show

nin

red.In

figure

20,wehaveinserted

the

singleton3in

the(4,1)cellan

drecomputedthecandidates.

Infigure

14.7,wehave

inserted

theremainingsingletonsas

they

aregeneratedto

complete

thesolution.

Page 99: Experiments With MatLab Moled 2011

187

1

2

3

4

Figure

14.8.diag(1:4)

1 3 4

2

4

2

3

3 4 2 1 4

1 3

2

4

1 4 3 1 2

2

3 1 3 1 2 4

Figure

14.9.Nosingletons.

1 32

3

4

Figure

14.10.Backtrack

step.

1 3 4 2

4 2 1 3

2 4 3 1

3 1 2 4

Figure

14.11.Solutionis

notunique.

Theinputarray

forfigure

14.8

isgeneratedbytheMatlabstatement

X=

diag(1:4)

Asfigure

14.9

show

s,thereare

nosingletons.

So,weem

ployabasiccomputerscience

technique,

recursivebacktracking.Weselect

oneof

theem

pty

cellsandtentatively

insert

oneofitscandidates.

Allof

theem

pty

cellshavetw

ocandidates,

sowepick

thefirston

eandtentatively

insert

a3in

cell(2,1).

This

createsanew

puzzle,

show

nin

figure

14.10.Ourprogram

isthen

called

recursively.

Inthisexample,the

new

puzzle

iseasily

solved

andtheresult

isshow

nin

figure

14.11.How

ever,the

solutiondep

endsuponthechoices

thatwemadebefore

therecursivecall.Other

choices

canleadto

differentsolutions.

Forthis

simple

diagonalinitialcondition,

188

Chapter14

.Sudoku

thesolutionis

notunique.

Therearetw

opossible

solutions,

whichhappen

tobe

matrix

transposesofeach

other.

Y=

shidoku(diag(1:4))

Y=

14

23

32

41

41

32

23

14

Z=

shidoku(diag(1:4)’)’

Z=

13

42

42

13

24

31

31

24

Existen

ceanduniquen

ess

Mathem

aticiansare

alwaysconcerned

abou

texistence

anduniquenessin

thevarious

problemsthatthey

encounter.

For

Sudoku,neither

existence

noruniquenesscan

bedetermined

easily

from

theinitialclues.It

wou

ldbeveryfrustratingifapuzzle

withnosolution,or

withmore

thanon

esolution,wereto

show

upin

yourdaily

new

spaper.

Uniquenessis

anelusiveproperty.

Infact,most

descriptionsof

Sudoku

do

notspecifythattherehasto

beexactly

onesolution.Theonly

way

thatIknow

tocheckuniquen

essis

toexhaustivelyenumerate

allpossibilities.

For

ourmagicsquare

puzzlein

figure

20,ifwewereto

replace

the1in

the(9,1)

cellbya5,6or

7,therow,columnandblock

conditionswould

stillbesatisfied.

Itturnsoutthata5would

produce

another

validpuzzle

withauniquesolution,

a6would

produce

apuzzle

withtw

opossible

solutions,

anda7would

produce

apuzzle

withnosolution.Anexercise

asksyou

toverifytheseclaim

s.It

takes

sudoku_allalittle

over

halfan

houron

mylaptopto

determinethat

themagic

square

puzzle

generatedby

X=

kron(eye(3),magic(3))

withouttheaddionalentrieson

rightin

figure

20has283576solutions.

Thepuzzle

generatedby

X=

sudoku_puzzle(13)

hasan

interestingspiralpattern.Butthereareover

300solutions.

Anexercise

asks

you

tofindoutexactly

how

many.

Page 100: Experiments With MatLab Moled 2011

189

Anumber

ofoperationsonaSudokugridcanchangeitsvisualap

pearance

withoutchangingitsessentialcharacteristics.Allofthevariationsare

basicallythe

samepuzzle.Theseequivalence

operationscanbeexpressed

asarray

operationsin

Matlab.Forexample

p=

randperm(9)

z=

find(X

>0)

X(z)=

p(X(z))

permutesthedigitsrepresentingtheelem

ents.Other

operationsinclude

X’

rot90(X,k)

flipud(X)

fliplr(X)

X([4:91:3],:)

X(:,[randperm(3)4:9])

Thealgorithm

Ifwedonotcountthecomments

andGUI,sudoku.minvolves

less

than40lines

of

code.

Theoutlineofthemain

program

is:

•Fillin

allsingletons.

•Exitifacellhasnocandidates.

•Fillin

atentativevalueforanem

pty

cell.

•Calltheprogram

recursively.

sudokuandsudokubasic

Hereis

theheader

forsudoku_basic.

function[X,steps]=

sudoku_basic(X,steps)

%SUDOKU_BASIC

Solve

the

Sudoku

puzzle

using

recursive

backtracking.

%sudoku_basic(X),

for

a9-by-9

array

X,

solves

the

Sudoku

puzzle

for

X

%without

providing

the

graphics

user

interface

from

sudoku.m

%[X,steps]

=sudoku_basic(X)

also

returns

the

number

of

steps.

%See

also

sudoku,

sudoku_all,

sudoku_assist,

sudoku_puzzle.

Thisfirstbitofcodechecksnargin,thenumber

ofinputarguments,andinitializes

thestep

counteronthefirstentry.

Anysubsequentrecursivecallswillhaveasecond

argument.

if

nargin

<2

steps=

0;

end

190

Chapter14

.Sudoku

Thesecomments

describetheprimary

variablesin

theprogram.

%C

is

the

array

of

candidate

values

for

each

cell.

%N

is

the

vector

of

the

number

of

candidates

for

each

cell.

%s

is

the

index

of

the

first

cell

with

the

fewest

candidates.

Theprogram

fillsin

anysingletons,

oneat

atime.

Thecandidatesarerecomputed

after

each

step.Thissectionof

code,

byitself,cansolvepuzzlesthatdonotrequire

backtracking.Such

puzzlescanbeclassified

as“easy”.

[C,N]=

candidates(X);

whileall(N>0)&

any(N==1)

s=

find(N==1,1);

X(s)=

C{s};

steps=

steps

+1;

[C,N]=

candidates(X);

end

Iffillingin

thesingletonsdoes

notsolvethepuzzle,wereach

thefollow

ingsection

ofcodethatim

plements

backtracking.Thebacktrackinggeneratesmanyim

possi-

ble

configurations.

Therecursionis

term

inatedbyencounteringapuzzle

withno

solution.

if

all(N>0)

Y=

X;

s=

find(N==min(N),1);

fort

=[C{s}]

%Iterate

over

the

candidates.

X=Y;

X(s)=

t;

%Insert

atentative

value.

steps=

steps

+1;

[X,steps]=

sudoku_basic(X,steps);

%Recursive

call.

ifall(X(:)

>0)

%Found

asolution.

break

end

end

end

Allof

thebookkeepingrequired

bybacktrackingis

handledbytherecursivecall

mechanism

inMatlabandtheunderlingoperatingsystem

.Thekey

internalfunctionforsudokuiscandidates.Hereis

thepream

ble.

function[C,N]=

candidates(X)

%C

=candidates(X)

is

a9-by-9

cell

array

of

vectors.

%C{i,j}

is

the

vector

of

allowable

values

for

X(i,j).

%N

is

arow

vector

of

the

number

of

candidates

for

each

cell.

%N(k)

=Inf

for

cells

that

already

have

values.

Page 101: Experiments With MatLab Moled 2011

191

Thefollow

ingstatementcreatesaninternalfunctionnamed

trithatcomputes

theindices

forblocks.

For

example,tri(1),tri(2)andtri(3)are

allequalto

1:3because

theblock

thatincludes

acellwithrow

orcolumnindex

equalto

1,2

or3hasrow

orcolumnindices

1:3.

tri=

@(k)

3*ceil(k/3-1)

+(1:3);

Hereis

thecore

ofcandidates.

C=

cell(9,9);

forj

=1:9

fori

=1:9

if

X(i,j)==0

z=

1:9;

z(nonzeros(X(i,:)))=

0;

z(nonzeros(X(:,j)))=

0;

z(nonzeros(X(tri(i),tri(j))))=

0;

C{i,j}=

nonzeros(z)’;

end

end

end

Foreach

empty

cell,thisfunctionstartswithz

=1:9andusesthenumeric

values

intheassociatedrow,columnandblock

tozero

elem

ents

inz.Thenonzerosthat

remain

are

thecandidates.

Forexample,consider

the(1,1)cellin

figure

20.We

start

with

z=

12

34

56

78

9

Thevalues

inthefirstrow

changezto

z=

10

00

56

78

9

Then

thefirstcolumnchanges

zto

z=

10

00

50

70

9

The(1,1)block

does

notmakeanyfurther

changes,so

thecandidatesforthis

cell

are

C{1,1}=

[1

57

9].

Thecandidatesfunctionconcludes

withthefollow

ingstatements.Thenum-

ber

ofcandidates,

N(i,j)forcell(i,j)is

thelength

ofC{i,j}.

Ifcell(i,j)

alreadyhasavalue,

then

X(i,j)is

nonzero,C{i,j}is

empty

andso

N(i,j)is

zero.ButwemaketheseN(i,j)infiniteto

distinguishthem

from

thecellsthat

signalanim

possible

puzzle.

N=

cellfun(@length,C);

N(X>0)=

Inf;

N=

N(:)’;

192

Chapter14

.Sudoku

Anex

ample,puzzle

number

one

Figure

14.12show

sthekey

stepsin

thesolutionof

ourLo-Shupuzzle.Theinitial

candidatesincludejust

onesingleton,thered5in

position(3,9).

Fivestep

swith

fivesingletonsallow

usto

fillin

thecellswithgreen

5’sand8’s.Wenow

consider

the

firstcellwithtw

ocandidates,

inposition(6,1).

Thefirststep

inthebacktracking

puts

atentative

6in

position(6,1).

Bluevalues

are

theinitialclues,cyanvalues

are

generatedbythebacktrackingan

dgreen

values

are

implied

bytheothers.

After

five

stepswereach

anim

possible

situationbecause

thereare

nocandidatesforposition

(6,2).

Try

again,witha7in

position(6,1).

Thispuzzleiseasily

completedbyfilling

insingletons.

Thetitleonthefinalsolutionsshow

sthatittook50step

s,including

theabortiveones

inthefirstbacktrack,to

reach

thesolution.

Referen

ces

[1]W

ikiped

ia’s

Mathem

atics

ofSudoku.

http://en.wikipedia.org/wiki/Mathematics_of_Sudoku

[2]GordonRoy

le,Minim

um

Sudoku.

http://mapleta.maths.uwa.edu.au/~gordon/sudokumin.php

[3]Nikoli.

http://www.nikoli.co.jp/en

[4]SudokuSquaresan

dChromaticPolynomials.

http://www.ams.org/notices/200706/tx070600708p.pdf

[5]Sudokuweb

site

modeled

after

Wikiped

ia.

http://www.sudopedia.org/wiki

[6]Ruud’s

Guide,

SudoCue.

http://www.sudocue.net/guide.php

Rec

ap

%%

Sudoku

Chapter

Recap

%This

is

an

executable

program

that

illustrates

the

statements

%introduced

in

the

Sudoku

Chapter

of

"Experiments

in

MATLAB".

%You

can

access

it

with

% %sudoku_recap

%edit

sudoku_recap

%publish

sudoku_recap

% %Related

EXM

programs

% %sudoku

%sudoku_all

%sudoku_assist

%sudoku_basic

%sudoku_puzzle

Page 102: Experiments With MatLab Moled 2011

193

%%Disclaimer

%Our

Sudoku

chapter

and

Sudoku

program

depend

heavily

%upon

recursion,

which

cannot

be

done

by

this

script.

%%Sudoku

puzzle

incorporating

the

Lo-Shu

magic

square.

X=

kron(eye(3),magic(3))

C=

full(sparse([9

84

37

62

1],[1:4

6:9],

[1

23

13

18

3]))

X=

X+

C

%Also

available

as

X=

sudoku_puzzle(1);

%%Transforms

of

aSudoku

puzzle

T=

X;

p=

randperm(9);

z=

find(X

>0);

T(z)=

p(X(z))

X’

rot90(X,-1)

flipud(X)

fliplr(X)

X([4:91:3],:)

X(:,[randperm(3)4:9])

%%Candidates

%C

=candidates(X)

is

acell

array

of

vectors.

%C{i,j}

is

the

set

of

allowable

values

for

X(i,j).

C=

cell(9,9);

tri=

@(k)

3*ceil(k/3-1)

+(1:3);

forj

=1:9

fori

=1:9

if

X(i,j)==0

z=

1:9;

z(nonzeros(X(i,:)))=

0;

z(nonzeros(X(:,j)))=

0;

z(nonzeros(X(tri(i),tri(j))))=

0;

C{i,j}=

nonzeros(z)’;

end

end

end

C

%%First

singleton

and

first

empty.

194

Chapter14

.Sudoku

%N

=number

of

candidates

in

each

cell.

%s

=first

cell

with

only

one

candidate.

%e

=first

cell

with

no

candidates.

N=

cellfun(@length,C)

s=

find(X==0

&N==1,1)

e=

find(X==0

&N==0,1)

%%

Sudoku

puzzles

helpsudoku_puzzle

forp

=1:16

sudoku_puzzle(p)

end

Exe

rcises

14.1

xkcd.Solvethebinary

Sudokupuzzle

byRandalMunroein

theWeb

comic

stripxkcdat

http://xkcd.com/74

14.2

Solve.

Use

sudokuto

solveapuzzle

from

anew

spaper,magazine,

orpuzzle

book

.Use

sudoku_assistto

solvethesamepuzzle

byhand.

14.3

sudoku

puzzle.Theexmprogram

sudoku_puzzlegenerates16

differentpuzzles.

Thecomments

intheprogram

describetheoriginsof

thepuzzles.

How

manysteps

are

required

bysudoku_basicto

solveeach

ofthepuzzles?

14.4

Byhand.Use

sudoku_assistto

solveou

rLo-Shubasedpuzzle

byhand.

X=

sudoku_puzzle(1);

sudoku_assist(X)

14.5

Modifypuzzle

#1.Thefollow

ingprogram

modifies

thelower

left

handcluein

ourLo-Shubasedpuzzle.W

hathappenswitheach

oftheresultingpuzzles?

X=

sudoku_puzzle(1);

fort

=[0

15

67]

X(9,1)=

t;

sudoku_all(X)

end

Page 103: Experiments With MatLab Moled 2011

195

14.6

Try

this.Try

touse

sudoku_assistto

solvethis

puzzle

byhand.

X=

sudoku_puzzle(1);

X(9,1)=

7;

sudoku_assist(X)

14.7

Puzzle

#3.How

manysolutionsdoes

sudoku_puzzle(3)have?

How

dothey

differ

from

each

other?

14.8

Puzzle

#13.How

manysolutionsdoes

sudoku_puzzle(13)have?

Inaddition

totheinitialclues,whatvalues

are

thesamein

allthesolutions?

14.9Allsolutions.

Whatarethedifferencesbetweensudoku_basicandsudoku_all?

14.10Combine.

Combinesudoku_allandsudoku_basicto

create

aprogram

that

returnsallpossible

solutionsandthenumber

ofstepsrequired

tofindeach

one.

Try

yourprogram

onsudoku_puzzle(13).W

hatis

theaveragenumber

ofsteps

required

?Hints:ifSisacellarray

whereeach

cellcontainsonenumeric

value,

then

s=

[S{:}]createsthecorrespondingvector.

And,helpmean.

14.11Searchstrategy

Insudoku_basic,thestatement

s=

find(N==min(N),1);

determines

thesearchstrategy.

Whathappenswhen

youchangethis

to

s=

find(N==min(N),’last’);

or

s=

find(X==0,’first’);

14.12Patterns.

Addsomehumanpuzzle

solvingtechniques

tosudoku.m.Thiswill

complicate

theprogram

andrequiremore

timeforeach

step,butshould

result

infewer

totalsteps.

14.13sudoku

alpha.In

sudoku.m,changeint2str(d)to

char(’A’+d-1)so

that

thedisplayusestheletters’A

’through’I’insteadofthedigits1through9.See

figure

14.13.Does

this

makeit

easier

orharder

tosolvepuzzlesbyhand.

14.14sudoku16.Modifysudoku.mto

solve16-by-16puzzleswith4-by-4

blocks.

196

Chapter14

.Sudoku

0

8 3 4 2

5

7 9

2

6

9

5 6

7 5

7 9

6

9

1

1 5 9

4 7 4 6

8

6

7 8

4 7

2 3

6

7 8

6 7 2 31 4 8 9

5

8

4 5

9

4 8 9

5

8

2

5

7 9

2

6

9

1 8 3 4 2

5

7 9

6

9

5 6

7

2

4 7 2

4 6

3

6

7 8 1 5 9

2

4 7 4 6

8

6

7 8

4 5

9

4 9

5

8 6 7 2 3

1 4 8 9

5

8

2

5

7 9

2

6

9

5 6

7 2

5

7 9

2

6

9

1 8 3 4

2

4 7

8

6

7 2

4 7 2

4 6

3

6

7

1 5 9

31 4 9

5

4 5

9

4 8 9

5

8 6 7 2

6

8 3 4 2

7 9

2

6

9

6

7 5

7 9

6

9

1

1 5 9

4 7 4 6

8

6

7 8

4 7

2 3

6

7

6 7 2 31 4 9

5

4 9

4 9

8

2

5

7 9

2

6

9

1 8 3 4 2

7 9

6

9

6

7

2

4 7 2

4 6

3

6

7

1 5 9 2

4 7 4 6

8

6

7

4 9

4 9

8 6 7 2 31 4 9

5

2

7 9

2

6

9

6

7 2

5

7 9

2

6

9

1 8 3 4

2

4 7

8

6

7 2

4 7 2

4 6

3

6

7

1 5 9

31 4 9

5

4 9

4 8 9

8 6 7 2

7

8 3 4 6 1

1 5 9 2

6 7 2 3 5 8

1 8 3 4

1 5 9

8 6 7 2 3 5

1 8 3 4

8 1 5 9

3 5 8 6 7 2

10

8 3 4 7 2 6

5 9 1

1 5 9

4 4 8

4 7

2 3

6

7

6 7 2 31 4 9

5

4 4

8

2

5

7 9

2

6

9

1 8 3 4 2

7 9

6

6

7

2

4 7 2

4 6

3

6

7

1 5 9 2

4 7 4 6

8

6

7

4 9

4 9

8 6 7 2 31 4

5

2

7 9

2

6

9

6

7 2

5

9

6

9

1 8 3 4

2

4 7

8

6

7 2

4 4 6

3

7

1 5 9

31 4 9

5

4 9

4 9

8 6 7 2

11

8 3 4 7 1

1 5 9 2

6 7 2 3 5 8

1 8 3 4

1 5 9

8 6 7 2 3 5

1 8 3 4

8 1 5 9

3 5 8 6 7 2

50

8 3 4 2 9 7 5 6 1

1 5 9 4 8 6 7 2 3

6 7 2 3 1 5 9 4 8

5 6 1 8 3 4 2 9 7

7 2 3 1 5 9 4 8 6

9 4 8 6 7 2 3 1 5

2 9 7 5 6 1 8 3 4

4 8 6 7 2 3 1 5 9

3 1 5 9 4 8 6 7 2

Figure

14.12.Thekeystepsin

thesolutionofourLo-Shupuzzle.

Page 104: Experiments With MatLab Moled 2011

197

H C D A

A E I B

F G B C

A H C D

A E I

F G B C

A H C D

H A E I

C F G B

Figure

14.13.Use

theletters’A

’through

’I’insteadofthedigits1through

9.

198

Chapter14

.Sudoku

Page 105: Experiments With MatLab Moled 2011

Chapter15

OrdinaryDifferen

tial

Equations

Mathem

aticalmodelsin

manydifferen

tfields.

System

sofdifferentialequationsform

thebasisofmathem

aticalmodelsin

awiderangeof

fields–from

engineeringan

dphysicalsciencesto

finance

andbiological

sciences.

Differentialequationsare

relationsbetweenunknow

nfunctionsan

dtheir

derivatives.Computingnumericalsolutionsto

differentialequationsis

oneofthe

most

importanttasksin

technicalcomputing,andon

eofthestrengthsofMatlab.

Ifyou

havestudiedcalculus,youhavelearned

akindofmechanicalprocess

for

differentiatingfunctionsrepresentedbyform

ulasinvo

lvingpow

ers,

trig

functions,

andthelike.

Youknow

thatthederivativeofx3is3x2andyoumay

remem

ber

that

thederivative

oftanxis

1+

tan2x.Thatkindof

differentiationis

importantand

useful,butnotou

rprimary

focushere.

Weareinterested

insituationswherethe

functionsarenotknow

nandcannotberepresentedbysimple

form

ulas.

Wewill

compute

numericalapproxim

ationsto

thevalues

ofafunctionatenoughpoints

toprintatable

orplotagraph.

Imagineyou

are

travelingonamountain

road.Youraltitudevaries

asyou

travel.Thealtitudecanberegarded

asafunctionoftime,

orasafunctionoflongi-

tudeandlatitude,

orasafunctionofthedistance

youhavetraveled.Let’sconsider

thelatter.Let

xden

ote

thedistance

traveled

andy=

y(x)den

ote

thealtitude.

Ifyouhappen

tobecarryinganaltimeter

withyou,oryouhaveadeluxeGPSsystem

,youcancollectenoughvalues

toplotagraphofaltitudeversusdistance,likethe

firstplotin

figure

15.1.

Suppose

youseeasignsayingthatyouare

ona6%

uphillgrade.

Forsome

Copyright

c ©2011CleveMoler

Matlab

R ©is

aregisteredtradem

ark

ofMath

Works,

Inc.

TM

October

4,2011

199

200

Chapter15

.OrdinaryDifferential

Equations

6000

6010

6020

6030

6040

6050

6060

6070

950

1000

1050

1100

1150

altitude

6000

6010

6020

6030

6040

6050

6060

6070

−20

−1001020

slope

dist

ance

Figure

15.1.Altitudealongamountain

road,andderivative

ofthatalti-

tude.

Thederivative

iszero

atthelocalmaximaandminim

aofthealtitude.

valueofxnearthesign,andforh=

100,you

willhave

y(x

+h)−y(x)

h=

.06

Thequotientontheleft

istheslope

oftheroadbetweenxandx+h.

Now

imaginethatyou

hadsignseveryfew

meterstellingyouthegradeat

those

points.Thesesignswould

provideap

proxim

ate

values

oftherate

ofchange

ofaltitudewith

respectto

distance

traveled

,This

isthederivative

dy/dx.

You

could

plotagraphof

dy/dx,likethesecondplotin

figure

15.1,even

thoughyou

do

nothaveclosed-form

form

ulasforeither

thealtitudeoritsderivative.This

ishow

Matlabsolves

differentialequations.

Note

thatthederivativeispositivewherethe

altitudeisincreasing,negativewhereitisdecreasing,zero

atthelocalmaxim

aan

dminim

a,an

dnearzero

ontheflatstretches.

Hereis

asimple

example

illustratingthenumericalsolutionofasystem

ofdifferentialequations.

Figure

15.2

isascreen

shotfrom

Spacewar,

theworld’s

firstvideo

game.

Spacewarwas

written

bySteve“Slug”Russellan

dsomeofhis

buddiesatMIT

in1962.It

ranon

thePDP-1,DigitalEquipmentCorporation’s

firstcomputer.

Twospace

ships,controlled

byplayers

usingsw

itches

onthePDP-1

console,shoot

space

torpedoes

ateach

other.

Thespace

shipsan

dthetorpedoes

orbit

around

acentralstar.

Russell’s

program

needed

tocompute

circularan

dellipticalorbits,likethepath

ofthetorpedo

inthescreen

shot.

Atthetime,

therewasnoMatlab.Programswerewritten

interm

sof

individualmachineinstructions.

Floating-pointarithmetic

wasso

slow

thatit

was

desirable

toavoidevaluationoftrig

functionsin

theorbit

calculations.

Theorbit-generatingprogram

looked

somethinglikethis.

x=

0

y=

32768

Page 106: Experiments With MatLab Moled 2011

201

Figure

15.2.

Spacewar,

theworld’s

firstvideo

game.

Thegravitational

pullofthecentralstarcausesthetorpedoto

move

inanellipticalorbit.

L:

plot

xy

loady

shiftright2

addx

storein

x

changesign

shiftright2

addy

storein

y

go

to

L

Whatdoes

this

program

do?

Thereare

notrig

functions,

nosquare

roots,no

multiplicationsordivisions.

Everythingis

donewith

shifts

and

additions.

The

initialvalueofy,whichis

215,serves

asanoverallscale

factor.

Allthearithmetic

involves

asingle

integer

register.

The“shiftright2”commandtakes

thecontents

ofthis

register,

divides

itby22

=4,

anddiscardsan

yremainder.

IfSpacewarorbit

generatorwerewritten

today

inMatlab,it

would

look

somethingthefollow

ing.Weare

nolonger

limited

tointeger

values,so

wehave

changed

thescale

factorfrom

215to

1.

x=

0;

y=

1;

h=

1/4;

n=

2*pi/h;

plot(x,y,’.’)

fork

=1:n

202

Chapter15

.OrdinaryDifferential

Equations

−1−0

.50

0.5

1

−1

−0.8

−0.6

−0.4

−0.20

0.2

0.4

0.6

0.81

Figure

15.3.The25bluepoints

are

generatedby

theSpacewarorbitgen-

eratorwithastep

size

of1/4.The201greenpoints

are

generatedwithastep

size

of1/32. x

=x

+h*y;

y=

y-

h*x;

plot(x,y,’.’)

end

Theou

tputproducedbythis

program

withh

=1/4andn

=25is

show

nbythe

bluedots

infigure

15.3.Theblueorbit

isactuallyanellipse

thatdeviatesfrom

anexact

circle

byab

out7%.Theoutputproducedwithh=

1/32andn=

201is

show

nbythegreen

dots.Thegreen

orbit

isan

other

ellipse

thatdeviatesfrom

anexact

circle

byless

than1%.

Thinkofxandyasfunctionsof

time,

t.Weare

computingx(t)andy(t)at

discretevalues

oft,increm

entedbythestep

size

h.Thevalues

ofxandyattime

t+

hare

computedfrom

thevalues

attimetby

x(t+h)=

x(t)+

hy(t)

y(t+h)=

y(t)−hx(t+h)

This

canberewritten

as

x(t+

h)−x(t)

h=

y(t)

y(t+h)−y(t)

h=

−x(t+

h)

You

haveprobably

noticedthattherighthandsideofthispairofequationsinvo

lves

Page 107: Experiments With MatLab Moled 2011

203

twodifferentvalues

ofthetimevariable,tandt+

h.Thatfact

turnsoutto

be

important,butlet’signore

itfornow

.Lookattheleft

handsides

ofthelast

pair

ofequations.

Thequotients

are

approxim

ationsto

thederivatives

ofx(t)andy(t).

Weare

look

ingfortw

ofunctions

withtheproperty

thatthederivativeofthefirstfunctionisequalto

thesecondand

thederivativeof

thesecondfunctionis

equalto

thenegativeof

thefirst.

Ineff

ect,

theSpacewarorbit

generatoris

usingasimple

numericalmethod

involvingastep

size

hto

compute

anapproxim

ate

solutionto

thesystem

ofdiffer-

entialequations

x=

y

y=

−xThedotover

xandydenotesdifferentiationwithrespectto

t.

x=

dx dt

Theinitialvalues

ofxandyprovidetheinitialconditions

x(0)=

0

y(0)=

1

Theexact

solutionto

thesystem

is

x(t)=

sint

y(t)=

cost

Toseewhy,

recallthetrig

identities

sin(t+h)=

sintcosh+costsinh

cos(t+h)=

costcosh−sintsinh

For

smallvalues

ofh,

sinh≈

h,

cosh≈

1

Consequently

sin(t+h)−sint

h≈

cost,

cos(t+h)−cost

h≈

−sint,

Ifyouplotx(t)an

dy(t)as

functionsof

t,youget

thefamiliarplots

ofsine

andcosine.

Butifyoumakeaphase

planeplot,

thatis

y(t)versusx(t),

yougeta

circle

ofradius1.

ItturnsoutthatthesolutioncomputedbytheSpacewarorbitgeneratorwith

afixed

step

size

his

anellipse,notan

exact

circle.Decreasinghandtakingmore

204

Chapter15

.OrdinaryDifferential

Equations

stepsgeneratesabetterap

proxim

ationto

acircle.Actually,

thefact

thatx(t+

h)

isusedinsteadof

x(t)in

thesecondhalfofthestep

meansthatthemethodis

not

quiteas

simple

asitmightseem

.Thissubtlechangeisresponsible

forthefact

that

themethodgeneratesellipsesinsteadof

spirals.Oneoftheexercisesasksyou

toverifythis

fact

experim

entally.

Mathem

aticalmodelsinvolvingsystem

sofordinary

differentialequationshave

oneindepen

den

tvariable

andon

eormore

depen

den

tvariables.

Theindep

endent

variable

isusuallytimeandis

den

otedbyt.

Inthis

book,wewillassem

ble

allthe

dep

endentvariablesinto

asinglevectory.Thisissometim

esreferred

toas

thestate

ofthesystem

.Thestate

canincludequantities

likeposition,velocity,temperature,

concentration,andprice.

InMatlab

asystem

ofodes

takes

theform

y=

F(t,y)

Thefunction

Falwaystakes

twoarguments,thescalarindep

endentvariable,t,

andthevectorofdep

endentvariables,

y.A

program

thatevaluatesF(t,y)hou

ldcompute

thederivatives

ofallthestate

variablesandreturn

them

inanother

vector.

Inourcircle

generatingexample,thestate

issimply

thecoordinatesof

the

point.

This

requires

achangeofnotation.Wehavebeenusingx(t)andy(t)to

denote

position,now

weare

goingto

use

y 1(t)andy 2(t).

ThefunctionF

defines

thevelocity.

y(t)=

( y 1(t)

y 2(t)

)

=

(y 2(t)

−y1(t)

)

Matlabhasseveralfunctionsthatcompute

numericalapproxim

ationsto

solu-

tionsof

system

sofordinary

differentialequations.

Thesuiteof

odesolversincludes

ode23,ode45,ode113,ode23s,ode15s,ode23t,an

dode23tb.Thedigitsin

the

names

referto

theorder

oftheunderlyingalgorithms.

Theorder

isrelatedto

the

complexityan

daccuracy

ofthemethod.Allof

thefunctionsau

tomaticallydeter-

minethestep

size

required

toob

tain

aprescribed

accuracy.Higher

order

methods

requiremore

work

per

step,butcantakelarger

steps.

Forexampleode23compares

asecondorder

methodwithathirdorder

methodto

estimate

thestep

size,while

ode45comparesafourthorder

methodwithafifthorder

method.

Theletter

“s”in

thenameofsomeoftheodefunctionsindicatesastiff

solver.

Thesemethodssolveamatrix

equationat

each

step,so

they

domore

workper

step

thanthenonstiff

methods.

Butthey

cantakemuch

larger

stepsforproblemswhere

numericalstabilitylimitsthestep

size,so

they

canbemore

efficientoverall.

You

can

use

ode23

formost

oftheexercisesin

this

book,butif

you

are

interested

intheseeinghow

theother

methodsbehave,

please

experim

ent.

Allof

thefunctionsin

theodesuitetakeatleast

threeinputarguments.

•F,thefunctiondefiningthedifferentialequations,

•tspan,thevectorspecifyingtheintegrationinterval,

Page 108: Experiments With MatLab Moled 2011

205

01

23

45

6−1

−0.8

−0.6

−0.4

−0.20

0.2

0.4

0.6

0.81

Figure

15.4.Graphsofsineandcosinegeneratedby

ode23.

•y0,thevectorofinitialconditions.

Thereareseveralwaysto

write

thefunctiondescribingthedifferentialequa-

tion.Anticipatingmore

complicatedfunctions,

wecancreate

aMatlabprogram

forourcircle

generatorthatextractsthetw

odep

endentvariablesfrom

thestate

vector.

Savethis

inafile

named

mycircle.m.

functionydot=

mycircle(t,y)

ydot=

[y(2);

-y(1)];

Notice

thatthisfunctionhastw

oinputarguments,tandy,even

thoughtheoutput

inthis

example

does

notdep

endupont.

Withthis

functiondefi

nitionstoredin

mycircle.m,thefollow

ingcodecalls

ode23to

compute

thesolutionover

theinterval0≤

t≤

2π,startingwithx(0)=

0andy(0)=

1.

tspan=

[0

2*pi];

y0

=[0;

1];

ode23(@mycircle,tspan,y0)

Withnooutputarguments,theodesolversautomaticallyplotthesolutions.

Figure

15.4

istheresult

forourexample.

Thesm

all

circlesin

theplotare

not

equallyspaced.They

show

thepoints

chosenbythestep

size

algorithm.

Toproduce

thephase

plotplotshow

nin

figure

15.5,capture

theoutputand

plotityou

rself.

tspan=

[0

2*pi];

y0

=[0;

1];

[t,y]=

ode23(@mycircle,tspan,y0)

plot(y(:,1),y(:,2)’-o’)

206

Chapter15

.OrdinaryDifferential

Equations

−1−0

.50

0.5

1

−1

−0.8

−0.6

−0.4

−0.20

0.2

0.4

0.6

0.81

Figure

15.5.Graphofacircle

generatedby

ode23.

axis([-1.11.1-1.11.1])

axissquare

Thecircle

generatorexample

isso

simple

thatwecanbypass

thecreationof

thefunctionfile

mycircle.mandwrite

thefunctionin

oneline.

acircle=

@(t,y)

[y(2);

-y(1)]

Theexpressioncreatedon

therightbythe“@

”symbol

isknow

nasananonym

ous

functionbecause

itdoes

nothaveanameuntilitisassigned

toacircle.Since

the

“@”signis

included

inthedefinitionofacircle,youdon’t

needit

when

you

call

anodesolver.

Once

acirclehasbeendefined,thestatement

ode23(acircle,tspan,y0)

automaticallyproducesfigure

15.4.And,thestatement

[t,y]=

ode23(acircle,tspan,y0)

capturestheou

tputso

you

canprocess

ityou

rself.

Manyadditionaloptionsfortheodesolverscanbesetvia

thefunctionodeset.

Forexample

opts=

odeset(’outputfcn’,@odephas2)

ode23(acircle,tspan,y0,opts)

axissquare

axis([-1.11.1-1.11.1])

Page 109: Experiments With MatLab Moled 2011

207

willalsoproduce

figure

15.5.

Use

thecommand

docode23

toseemore

detailsabouttheMatlab

suiteofodesolvers.

Consult

theODE

chapterin

ourcompanionbook,NumericalComputingwithMATLAB,formore

of

themathem

aticalbackgroundoftheodealgorithms,

andforode23tx,atextbook

version

ofode23.

Hereisaverysimpleexamplethatillustrateshow

thefunctionsin

theodesuite

work.Wecallit

“ode1”because

itusesonly

oneelem

entary

firstorder

algorithm,

know

nas

Euler’smethod.Thefunctiondoes

notem

ploytw

odifferentalgorithms

toestimate

theerroranddeterminethestep

size.Thestep

size

his

obtained

by

dividingtheintegrationinterval

into

200equalsizedpieces.

This

wou

ldap

pearto

beappropriate

ifwejust

wantto

plotthesolutiononacomputerscreen

witha

typicalresolution,butwehavenoidea

oftheactualaccuracy

oftheresult.

function[t,y]=

ode1(F,tspan,y0)

%ODE1

World’s

simplest

ODE

solver.

%ODE1(F,[t0,tfinal],y0)

uses

Euler’s

method

to

solve

%dy/dt=

F(t,y)

%with

y(t0)

=y0

on

the

interval

t0

<=

t<=

tfinal.

t0

=tspan(1);

tfinal=

tspan(end);

h=

(tfinal

-t0)/200;

y=

y0;

fort

=t0:h:tfinal

ydot=

F(t,y);

y=

y+

h*ydot;

end How

ever,even

with200stepsthiselem

entary

firstorder

methoddoes

nothave

satisfactory

accuracy.Theoutputfrom

[t,y]]=

ode1(acircle,tspan,y0)

is

t=

6.283185307179587

y=

0.032392920185564

1.103746317465277

Wecanseethatthefinalvalueoftis

2*pi,butthefinalvalueofyhasmissed

returningto

itsstartingvaluebymore

than10

percent.

Manymore

smaller

step

swou

ldberequired

toget

graphicalaccuracy.

208

Chapter15

.OrdinaryDifferential

Equations

Rec

ap

%%

Ordinary

Differential

Equations

Chapter

Recap

%This

is

an

executable

program

that

illustrates

the

statements

%introduced

in

the

Ordinary

Differential

Equations

Chapter

%of

"Experiments

in

MATLAB".

%You

can

access

it

with

% %odes_recap

%edit

odes_recap

%publish

odes_recap

% %Related

EXM

programs

% %ode1

%%

Spacewar

Orbit

Generator.

x=

0;

y=

1;

h=

1/4;

n=

2*pi/h;

plot(x,y,’.’)

holdon

fork

=1:n

x=

x+

h*y;

y=

y-

h*x;

plot(x,y,’.’)

end

holdoff

axissquare

axis([-1.11.1-1.11.1])

%%

An

Anonymous

Function.

acircle=

@(t,y)

[y(2);

-y(1)];

%%

ODE23

Automatic

Plotting.

figure

tspan=

[0

2*pi];

y0

=[0;

1];

ode23(acircle,tspan,y0)

%%

Phase

Plot.

figure

tspan=

[0

2*pi];

y0

=[0;

1];

[t,y]=

ode23(acircle,tspan,y0)

Page 110: Experiments With MatLab Moled 2011

209

plot(y(:,1),y(:,2),’-o’)

axissquare

axis([-1.11.1-1.11.1])

%%ODE23

Automatic

Phase

Plot.

opts=

odeset(’outputfcn’,@odephas2)

ode23(acircle,tspan,y0,opts)

axissquare

axis([-1.11.1-1.11.1])

%%ODE1

implements

Euler’s

method.

%ODE1

illustrates

the

structure

of

the

MATLAB

ODE

solvers,

%but

it

is

low

order

and

employs

acoarse

step

size.

%So,

even

though

the

exact

solution

is

periodic,

the

final

value

%returned

by

ODE1

misses

the

initial

value

by

asubstantial

amount.

typeode1

[t,y]=

ode1(acircle,tspan,y0)

err=

y-

y0

Exe

rcises

15.1

Walkingto

class.You

leavehome(oryourdorm

room)attheusualtimein

the

morningan

dwalk

towardyou

rfirstclass.Abouthalfway

toclass,yourealize

that

youhaveforgotten

yourhomew

ork.You

runback

home,

getyou

rhomew

ork,run

toclass,andarriveatyou

rusualtime.

Sketch

aroughgraphbyhandshow

ingyou

rdistance

from

homeasafunctionoftime.

Makeasecondsketch

ofyou

rvelocity

asafunctionoftime.

Youdonothaveto

assumethatyou

rwalkingan

drunning

velocities

are

constant,orthatyourreversals

ofdirectionare

instantaneous.

15.2

Divided

differen

ces.

Create

yourow

ngraphic

likeou

rfigure

15.1.Makeup

yourow

ndata,xandy,fordistance

andaltitude.

Youcanuse

subplot(2,1,1)

and

subplot(2,1,2)

toplace

twoplots

inon

efigure

window

.Thestatement

d=

diff(y)./diff(x)

computesthedivided

differen

ceapproxim

ationto

thederivativeforuse

inthesecond

subplot.

Thelength

ofthevectordis

oneless

thanthelength

ofxandy,so

you

canad

donemore

valueattheendwith

210

Chapter15

.OrdinaryDifferential

Equations

d(end+1)=

d(end)

For

more

inform

ationab

outdiffandsubplot,use

helpdiff

helpsubplot

15.3

Orbitgenerator.

Hereisacomplete

Matlabprogram

fortheorbitgenerator,

includingappropriate

settingofthegraphicsparameters.

Investigate

thebehav

ior

ofthis

program

forvariousvalues

ofthestep

size

h.

axis(1.2*[-11

-1

1])

axissquare

boxon

holdon

x=

0;

y=

1;

h=

...

n=

2*pi/h;

plot(x,y,’.’)

fork

=1:n

x=

x+

h*y;

y=

y-

h*x;

plot(x,y,’.’)

end

15.4

Modified

orbit

generator.

Hereis

aMatlab

program

thatmakes

asimpler

approxim

ationfortheorbit

generator.

Whatdoes

itdo?Investigate

thebehav

ior

forvariousvalues

ofthestep

size

h.

axis(1.5*[-11

-1

1])

axissquare

boxon

holdon

x=

0;

y=

1;

h=

1/32;

n=

6*pi/h;

plot(x,y,’.’)

fork

=1:n

savex=

x;

x=

x+

h*y

y=

y-

h*savex;

plot(x,y,’.’)

end

Page 111: Experiments With MatLab Moled 2011

211

15.5

Linearsystem

Write

thesystem

ofdifferentialequations

y 1=

y 2

y 2=

−y1

inmatrix-vectorform

,

y=

Ay

whereyis

avector-valued

functionoftime,

y(t)=

( y 1(t)

y 2(t)

)

andA

isaconstant2-by-2

matrix.Use

ourode1aswellasode23to

experim

ent

withthenumericalsolutionofthesystem

inthis

form

.

15.6

Example

from

ode23.Thefirstexample

inthedocumentationforode23is

y 1=

y 2y 3

y 2=

−y1y 3

y 3=

−0.51y 1

y 2

withinitialconditions

y 1(0)=

0

y 2(0)=

1

y 3(0)=

1

Compute

thesolutionto

this

system

ontheinterval0≤

t≤

12.Reproduce

the

graphincluded

inthedocumentationprovided

bythecommand

docode23

15.7

Acubicsystem

.Makeaphase

planeplotofthesolutionto

theodesystem

y 1=

y3 2

y 2=

−y3 1

withinitialconditions

y 1(0)=

0

y 2(0)=

1

ontheinterval

0≤

t≤

7.4163

Whatis

specialaboutthefinalvalue,

t=

7.4163?

212

Chapter15

.OrdinaryDifferential

Equations

15.8

Aquinticsystem

.Makeaphase

planeplotof

thesolutionto

theodesystem

y 1=

y5 2

y 2=

−y5 1

withinitialconditions

y 1(0)=

0

y 2(0)=

1

onaninterval

0≤

t≤

T

whereT

isthevaluebetween7and8determined

bytheperiodicitycondition

y 1(T

)=

0

y 2(T

)=

1

15.9

Aquadraticsystem

.W

hathappensto

solutionsof

y 1=

y2 2

y 2=

−y2 1

Whydosolutionsof

y 1=

yp 2

y 2=

−yp 1

havesuch

differentbehav

iorifpis

oddoreven

?

Page 112: Experiments With MatLab Moled 2011

Chapter16

Predator-PreyModel

Modelsofpopulationgrowth.

Thesimplest

model

forthegrow

th,ordecay,ofapopulationsaysthatthe

growth

rate,or

thedecay

rate,is

proportionalto

thesize

ofthepop

ulationitself.

Increasingordecreasingthesize

ofthepopulationresultsin

aproportionalincrease

ordecrease

inthenumber

ofbirthsanddeaths.

Mathem

atically,

this

isdescribed

bythedifferentialequation

y=

ky

Theproportionality

constantkrelatesthesize

ofthepopulation,y(t),

toitsrate

ofgrowth,y(t).

Ifk

ispositive,

thepop

ulation

increases;

ifk

isnegative,

the

populationdecreases.

Asweknow

,thesolutionto

thisequationisafunctiony(t)thatisproportional

totheexponentialfunction

y(t)=

ηek

t

whereη=

y(0).

Thissimplemodelisap

propriate

intheinitialstages

ofgrowth

when

thereare

norestrictionsorconstraints

onthepopulation.Asm

allsampleofbacteria

inalarge

Petridish,forexample.Butin

more

realistic

situationsthereare

limitsto

grow

th,

such

asfinitespace

orfoodsupply.A

more

realistic

model

saysthatthepopulation

competes

withitself.Asthepopulationincreases,itsgrow

thrate

decreaseslinearly.

Thedifferentialequationis

sometim

escalled

thelogistic

equation.

y=

k(1

−y μ)y

Copyright

c ©2011CleveMoler

Matlab

R ©is

aregisteredtradem

ark

ofMath

Works,

Inc.

TM

October

4,2011

213

214

Chapter16

.Predator-PreyModel

01

23

45

67

80246810121416182022

Figure

16.1.Exponen

tialgrowth

andlogistic

growth.

Thenew

parameter

μis

thecarryingcapacity.Asy(t)ap

proaches

μthegrowth

rate

approaches

zero

andthegrow

thultim

ately

stops.

Itturnsoutthatthesolution

is

y(t)=

μηek

t

ηek

t+

μ−

η

You

caneasily

verifyforyourselfthatas

tapproaches

zero,y(t)ap

proaches

ηand

thatastapproaches

infinity,

y(t)ap

proaches

μ.If

youknow

calculus,

then

with

quiteabitmore

effort,youcanverifythaty(t)actuallysatisfies

thelogisticequation.

Figure

16.1

show

sthetw

osolutionswhen

both

ηandkare

equalto

one.

The

expon

entialfunction

y(t)=

et

gives

therapidly

grow

inggreen

curve.

Withcarryingcapacity

μ=

20,thelogistic

function

y(t)=

20et

et+19

gives

themore

slow

lygrowingbluecurve.

Both

curves

havethesameinitialvalue

andinitialslope.

Theexponentialfunctiongrowsexponentially,

whilethelogistic

functionapproaches,butnever

exceeds,

itscarryingcapacity.

Figure

16.1

wasgeneratedwiththefollow

ingcode.

k=

1

eta=

1

mu

=20

t=

0:1/32:8;

Page 113: Experiments With MatLab Moled 2011

215

y=

mu*eta*exp(k*t)./(eta*exp(k*t)

+mu

-eta);

plot(t,[y;exp(t)])

axis([08

022])

Ifyoudon’t

havetheform

ula

forthesolutionto

thelogisticequationhandy,

you

cancompute

anumericalsolutionwithode45,oneoftheMatlab

ordinary

differentialequationsolvers.

Try

runningthefollow

ingcode.

Itwillautomatically

produce

aplotsomethinglikethebluecurvein

figure

16.1.

k=

1

eta=

1

mu

=20

ydot=

@(t,y)

k*(1-y/mu)*y

ode45(ydot,[08],eta)

The@signand@(t,y)specifythatyou

aredefiningafunctionoftandy.Thet

isnecessary

even

thoughit

doesn’t

explicitlyappearin

this

particulardifferential

equation.

Thelogisticequation

and

itssolution

occurin

many

differentfields.

The

logisticfunctionis

alsoknow

nasthesigm

oid

functionanditsgraphis

know

nas

theS-curve.

Populationsdonotlivein

isolation.Everybodyhasafew

enem

ieshereand

there.

TheLotka-Volterra

predator-preymodel

isthesimplest

descriptionofcom-

petitionbetweentw

ospecies.

Thinkofrabbitsandfoxes,orzebrasandlions,

orlittle

fish

andbig

fish.

Theidea

isthat,ifleft

tothem

selves

withaninfinitefoodsupply,therabbits

orzebraswould

livehappilyandexperience

exponentialpop

ulationgrow

th.Onthe

other

hand,ifthefoxes

orlionswereleft

withnopreyto

eat,they

wou

lddie

faster

thanthey

could

reproduce,andwould

experience

expon

entialpopulationdecline.

Thepredator-preymodel

isapairofdifferentialequationsinvolvingapairof

competingpopulations,

y 1(t)andy 2(t).

Thegrow

thrate

fory 1

isalinearfunction

ofy 2

andviceversa.

y 1=

(1−

y 2 μ2)y

1

y 2=

−(1−

y 1 μ1)y

2

Weare

usingnotationy 1(t)an

dy 2(t)insteadof,say,

r(t)

forrabbitsandf(t)for

foxes,because

ourMatlabprogram

usesatw

o-componentvectory.

Theextraminussignin

thesecondequationdistinguishes

thepredators

from

theprey.

Notethatify 1

ever

becomes

zero,then

y 2=

−y2

andthepredators

are

introuble.Butify 2

ever

becomes

zero,then

y 1=

y 1

andthepreypopulationgrow

sexponentially.

216

Chapter16

.Predator-PreyModel

Wehaveaform

ula

forthesolutionofthesinglespecieslogisticmodel.How

ever

itis

notpossible

toexpress

thesolutionto

this

predator-preymodel

interm

sof

expon

ential,trigonmetric,

oran

yother

elem

entary

functions.

Itis

necessary,but

easy,to

compute

numericalsolutions.

05

1015

200

100

200

300

400

500

600

Figure

16.2.A

typicalsolutionofthepredator-preyequations.

Therearefourparameters,

thetw

oconstants

μ1andμ2,andthetw

oinitial

conditions,

η 1=

y 1(0)

η 2=

y 2(0)

Ifwehappen

tostart

withη 1

=μ1andη 2

=μ2,then

both

y 1andy 2

are

zero

and

thepopulationsremain

constantattheirinitialvalues.In

other

words,

thepoint

(μ1,μ

2)isanequilibrium

point.

Theorigin,(0,0)isanother

equilibrium

point,but

notaveryinterestingone.

Thefollow

ingcodeusesode45to

automaticallyplotthetypicalsolutionshow

nin

figure

16.2.

mu

=[300

200]’

eta=

[400

100]’

signs=

[1

-1]’

pred_prey_ode=

@(t,y)

signs.*(1-flipud(y./mu)).*y

period=

6.5357

ode45(pred_prey_ode,[03*period],eta)

Page 114: Experiments With MatLab Moled 2011

217

Therearetw

otrickypartsofthis

code.

Matlab

vectoroperationsare

usedto

defi

nepred_prey_ode,thedifferentialequationsin

oneline.

And,thecalculation

thatgeneratesfigure

16.3

provides

thevalueassigned

toperiod.Thisvaluespecifies

avalueoftwhen

thepopulationsreturn

totheirinitialvalues

given

byeta.The

codeintegratesover

threeofthesetimeintervals,andso

attheendweget

back

towherewestarted.

Thecirclessuperim

posedontheplots

infigure

16.2

show

thepoints

where

ode45computesthesolution.

Theplots

looksomethingliketrig

functions,

but

they’renot.

Notice

thatthecurves

neartheminim

aarebroader,andrequiremore

stepsto

compute,then

thecurves

nearthemaxim

a.Theplotof

sintwou

ldlook

thesameat

thetopas

thebottom.

010

020

030

040

050

060

070

080

00

200

400

prey

predator

Dra

g ei

ther

dot

06.

5357

13.0

713

0

200

400

600

800

time

prey

pred

ator

perio

d Figure

16.3.Thepredpreyexperimen

t.

OurMatlabprogram

exm/predpreyshow

sareddotattheequilibrium

point,

(μ1,μ

2),

andablue-green

dotattheinitialpoint,

(η1,η

2).

When

you

drageither

dotwiththemouse,thesolutionisrecomputingbyode45andplotted.Figure

16.3

show

sthattw

oplots

areproduced—

aphase

planeplotofy 2(t)versusy 1(t)an

datimeseries

plotofy 1(t)an

dy 2(t)versust.

Figures16.2

and16.3

havethesame

parameters,an

dconsequentlyshow

thesamesolution,butwithdifferentscalingof

218

Chapter16

.Predator-PreyModel

theaxes.

Theremarkab

leproperty

oftheLotka-Volterra

model

isthatthesolutionsare

alwaysperiodic.Thepopulationsalway

sreturn

totheirinitialvalues

andrepeat

thecycle.

Thisproperty

isnotobviousandnoteasy

toprove.It

israre

fornonlinear

modelsto

haveperiodic

solutions.

Thediffi

cultaspectofcomputingthesolutionto

thepredator-preyequations

isdeterminingthelength

oftheperiod.Ourpredpreyprogram

usesafeature

ofthe

MatlabODE

solverscalled

“eventhandling”to

compute

thelength

ofaperiod.

Iftheinitialvalues

(η1,η

2)are

close

totheequilibrium

point(μ

1,μ

2),

then

thelength

oftheperiodisclose

toafamilarvalue.

Anexercise

asksyouto

discover

thatvalueexperim

entally.

Rec

ap

%%

Predator-Prey

Chapter

Recap

%This

is

an

executable

program

that

illustrates

the

statements

%introduced

in

the

Preditor

Prey

Chapter

of

"Experiments

in

MATLAB".

%You

can

access

it

with

% %predprey_recap

%edit

predprey_recap

%publish

predprey_recap

% %Related

EXM

programs

% %predprey

%%

Exponential

and

Logistic

Growth.

closeall

figure

k=

1

eta=

1

mu

=20

t=

0:1/32:8;

y=

mu*eta*exp(k*t)./(eta*exp(k*t)

+mu

-eta);

plot(t,[y;exp(t)])

axis([08

022])

title(’Exponentialandlogisticgrowth’)

xlabel(’t’)

ylabel(’y’)

%%

ODE45

for

the

Logistic

Model.

figure

k=

1

Page 115: Experiments With MatLab Moled 2011

219

eta=

1

mu

=20

ydot=

@(t,y)

k*(1-y/mu)*y

ode45(ydot,[08],eta)

%%ODE45

for

the

Predator-Prey

Model.

figure

mu

=[300

200]’

eta=

[400

100]’

signs=

[1

-1]’

pred_prey_ode=

@(t,y)

signs.*(1-flipud(y./mu)).*y

period=

6.5357

ode45(pred_prey_ode,[03*period],eta)

%%Our

predprey

gui.

figure

predprey

Exe

rcises

16.1

Plot.

Makeamore

fewplots

likefigures16.1

and16.2,butwithdifferentvalues

oftheparametersk,η,andμ.

16.2

Decay.

Compare

exponentialandlogisticdecay.Makeaplotlikefigure

16.1

withnegativek.

16.3

Differen

tiate.

Verifythatourform

ula

fory(t)actuallysatisfies

thelogistic

differentialequations.

16.4

Easy

aspie.

Inpredprey,if

theredan

dblue-green

dots

are

close

toeach

other,then

thelength

oftheperiodisclose

toafamilarvalue.

Whatisthatvalue?

Does

thatvaluedep

endupon

theactuallocationofthedots,orjust

theirrelative

closeness?

16.5

Period.In

predprey,iftheredandblue-green

dots

are

farapart,does

the

length

oftheperiodgetlonger

orshorter?Is

itpossible

tomaketheperiodshorter

thanthevalueithasnearequilibrium?

16.6

Phase.

Iftheinitialvalueis

neartheequilibrium

point,

thegraphsofthe

predatorandpreypopulationsare

nearlysinusoidal,withaphase

shift.

Inother

words,

after

thepreypopulationreaches

amaxim

um

orminim

um,thepredator

pop

ulationreaches

amaxim

um

orminim

um

somefractionof

theperiodlater.

What

isthatfraction?

220

Chapter16

.Predator-PreyModel

16.7

Pitstop.

Thepredpreysubfunctionpitstopis

involved

inthe“eventhan-

dling”thatode45usesto

compute

theperiod.pitstop,in

turn,usesatan2to

compute

anglestheta0andtheta1.W

hatisthedifference

betweenthetw

oMat-

labfunctionsatan2,whichtakes

twoarguments,andatan,whichtakes

only

one?

Whathappensifatan2(v,u)is

replacedbyatan(v/u)in

predprey?

Draw

asketch

show

ingtheanglestheta0andtheta1.

16.8

tfinal.Thecallto

ode45in

predpreyspecifies

atimeintervalof[0

100].W

hat

isthesignificance

ofthevalue100?W

hathappensifyouchangeit?

16.9

Lim

itgrowth.Modifypredpreyto

includeagrowth

limitingterm

fortheprey,

similarto

onein

thelogisticequation.

Avoidanother

parameter

bymakingthe

carryingcapacity

twicetheinitialvalue.

Theequationsbecome

y 1=

(1−

y 1 2η 1

)(1−

y 2 μ2)y

1

y 2=

−(1−

y 1 μ1)y

2

Whathappensto

theshapeof

thesolutioncurves?Are

thesolutionsstillperiodic?

Whathappensto

thelength

oftheperiod?

Page 116: Experiments With MatLab Moled 2011

Chapter17

Orbits

Dyn

amicsofmany-bodysystem

s.

Manymathem

aticalmodelsinvolve

thedynamicsofobjectsunder

theinflu-

ence

ofboth

theirmutualinteractionandthesurroundingenvironment.

Theobjects

mightbeplanets,molecules,vehicles,orpeople.Theultim

ate

goalofthischapteris

toinvestigate

then-bodyproblem

incelestialmechanics,whichmodelsthedynamics

ofasystem

ofplanets,

such

asou

rsolarsystem

.Butfirst,

welookattw

osimpler

modelsandprograms,

abouncingballandBrownianmotion.

Theexmprogram

bounceris

amodel

ofabouncingball.Theballis

tossed

into

theair

and

reactsto

thepull

oftheearth’s

gravitation

force.

Thereis

acorrespondingpullof

theballontheearth,buttheearthisso

massivethatwecan

neglect

itsmotion.

Mathem

atically,

weletv(t)an

dz(t)denote

thevelocity

andtheheightofthe

ball.Both

are

functionsof

time.

Highschoolphysics

provides

form

ulasforv(t)an

dz(t),

butwechoosenotto

use

them

because

weareanticipatingmore

complicated

problemswheresuch

form

ulasarenotavailable.Instead,wetakesm

allstepsofsize

δin

time,

computingthevelocity

andheightat

each

step.After

theinitialtoss,

gravitycausesthevelocity

todecrease

ataconstantrate,g.Soeach

step

updates

v(t)with

v(t+δ)

=v(t)−δg

Thevelocity

istherate

ofchangeoftheheight.

Soeach

step

updatesz(t)with

z(t+

δ)=

z(t)+

δv(t)

Hereis

thecore

ofbouncer.m.

Copyright

c ©2011CleveMoler

Matlab

R ©is

aregisteredtradem

ark

ofMath

Works,

Inc.

TM

October

4,2011

221

222

Chapter17

.Orbits

[z0,h]=

initialize_bouncer;

g=

9.8;

c=

0.75;

delta=

0.005;

v0

=21;

whilev0

>=

1

v=

v0;

z=

z0;

whileall(z>=

0)

set(h,’zdata’,z)

drawnow

v=

v-

delta*g;

z=

z+

delta*v;

end

v0

=c*v0;

end

finalize_bouncer

Thefirststatement

[z0,h]=

initialize_bouncer;

generatestheplotofasphereshow

nin

figure

17.1

andreturnsz0,thez-coordinates

ofthesphere,

andh,theHandle

Graphics“handle”fortheplot.

Oneoftheexer-

ciseshasyouinvestigate

thedetailsofinitialize_bouncer.Thefigure

show

sthe

situationat

both

thestart

andtheendofthesimulation.Theballisat

rest

andso

thepicture

isprettyboring.Toseewhathappensduringthesimulation,youhave

toactuallyrunbouncer.

Thenextfourstatements

inbouncer.mare

g=

9.8;

c=

0.75;

delta=

0.005;

v0

=21;

Thesestatements

setthevalues

oftheaccelerationof

grav

ityg,anelasticitycoef-

ficientc,thesm

alltimestep

delta,andtheinitialvelocity

fortheball,v0.

Allthecomputationin

bounceris

donewithin

adoubly

nestedwhileloop.

Theouterloopinvolves

theinitialvelocity

v0.

whilev0

>=

1

...

v0

=c*v0;

end

Toachieve

thebouncingaffect,

theinitialvelocity

isrepeatedly

multiplied

byc=

0.75untilit

isless

than1.Each

bou

nce

startswithavelocity

equalto

3/4ofthe

previousone.

Within

theouterloop,thestatements

Page 117: Experiments With MatLab Moled 2011

223

Figure

17.1.Initial,andfinal,positionofabouncingball.Toseewhat

happensin

between,runbouncer.

v=

v0;

z=

z0;

initialize

thevelocity

vto

v0andtheheightzto

z0.Then

theinner

loop

whileall(z>=

0)

set(h,’zdata’,z)

drawnow

v=

v-

delta*g;

z=

z+

delta*v;

end

proceedsuntiltheheightgo

esnegative.

Theplotis

repeatedly

updatedto

reflect

thecurrentheight.

Ateach

step

,thevelocity

visdecreasedbyaconstantamount,

delta*g,therebyaffectingthegravitationaldeceleration.Thisvelocity

isthen

used

tocompute

thechangein

theheightz.Aslongasvispositive,

thezincreaseswith

each

step.W

hen

vreaches

zero,theballhasreached

itsmaxim

um

height.

Then

v

becomes

negativeandzdecreasesuntiltheballreturnsto

heightzero,term

inating

theinner

loop.

After

both

loop

sare

complete,thestatement

finalize_bouncer

activates

apushbuttonthatoff

ersyouthepossibilityof

repeatingthesimulation.

Brownianmotionis

notasobviousasgravityin

ourdailylives,butwedo

encounteritfrequently.

AlbertEinstein’sfirstim

portantscientificpaper

wasabout

Brownianmotion.Thinkofparticplesofdust

suspended

intheairan

dilluminated

224

Chapter17

.Orbits

byabeam

ofsunlight.

Or,

diffusionofodors

throughoutaroom.Or,

abeach

ball

beingtossed

aroundastadium

bythespectators.

InBrownianmotionanobject

–adust

particle,amolecule,or

aball–reacts

tosurroundingrandom

forces.

Oursimulation

oftheseforces

usesthebuilt-in

MATLAB

functionrandnto

generate

norm

allydistributedrandom

numbers.

Each

timethestatement

randn

isexecutedanew

,unpredictable,valueis

produced.Thestatement

randn(m,n)

producesanm-by-n

array

ofrandom

values.Each

timethestatement

hist(randn(100000,1),60)

isexecutedahistogram

plotliketheonein

figure

17.2

isproduced.Try

executing

this

statementseveraltimes.You

willseethatdifferenthistogramsareproduced

each

time,

butthey

allhavethesameshape.

You

mightrecognizethe“bell-shaped

curve”

thatis

know

nmore

form

allyastheGaussianornorm

aldistribution.The

histogram

show

sthatpositivean

dnegativerandom

numbersare

equallylikelyan

dthatsm

allvalues

aremore

likelythanlargeones.This

distributionis

themathe-

maticalheart

ofBrownianmotion.

−50

50

1000

2000

3000

4000

5000

6000

7000

Figure

17.2.Histogram

ofthenorm

alrandom

numbergenerator.

Asimple

example

ofBrownianmotionknow

nas

arandom

walk

isshow

nin

figure

17.3.This

isproducedbythefollow

ingcodefragment.

m=

100;

x=

cumsum(randn(m,1));

y=

cumsum(randn(m,1));

Page 118: Experiments With MatLab Moled 2011

225

plot(x,y,’.-’)

s=

2*sqrt(m);

axis([-ss

-s

s]);

−15

−10

−50

510

15−1

5

−10−5051015

Figure

17.3.A

simple

example

ofBrownianmotion.

Thekey

statementis

x=

cumsum(randn(m,1));

This

statementgeneratesthex-coordinatesofthewalk

byform

ingthesuccessive

cumulative

partialsumsof

theelem

ents

ofthevectorr

=randn(m,1).

x1

=r 1

x2

=r 1

+r 2

x3

=r 1

+r 2

+r 3

...

Asimilarstatementgeneratesthey-coordinates.

Cutandpastethecodefragment

into

theMatlabcommandwindow

.Execute

itseveraltimes.Try

differentvalues

ofm.Youwillseedifferentrandom

walksgoingoffin

differentrandom

directions.

Over

manyexecutions,

thevalues

ofxandyare

just

aslikelyto

bepositiveas

negative.

Wewantto

compute

anaxis

scale

factorsso

thatmost,butnotall,of

thewalksstay

within

theplotboundaries.It

turnsou

tthatasm,thelength

ofthe

walk,increases,

theproper

scale

factorincreaseslike√ m

.A

fancier

Brownianmotionprogram,invo

lvingsimultaneousrandom

walksof

manyparticlesin

threedim

ensions,isavailable

inbrownian3.m.A

snapshotofthe

evolvingmotionis

show

nin

figure

17.4.Hereis

thecore

ofbrownian3.m.

226

Chapter17

.Orbits

−50

510

−50

510−50510

Figure

17.4.A

snapshotoftheoutputfrom

brownian3,showingsimulta-

neousrandom

walksofmanyparticulesin

threedim

ensions.

n=

50;

%Default

number

of

particles

P=

zeros(n,3);

H=

initialize_graphics(P);

while~get(H.stop,’value’)

%Obtain

step

size

from

slider.

delta=

get(H.speed,’value’);

%Normally

distributed

random

velocities.

V=

randn(n,3);

%Update

positions.

P=

P+

delta*V;

update_plot(P,H);

end

Thevariable

nis

thenumber

ofparticles.

Itis

usuallyequalto

50,butsomeother

number

ispossible

withbrownian3(n).

Thearray

Pcontainsthepositionsofn

particlesin

threedim

ensions.

Initially,

alltheparticlesare

locatedattheorigin,

(0,0,0).

Thevariable

His

aMatlabstructure

containinghandlesforalltheuser

Page 119: Experiments With MatLab Moled 2011

227

interface

controls.In

particular,H.stoprefers

toatogglethatterm

inatesthewhile

loopandH.speedrefers

toaslider

thatcontrolsthespeedthroughthevalueof

the

timestep

delta.Thearray

Vis

ann-by-3

arrayof

norm

allydistributedrandom

numbersthatserveastheparticle

velocities

intherandom

walks.

Most

ofthe

complexityof

brownian3is

contained

inthesubfunctioninitialize_graphics.

Inadditionto

thespeedslider

andthestopbutton,theGUIhaspushbuttonsor

togglesto

turn

onatrace,zoom

inandou

t,andchangetheview

point.

Weare

now

readyto

tackle

then-bodyproblem

incelestialmechanics.

Thisis

amodel

ofasystem

ofplanetsandtheirinteractiondescribed

byNew

ton’slawsof

motionandgrav

itationalattraction.Over

fivehundredyears

ago,Johannes

Kepler

realizedthatifthereareonly

twoplanetsin

themodel,theorbitsare

ellipseswitha

commonfocusatthecenterof

mass

ofthesystem

.Thisprovides

afairdescription

ofthemoon

’sorbitaroundtheearth,oroftheearth’sorbitaroundthesun.Butif

youare

planningatrip

tothemoonoramissionto

Mars,youneedmore

accuracy.

Youhaveto

realize

thatthesunaff

ects

themoon’sorbitaroundtheearthandthat

Jupiter

affects

theorbitsofboth

theearthandMars.Furthermore,ifyouwishto

model

more

thantw

oplanets,ananalyticsolutionto

theequationsofmotionisnot

possible.It

isnecessary

tocompute

numericalapproxim

ations.

Ournotationusesvectors

andarray

s.Let

nbethenumber

ofbodiesan

d,

fori=

1,...,n

,letpibethevectordenotingthepositionof

thei-th

body.

For

two-dim

ensionalmotionthei-th

positionvectorhascomponents

(xi,y i).

For

three-

dim

ensionalmotion

itscomponents

are

(xi,y i,z

i).

Thesm

all

system

show

nin

figure

17.5

illustratesthis

notation.Therearethreebodiesmov

ingin

twodim

en-

sions.

Thecoordinate

system

andunitsare

chosenso

thatinitiallythefirstbody,

whichis

gold

ifyouhavecolor,

isattheorigin,

p1=

(0,0)

Thesecond

body,

which

isblue,

isoneunit

away

from

thefirstbodyin

thex

direction,so

p2=

(1,0)

Thethirdbody,

whichisred,isoneunitaw

ayfrom

thefirstbodyin

theydirection,

so

p3=

(0,1)

Wewishto

model

how

thepositionvectors

pivary

withtime,

t.Thevelocity

ofabodyis

therate

ofchangeofitspositionan

dtheacceleration

istherate

ofchangeofitsvelocity.Weuse

oneandtw

odots

over

pito

den

ote

thevelocity

and

accelerationvectors,piandpi.

Ifyouare

familiarwithcalculus,

you

realize

that

thedotmeansdifferentiationwithrespectto

t.Forourthreebodyexample,the

firstbodyisinitiallyheadingaw

ayfrom

theother

twobodies,so

itsvelocity

vector

hastw

onegativecomponents,

p1=

(−0.12,−

0.36)

Theinitialvelocity

ofthesecondbodyis

allin

theydirection,

p2=

(0,0.72)

228

Chapter17

.Orbits

−1.5

−1−0

.50

0.5

11.

5−1

.5−1

−0.50

0.51

1.5

p 1p 2

p 3

Figure

17.5.Initialpositionsandvelocities

ofasm

allsystem

withthree

bodiesin

two-dim

ensionalspace.

andtheinitialvelocity

ofthethirdbodyis

sendingittowardsthesecondbody,

p3=

(0.36,−0

.36)

New

ton’s

law

ofmotion,thefamousF

=ma,saysthatthemass

ofabody

times

itsaccelerationisproportionalto

thesum

oftheforces

actingonit.New

ton’s

law

ofgrav

itationalsaysthattheforcebetweenanytw

obodiesis

proportionalto

theproduct

oftheirmasses

andinverselyproportionalto

thesquare

ofthedistance

betweenthem

.So,theequationsofmotionare

mip

i=

γ∑ j�=i

mim

jpj−pi

||pj−

pi||

3,

i=

1,...,n

Hereγis

thegravitationalconstant,m

iis

themass

ofthei-th

body,

pj−piis

the

vectorfrom

bodyito

bodyjand||p

j−

pi||

isthelength

ornorm

ofthatvector,

whichis

thedistance

betweenthetw

obodies.

Thedenominatorofthefraction

involves

thecubeof

thedistance

because

thenumeratorcontainsthedistance

itself

andso

theresultingquotientinvo

lves

theinverseof

thesquare

ofthedistance.

Figure

17.6

show

sourthreebodyexample

again.Thelength

ofthevector

r 23=

p3−p2isthedistance

betweenp2andp3.Thegravitationforces

betweenthe

bodieslocatedatp2andp3are

directedalongr 2

3and−r

23.

Tosummarize,thepositionof

thei-th

bodyisdenotedbythevectorpi.

The

instantaneouschangein

positionof

thisbodyisgiven

byitsvelocity

vector,denoted

bypi.

Theinstantaneouschangein

thevelocity

isgiven

byitsaccelerationvector,

denotedbypi.

Theaccelerationis

determined

from

thepositionandmasses

ofall

thebodiesbyNew

ton’s

lawsof

motionan

dgravitation.

Thefollow

ingnotationsimplifies

thediscussionofnumericalmethods.

Stack

thepositionvectors

ontopofeach

other

toproduce

ann-by-d

array

wherenisthe

Page 120: Experiments With MatLab Moled 2011

229

−1.5

−1−0

.50

0.5

11.

5−1

.5−1

−0.50

0.51

1.5

p 1p 2

p 3

r 23

Figure

17.6.Thedoublearrowdepicts

thevectors

r 23=

p3−p2and−r

32.

Thelengthofthis

arrow

isthedistance

betweenp2andp3.

number

ofbodiesandd=

2or3is

thenumber

ofspatialdim

ensions..

P=

⎛ ⎜ ⎜ ⎜ ⎝p1

p2 . . . pn

⎞ ⎟ ⎟ ⎟ ⎠Let

Vden

ote

asimilararrayofvelocity

vectors.

V=

⎛ ⎜ ⎜ ⎜ ⎝p1

p2 . . . pn

⎞ ⎟ ⎟ ⎟ ⎠And,letG(P

)denote

thearray

ofgrav

itationforces.

G(P

)=

⎛ ⎜ ⎜ ⎜ ⎝g 1 g 2 . . . g n

⎞ ⎟ ⎟ ⎟ ⎠where g i

=γ∑ j�=i

mj

pj−pi

||pj−pi||

3

Withthis

notation,theequationsofmotioncanbewritten

P=

V

V=

G(P

)

230

Chapter17

.Orbits

Forourthreebodyexample,theinitialvalues

ofP

andV

are

P=

⎛ ⎝00

10

01

⎞ ⎠and

V=

⎛ ⎝−0.12

−0.36

00.72

0.36

−0.36

⎞ ⎠Themasses

inourthreebodyexample

are

m1=

1/2,

m2=

1/3,

m3=

1/6

From

thesequantities,wecancompute

theinitialvalueofthegrav

itationforces,

G(P

). Wewillillustrate

ournumericalmethodsbytryingto

gen

erate

acircle.The

differentialequationsare

x=

y

y=

−xW

ithinitialconditionsx(0)=

0,y(0)=

1,theexact

solutionis

x(t)=

sint,

y(t)=

cost

Theorbitis

aperfect

circle

withaperiodequalto

2π.

Themost

elem

entary

numericalmethod,whichwewillnotactuallyuse,is

know

nastheforw

ard

orexplicitEulermethod.Themethodusesafixed

timestep

δandsimultaneouslyad

vancesboththepositionsandvelocities

from

timet k

totimet k

+1=

t k+δ.

Pk+1=

Pk+δVk

Vk+1=

Vk+

δG(P

k)

Theforw

ardEuler’smethodapplied

tothecircle

generatorproblem

becomes

xk+1=

xk+

δy k

y k+1=

y k−

δxk

Theresultforδ=

2π/30isshow

nin

thefirstplotin

figure

17.7.Insteadof

acircle

weget

agrowingspiral.

Themethodis

unstable

andconsequentlyunsatisfactory,

particularlyforlongtimeperiods.

Smaller

timestep

smerelydelay

theinevitable.

Wewou

ldseemore

complicated,butsimilar,

behav

iorwiththen-bodyequations.

Another

elem

entary

numericalmethodis

know

nas

thebackward

orim

plicit

Eulermethod.In

general,it

invo

lves

somehow

solvinganonlinearsystem

ateach

step

.

Pk+1−δVk+1=

Pk

Vk+1−

δG(P

k+1)=

Vk

Page 121: Experiments With MatLab Moled 2011

231

−10

1

−101

−10

1

−101

−10

1

−101

Figure

17.7.

ThreeversionsofEuler’smethod

forgeneratingacircle.

Thefirstplotshowsthattheforw

ard

method

isunstable.

Thesecondplotshowsthat

thebackward

method

hasexcessivedamping.

Thethirdplotshowsthatsymplectic

method,whichis

acompromisebetween

thefirsttwomethods,

producesanearly

perfectcircle.

For

oursimple

circle

example

theim

plicitsystem

islinear,

soxk+1andy k

+1are

easily

computedbysolvingthe2-by-2

system

xk+1−

δy k

+1=

xk

y k+1+

δxk+1=

y k

Theresult

isshow

nin

thesecondplotin

figure

17.7.Insteadof

acircle

weget

adecay

ingspiral.

Themethodis

stable,butthereis

toomuch

damping.Again,we

wou

ldseesimilarbehav

iorwiththen-bodyequations.

Themethodthatweactuallyuse

isacompromisebetweentheexplicitand

implicitEulermethods.

Itis

themost

elem

entary

instance

ofwhatare

know

nas

symplectic

methods.

Themethodinvolves

twohalf-steps.

Inthefirsthalf-step,the

positionsattimet k

are

usedin

thegrav

itationequationsto

update

ofthevelocities.

Vk+1=

Vk+δG(P

k)

Then,in

thesecondhalf-step,these“new

”velocities

are

usedto

update

theposi-

tions.

Pk+1=

Pk+δVk+1

Thenovel

feature

ofthis

symplectic

methodis

thesubscriptk+

1insteadofkon

theV

term

inthesecondhalf-step.

For

thecircle

gen

erator,

thesymplectic

methodis

xk+1=

xk+δy k

y k+1=

y k−δxk+1

Theresultisthethirdplotin

figure

17.7.Ifyoulook

carefully,

youcanseethatthe

orbitin

notquiteacircle.It’sactuallyanearlycircularellipse.Andthefinalvalue

does

notquitereturn

totheinitialvalue,

sotheperiodis

notexactly

2π.Butthe

importantfact

isthattheorbitis

neither

agrow

ingnoradecay

ingspiral.

232

Chapter17

.Orbits

−1.5

−1−0

.50

0.5

11.

5−1

.5−1

−0.50

0.51

1.5

p 1p 2

p 3

Figure

17.8.Thefirstfew

stepsofourexample

system

.

Therearemore

complicatedsymplectic

algorithmsthataremuch

more

accu-

rate

per

step

thanthis

symplectic

Euler.

Butthesymplectic

Euleris

satisfactory

forgeneratingwellbehaved

graphicaldisplays.

Most

well-know

nnumericalmeth-

ods,

includingRunge-Kuttamethodsand

traditionalmultistep

methods,

donot

havethis

symplectic

stabilityproperty

and,asaresult,arenotas

satisfactory

for

computingorbitsover

longtimespans.

Figure

17.8

show

sthefirstfew

stepsforourexample

system

.Aswenoted

earlier,

theinitialpositionandvelocity

are

P=

00

1.0000

0

01.0000

V=

-0.1200

-0.3600

00.7200

0.3600

-0.3600

After

onestep

withδ=

0.20weobtain

thefollow

ingvalues.

P=

-0.0107

-0.0653

0.9776

0.1464

0.0767

0.9033

V=

-0.0533

-0.3267

-0.1118

0.7318

Page 122: Experiments With MatLab Moled 2011

233

0.3836

-0.4836

Thethreemasses,1/2,1/3,and1/

6,are

notequal,butare

comparable,so

allthree

bodieshavesignificantaffects

oneach

other

andallthreemovenoticeabledistances.

Weseethattheinitialvelocity

ofthefirstbodycausesit

tomoveaw

ayfrom

the

other

two.In

onestep,itspositionchanges

from

(0,0)to

smallnegativevalues,

(−0.0107

,−0.0653)Thesecondbodyisinitiallyatposition(1,0)withvelocity

(0,1)

inthepositiveydirection.In

onestep,itspositionchanges

to(0.9776,0.1464).

The

x-coordinate

haschanged

relativelylittle,whilethey-coordinate

haschanged

by

roughly

0.72

δ.Thethirdbodymoves

inthedirectionindicatedbythevelocity

vectorin

figure

17.5.

After

asecondstep

wehavethefollow

ingvalues.Asexpected,allthetrends

notedin

thefirststep

continue.

P=

-0.0079

-0.1209

0.9325

0.2917

0.1589

0.7793

V=

0.0136

-0.2779

-0.2259

0.7268

0.4109

-0.6198

−1.5

−1−0

.50

0.5

11.

5−1

.5−1

−0.50

0.51

1.5

Figure

17.9.Theinitialtrajectories

ofourexample

system

.

Figure

17.9

show

saninitialsectionofthetrajectories.Youshould

runour

Experim

ents

program

orbits(3)to

seethethreebodiesin

motion.

Thesm

all

bodyandthelargebodyorbitin

aclockwisedirectionaroundeach

other

whilethe

medium-sizebodyorbitsin

acounter-clockwisedirectionaroundtheother

two.

234

Chapter17

.Orbits

−20

0

20

−20

−10

010

20−505

Figure

17.10.Thesolarsystem

,withtheinitialpositionsofalltheplanets

andtheorbitsoftheouterplanets,

Jupiter,Saturn,Uranus,

andNeptune.

OurExperim

ents

program

orbitsmodelsninebodiesin

thesolarsystem

,namelythesunandeightplanets.

Figures17.10and17.11show

snapshots

ofthe

outputfrom

orbitswithtw

odifferentzoom

factors

thatare

necessary

tospanthe

scale

ofthesystem

.Theorbitsforalltheplanetsarein

theproper

proportion.

But,obviously,

thesymbolsforthesunandtheplanetsdonothavethesamescale.

Web

sources

forinform

ationab

outthesolarsystem

are

provided

bytheUniversity

CorporationforAtm

ospheric

Research,theJet

PropulsionLaboratory,andtheUS

NationalAir

andSpace

Museum,

http://www.windows.ucar.edu

http://www.jpl.nasa.gov/solar_system

http://airandspace.si.edu:80/etp/ss/index.htm

Page 123: Experiments With MatLab Moled 2011

235

−1

0

1

−1−0

.50

0.5

1

−0.3

−0.2

−0.10

0.1

0.2

0.3

Figure

17.11.Zoomingin

byafactorof16reveals

theorbitsoftheinner

planets,

Mercury,Ven

us,

EarthandMars.

Rec

ap

%%Orbits

Chapter

Recap

%This

is

an

executable

program

that

illustrates

the

statements

%introduced

in

the

Orbits

Chapter

of

"Experiments

in

MATLAB".

%You

can

access

it

with

% %orbits_recap

%edit

orbits_recap

%publish

orbits_recap

% %Related

EXM

programs

% %bouncer

%orbits

236

Chapter17

.Orbits

%%

Core

of

bouncer,

simple

gravity.

no

gravity

%Initialize

z0

=eps;

g=

9.8;

c=

0.75;

delta=

0.005;

v0

=21;

y=

[];

%Bounce

whilev0

>=

1

v=

v0;

z=

z0;

whilez

>=

0

v=

v-

delta*g;

z=

z+

delta*v;

y=

[y

z];

end

v0

=c*v0;

end

%Simplified

graphics

closeall

figure

plot(y)

%%

Normal

random

number

generator.

figure

hist(randn(100000,1),60)

%%

Snapshot

of

two

dimensional

Brownian

motion.

figure

m=

100;

x=

cumsum(randn(m,1));

y=

cumsum(randn(m,1));

plot(x,y,’.-’)

s=

2*sqrt(m);

axis([-ss

-s

s]);

Page 124: Experiments With MatLab Moled 2011

237

%%Snapshot

of

three

dimensional

Brownian

motion,

brownian3

n=

50;

delta=

0.125;

P=

zeros(n,3);

fort

=0:10000

%Normally

distributed

random

velocities.

V=

randn(n,3);

%Update

positions.

P=

P+

delta*V;

end

figure

plot3(P(:,1),P(:,2),P(:,3),’.’)

boxon

%%Orbits,

the

n-body

problem.

%{

%ORBITS

n-body

gravitational

attraction

for

n=

2,

3or

9.

%ORBITS(2),

two

bodies,

classical

elliptic

orbits.

%ORBITS(3),

three

bodies,

artificial

planar

orbits.

%ORBITS(9),

nine

bodies,

the

solar

system

with

one

sun

and

8planets.

% %ORBITS(n,false)

turns

off

the

uicontrols

and

generates

astatic

plot.

%ORBITS

with

no

arguments

is

the

same

as

ORBITS(9,true).

%n

=number

of

bodies.

%P

=n-by-3

array

of

position

coordinates.

%V

=n-by-3

array

of

velocities

%M

=n-by-1

array

of

masses

%H

=graphics

and

user

interface

handles

if

(nargin

<2)

gui=

true;

end

if

(nargin

<1);

n=

9;

end

[P,V,M]=

initialize_orbits(n);

H=

initialize_graphics(P,gui);

steps=

20;

%Number

of

steps

between

plots

238

Chapter17

.Orbits

t=

0;

%time

whileget(H.stop,’value’)==

0

%Obtain

step

size

from

slider.

delta=

get(H.speed,’value’)/(20*steps);

fork

=1:steps

%Compute

current

gravitational

forces.

G=

zeros(size(P));

fori

=1:n

forj

=[1:i-1

i+1:n];

r=

P(j,:)

-P(i,:);

G(i,:)=

G(i,:)

+M(j)*r/norm(r)^3;

end

end

%Update

velocities

using

current

gravitational

forces.

V=

V+

delta*G;

%Update

positions

using

updated

velocities.

P=

P+

delta*V;

end

t=

t+

steps*delta;

H=

update_plot(P,H,t,gui);

end

finalize_graphics(H,gui)

end

%}

%%

Run

all

three

orbits,

with

2,

3,

and

9bodies,

and

no

gui.

figure

orbits(2,false)

figure

orbits(3,false)

figure

orbits(9,false)

Page 125: Experiments With MatLab Moled 2011

239

Exe

rcises

17.1

Bouncingball.

(a)W

hatis

themaxim

um

heightofthebouncingball?

(b)How

manytimes

does

theballbounce?

(c)W

hatistheeff

ectofchangingeach

ofthefourbouncervalues

g,c,delta,an

dv0.

17.2

Pluto

andCeres.Changeorbitsto

orbits11byaddingtheerstwhileplanet

Pluto

andtherecentlypromoteddwarf

planet

Ceres.See

Wikipedia:

http://en.wikipedia.org/wiki/Planet

http://en.wikipedia.org/wiki/Ceres_(dwarf_planet)

and

http://orbitsimulator.com/gravity/articles/ceres.html

17.3

Comet.

Addacomet

toorbits.

Findinitialconditionsso

thatthecomet

hasastable,buthighly

ellipticalorbit

thatextendswellbeyondtheorbitsofthe

planets.

17.4

Twin

suns.

Turn

thesunin

orbitsinto

atw

instarsystem

,withtw

osuns

orbitingeach

other

outoftheplaneoftheplanets.

Whateventuallyhappensto

the

planetary

orbits?

Forexample,try

sun1.p=

[1

00];

sun1.v=

[0

0.25

0.25];

sun1.m=

0.5;

sun2.p=

[-1

00];

sun2.v=

[0

-0.25

-0.25];

sun2.m=

0.5;

Try

other

values

aswell.

240

Chapter17

.Orbits

Page 126: Experiments With MatLab Moled 2011

Chapter18

Shallo

wW

aterEquations

Theshallow

waterequationsmodel

tsunamis

andwavesin

bathtubs.

Thischapterismore

advancedmathem

aticallythanearlierchapters,butyou

mightstillfinditinterestingeven

ifyoudonotmaster

themathem

aticaldetails.

Theshallow

waterequationsmodel

thepropagationofdisturbancesin

water

andother

incompressible

fluids.

Theunderlyingassumptionis

thatthedepth

of

thefluid

issm

allcomparedto

thewavelength

ofthedisturbance.For

example,we

donotordinary

thinkoftheIndianOceanasbeingshallow

.Thedepth

istw

oor

threekilometers.

Butthedevastatingtsunamiin

theIndianOceanonDecem

ber

26,2004involved

waves

thatweredozensor

hundredofkilometerslong.Sothe

shallow

waterapproxim

ationprovides

areasonable

model

inthis

situation.

Theequationsare

derived

from

theprinciplesofconservation

ofmass

and

conservationofmomentum.Theindep

endentvariablesare

time,

t,andtw

ospace

coordinates,xandy.Thedep

endentvariablesare

thefluid

heightor

dep

th,h,an

dthetw

o-dim

ensionalfluid

velocity

field,uandv.W

iththeproper

choiceofunits,the

conserved

quantities

aremass,whichis

proportionalto

h,an

dmomentum,which

isproportionalto

uhandvh.Theforceactingon

thefluid

isgravity,

represented

bythegravitationalconstant,g.Thepartialdifferentialequationsare:

∂h ∂t+

∂(uh)

∂x

+∂(vh)

∂y

=0

∂(uh)

∂t

+∂(u

2h+

1 2gh2)

∂x

+∂(uvh)

∂y

=0

∂(vh)

∂t

+∂(uvh)

∂x

+∂(v

2h+

1 2gh2)

∂x

=0

Copyright

c ©2011CleveMoler

Matlab

R ©is

aregisteredtradem

ark

ofMath

Works,

Inc.

TM

October

4,2011

241

242

Chapter18

.Shallow

Water

Equations

Inorder

towrite

theequationsin

acompact

form

,introduce

threevectors.

U=

⎛ ⎝h uh

vh

⎞ ⎠

F(U

)=

⎛ ⎝uh

u2h+

1 2gh2

uvh

⎞ ⎠

G(U

)=

⎛ ⎝vh

uvh

v2h+

1 2gh2

⎞ ⎠W

iththisnotation,theshallow

waterequationsareaninstance

ofahyperbolic

conservationlaw.

∂U ∂t+

∂F(U

)

∂x

+∂G(U

)

∂y

=0

Onedelicate

aspectofthis

model

isthebou

ndary

conditions,

especiallyifwe

intendto

model

arealworld

geometry

such

astheIndianOcean.For

oursimple

experim

ent,weconfineourselves

toasquare

regionandspecifyreflective

bou

ndary

conditions,

u=

0ontheverticalsides

ofthesquare

andv=

0onthehorizontal

sides.Theseconditionscause

anywaves

thatreach

thebou

ndary

tobereflected

back

into

theregion.

More

realistic

modelsof

oceansandtsunamisincludeterm

sthatdescribethe

topographyoftheoceanfloor,theCoriolisforceresultingtheearth’srotation,and

possibly

other

externalforces.Buttheequationsweareconsideringherearestill

thebasisofsuch

models.

Figure

18.1.Atthebeginningofatimestep,thevariables

representthe

solutionatthecenters

ofthefinitedifferen

cegrid.

Wewilluse

theLax-Wen

droff

methodto

compute

anumericalap

proxim

ation

tothesolution.Introduce

aregularsquare

finitedifferen

cegridwithavector-valued

solutioncenteredin

thegridcells,

asshow

nin

figure

18.1.Thequantity

Un i,j

Page 127: Experiments With MatLab Moled 2011

243

represents

athreecomponentvectorateach

gridcelli,jthatevolves

withtimestep

n.

Each

timestep

involves

twostages,somethinglikeatw

o-stageRungeKutta

methodforordinary

differentialequations.

Thefirststageis

ahalfstep;it

defines

values

ofU

attimestep

n+

1 2andthemidpoints

oftheedges

ofthegrid,as

show

nin

figure

18.2.

Un+

1 2

i+1 2,j=

1 2(U

n i+1,j+

Un i,j)−

Δt

2Δx(F

n i+1,j−F

n i,j)

Un+

1 2

i,j+

1 2

=1 2(U

n i,j+1+

Un i,j)−

Δt

2Δy(G

n i,j+1−G

n i,j)

Figure

18.2.Thefirststage

computesvalues

thatrepresentthesolution

atthemidpoints

oftheedgesin

thefinitedifferen

cegrid.

Thesecondstagecompletesthetimestep

byusingthevalues

computedin

the

firststageto

compute

new

values

atthecenters

ofthecells,returningto

figure

18.1.

Un+1

i,j

=U

n i,j−

Δt

Δx(F

n+

1 2

i+1 2,j−F

n+

1 2

i−1 2,j)−

Δt

Δy(G

n+

1 2

i,j+

1 2

−G

n+

1 2

i,j−

1 2

)

OurMATLABprogram,exm/waterwave,usesLax-W

endroffto

solvetheshal-

lowwaterequationsonasquare

regionwithreflectiveboundary

conditions.

Initially,

h=

1,u

=0,v

=0over

theentire

region,so

thesolutionis

static.

Then,at

re-

peatedintervals,atw

odim

ensionalGaussianshaped

peakisadded

toh,simulating

anim

pulsivedisturbance

likeawaterdrophittingthesurface.Theresultingwaves

propagate

back

andforthover

theregion.A

few

snapshots

ofthedynamic

graphic

are

show

nin

figure

18.3.TheLax-W

endroffschem

eamplifies

artificial,nonphysi-

caloscillations.

Eventuallythenumericalvalues

overflow

,producingfloatingpoint

Infsan

dNaNs,

whichcause

thesurface

plotto

disappear.

CLAW

PACK,whichstandsforConservationLaw

Package,isalargecollection

ofFortransubroutines

developed

byRandyLeV

equeandhiscolleagues

attheUni-

versity

ofWashington.A

versionofthepackagespecializedto

modelingtsunamis

hasbeendeveloped

byDav

idGeorge.

See:

http://www.clawpack.org

http://www.amath.washington.edu/~dgeorge/tsunamimodeling.html

244

Chapter18

.Shallow

Water

Equations

Figure

18.3.A

waterdropinitiatesawave

thatreflects

offtheboundary.

Rec

ap

%%

Shallow

Water

Chapter

Recap

%This

is

an

executable

program

that

illustrates

the

statements

%introduced

in

the

Shallow

Water

Chapter

of

"Experiments

in

MATLAB".

%You

can

access

it

with

% %water_recap

%edit

water_recap

%publish

water_recap

% %Related

EXM

programs

% %waterwave

%%

Finite

Differences

%A

simple

example

of

the

grid

operations

in

waterwave.

Page 128: Experiments With MatLab Moled 2011

245

%%Create

atwo

dimensional

grid.

m=

21;

[x,y]=

ndgrid(-1:

2/(m-1):

1);

%%The

water

drop

function

from

waterwave.

U=

exp(-5*(x.^2+y.^2));

%%Surf

plot

of

the

function

clf

shg

h=

surf(x,y,U);

axisoff

ax

=axis;

%%Colormap

c=

(37:100)’;

cyan=

[0*c

cc]/100;

colormap(cyan)

pause(1)

%%Indices

in

the

four

compass

directions.

n=

[2:m

m];

e=

n;

s=

[1

1:m-1];

w=

s;

%%A

relation

parameter.

Try

other

values.

%Experiment

with

omega

slightly

greater

than

one.

omega=

1;

%%Relax.

%Repeatedly

replace

grid

values

by

relaxed

average

of

four

neighbors.

tfinal=

500;

fort

=1:tfinal

U=

(1-omega)*U

+omega*(U(n,:)+U(:,e)+U(s,:)+U(:,w))/4;

set(h,’zdata’,U);

axis(ax)

drawnow

end

246

Chapter18

.Shallow

Water

Equations

Exe

rcises

18.1

Relax.

Modifyomegain

water_recap.Try

values

slightlylarger

than1.0

.

18.2

Boundary

conditions.

Modifytheboundary

conditionsusedin

waterwave.

Page 129: Experiments With MatLab Moled 2011

Chapter19

MorseCode

Morsecodedem

onstratesbinary

treesandcellarrays.

HV

FL

PJ

BX

CY

ZQ

SU

RW

DK

GO

IA

NM

ET

Figure

19.1.Thebinary

tree

defi

ningMorsecode.

Abranch

totheleft

sign

ifies

adotin

thecodeandabranch

totherightis

adash.In

additionto

the

rootnode,

thereare

26nodes

containingthecapitallettersoftheEnglishalphabet.

Thischapterbringstogether

threedisparate

topics:

Morsecode,

binary

trees,

andcellarray

s.Morsecodeis

nolonger

importantcommercially,

butit

stillhas

Copyright

c ©2011CleveMoler

Matlab

R ©is

aregisteredtradem

ark

ofMath

Works,

Inc.

TM

October

4,2011

247

248

Chapter19

.Morse

Code

someav

idfansamonghobbyists.Binary

treesare

afundamentaldata

structure

used

throughoutmoderncomputing.Andcellarrays,whichare

uniqueto

Matlab,are

array

swhose

elem

ents

areother

arrays.

You

canget

aheadstart

onou

rinvestigationbyrunningtheexmprogram

morse_gui

Experim

entwiththefourbuttonsin

variouscombinations,

andthetextandcode

box

.This

chapterwillexplain

theiroperation.

Morsecodewasinventedover

150years

ago,notbySamuel

F.B.Morse,

but

byhiscolleague,AlfredVail.Ithasbeenin

widespreaduse

ever

since.Thecodecon-

sistsofshort

dots,’.’,an

dlonger

dashes,’-’,separatedbyshort

andlongspaces.

Youare

certainly

familiarwiththeinternationaldistresssignal,’...---...’,

thecodefor“SOS”,abbreviating“SaveOurShips”

orperhaps“SaveOurSouls”.

Butdid

you

notice

thatsomemoderncellphones

signal’...--

...’,thecode

for“S

MS”,indicatingactivityof

the“Short

MessageService”.

Until2003,alicense

tooperate

anam

ateurradio

required

minim

alproficiency

inMorsecode.

(Fulldisclosure:W

hen

Iwasin

juniorhighschool,Ilearned

Morse

codeto

get

myham

license,andI’venever

forgotten

it.)

Accordingto

Wikipedia,in

2004,theInternationalTelecommunicationUnion

form

allyadded

acodefortheubiquitousem

ailcharacter,@,to

theinternational

Morsecodestandard.This

wasthefirstad

ditionsince

WorldWar

I.

TheMorsetree

Wecould

provideatable

show

ingthat’.-’isthecodeforA,’-...’thecodefor

B,andso

on.Butwe’re

notgoingto

dothat,

andourMatlabprogram

does

not

start

withsuch

atable.Instead,wehavefigure

19.1.This

isabinary

tree,an

dfor

ourpurposes,

itis

thedefi

nition

ofMorsecode.

Incontrast

tonature,computer

scientistsputtheroot

ofatree

ontop.Startingatthisroot,or

anyother

node,

and

mov

ingleft

alongalinksignifies

adot,whilemov

ingrightis

adash.Forexample,

startingattherootandmov

ingonestep

totheleft

follow

edbyoneto

theright

getsusto

A.Sothis

fact,rather

thanatable,tellsus’.-’is

thecodeforA.

Thelength

ofaMorsecodesequence

foraparticularcharacter

isdetermined

by

thefrequency

ofthatcharacter

intypicalEnglish

text.

Themost

frequent

character

is“E

”.Consequently,

itsMorsesequence

isasingle

dotan

dit

islinked

directlyto

theroot

ofou

rtree.Theleast

frequentcharacters,such

as“Z

”and“X”,

havethelongestMorsesequencesandarefarfrom

theroot.

(Wewillconsider

the

fourmissingnodes

inthetree

later.)

Binary

treesare

bestim

plementedin

Matlabbycellarrays,whichare

array

swhose

elem

ents

arethem

selves

other

Matlabobjects,includingother

arrays.

Cell

array

shavetw

okindsofindexingop

erations.

Curlybraces,

{and},areusedfor

constructionandforaccessingindividualcells.

Conventionalsm

ooth

parentheses,

(and),areusedforaccessingsubarray

s.Forexample,

C=

{’A’,’rolling’,’stone’,’gathers’,’momentum’,’.’}

Page 130: Experiments With MatLab Moled 2011

249

producesacellarray

thatcontainssixstringsofdifferentlengths.

This

example

isdisplayedas

C=

’A’’rolling’’stone’’gathers’’momentum’’.’

Thethirdelem

ent,denotedwithcurlybracesbyC{3},is

thestring’stone’.The

thirdsubarray,

denotedwithparentheses

byC(3),isanother

cellarraycontaininga

single

elem

ent,thestring’stone’.Now

goback

andreadthose

last

twosentences

afewmore

times.Thesubtledistinctionbetweenthem

isboththekey

tothepow

erofcellarraysandthesourceofpervasiveconfusion.

Thinkof

astringofmailbox

esalongCstreet.

Assumethey

are

numbered

consecutively.

Then

C(3)is

thethirdmailbox

andC{3}is

themailin

thatbox

.Byitself,Cistheentire

array

ofmailbox

es.TheexpressionC(1:3)isthesubarray

containingthefirstthreemailbox

es.

And

hereis

an

unusualconstruction,with

curlybracesC{1:3}is

acommaseparatedlist,

C{1},C{2},C{3}

Byitself,onthecommandline,

thiswilldothreeassignmentstatements,assigning

thecontents

ofeach

ofthefirstthreemailbox

es,oneatatime,

toans.W

ithmore

curlybraces,{C{1:3}}is

thesameasC(1:3).

Inthecomputerhardware

itself,thereis

adistinction

between

amem

ory

locationwithaparticularad

dress

andthecontents

ofthatlocation.

This

same

distinctionis

preserved

byindexingacellarraywithparentheses

andwithbraces.

Did

youseethe“M

enin

Black”mov

ies?

Inoneofthem

theMIB

headquarters

hasabankofstoragelockers.

Itturnsou

tthateach

locker

containsan

entire

civilization,presumably

withitsow

nlockers.

Attheen

dof

themov

ieitisrevealed

thattheEarthitselfis

astoragelocker

inalarger

civilization.It

ispossible

that

weare

alllivingin

oneelem

entofahugecellarray.

Thebinary

tree

definingMorsecodeis

acellarraywhose

contents

are

char-

actersandother

cellarrays.

Each

cellrepresents

anodein

thetree.

Acell,N,

hasthreeelem

ents,Thefirstelem

ent,N{1},is

astringwithasingle

capitalletter,

X,designatingthenode.

Thesecondelem

ent,

N{2},is

another

cellarray,thedot

branch.Thethirdelem

ent,N{3},is

thedash

branch.Thereare

acouple

ofexcep-

tionalcases.

Theroot

nodedoes

nothaveanassociatedletter,so

itsfirstelem

ent

isanem

pty

string.TheUandRnodes,andtheleafnodes,haveoneortw

oem

pty

cellarraysforbranches.

Inprinciple,wecould

create

theentire

Morsebinary

tree

withasinglegigantic,

butunrealistic,assignmentstatement.

M=

{’’

...

{’E’...

{’I’{’S’{’H’{}

{}}

{’V’

{}

{}}}

...

{’U’{’F’{}

{}}

{}}}

...

{’A’{’R’{’L’{}

{}}

{}}

...

{’W’{’P’{}

{}}

{’J’

{}

{}}}}}

...

{’T’...

250

Chapter19

.Morse

Code

{’N’{’D’

{’B’{}

{}}

{’X’

{}

{}}}

...

{’K’{’C’{}

{}}

{’Y’

{}

{}}}}

...

{’M’{’G’

{’Z’{}

{}}

{’Q’

{}

{}}}

...

{’O’{}

{}}}}}

You

canseethecellarrayswithin

cellarraysandthemanyem

pty

cellarraysat

theleaves.Thisstatementactuallyworks,butitisunreasonable

because

itiserror

pronean

dnearlyim

possible

toextend.Instead,ourfunctionmorse_treebegins

withaheader

functionM

=morse_tree

This

isfollow

edby27

assignmentstatements,tw

elve

atlevel

four.

h=

{’H’

{}

{}};

v=

{’V’

{}

{}};

f=

{’F’

{}

{}};

l=

{’L’

{}

{}};

p=

{’P’

{}

{}};

j=

{’J’

{}

{}};

b=

{’B’

{}

{}};

x=

{’X’

{}

{}};

c=

{’C’

{}

{}};

y=

{’Y’

{}

{}};

z=

{’Z’

{}

{}};

q=

{’Q’

{}

{}};

Eightat

level

three.

s=

{’S’

hv};

u=

{’U’

f{}};

r=

{’R’

l{}};

w=

{’W’

pj};

d=

{’D’

bx};

k=

{’K’

cy};

g=

{’G’

zq};

o=

{’O’

{}

{}};

Fou

ratlevel

two.

i=

{’I’

su};

a=

{’A’

rw};

n=

{’N’

dk};

m=

{’M’

go};

Twoat

level

one.

e=

{’E’

ia};

t=

{’T’

nm};

Page 131: Experiments With MatLab Moled 2011

251

Andfinallyoneassignmentstatementat

level

zero

tocreate

therootnode.

M=

{’’

et};

This

functionis

attheheart

ofallourMorsecodesoftware.

You

cantravel

dow

nthis

tree

byfirstenteringthreecommands.

M=

morse_tree

M=

M{2}

M=

M{3}

You

then

canuse

theup-arrow

onyourkeyboard

torepeatedly

select

andreexecute

thesecommands.

Returningto

thefirstcommandgives

youafreshtree.Executing

thesecondcommandisadotoperation,mov

ingdow

nthetree

totheleft.Executing

thethirdcommandis

adash

operation,mov

ingdow

nthetree

totheright.

For

example,thefivecommands

M=

morse_tree

M=

M{3}

M=

M{2}

M=

M{2}

M=

M{3}

correspondto

theMorsesequence

’-..-’.This

bringsyouto

thenode

’X’

{}

{}

Youhavereached

theXleafofthetree.

Sea

rchingthetree

Returningto

the“Men

inBlack”analogy,

theMorsebinary

tree

isasingle

locker.

When

youop

enthatlocker,you

seeanem

pty

string(because

therootdoes

not

haveaname)

andtw

omore

lockers.

When

youopen

thelocker

ontheleft,yousee

an’E’andtw

omore

lockers.

Now

youhavethreechoices.You

canopen

either

of

thetw

olockersin

theElocker,or

youcangoback

totherootlocker

andopen

the

locker

ontherightto

visittheTlocker.

Rep

eatedly

choosingdifferentlockers,ordifferentbranches

inthetree,corre-

spondsto

traversingthetree

indifferentorders.

Amongthesemanypossibleorders,

twohavestandard

names,“depth

firstsearch”and“breadth

firstsearch”.They

are

show

nin

figures19.2

and19.3

andyoucanseeandhearanim

atedversionswiththe

morse_guiprogram.

Depth

firstsearchvisitseach

branch

assoon

asitsees

it.W

hen

ithasvisited

bothbranches

atanode,

itbacksupto

thefirstnodethathasanavailable

branch.

Figure

19.2

show

stheprogress

ofdepth

firstorder

upto

nodeW.

EI

SH

VU

FA

RL

W

Nothingto

therightofWhasyet

beenvisited.

252

Chapter19

.Morse

Code

E

I

S

HV

U

F

A

R

L

W

..

..

Figure

19.2.A

depth

firstsearchin

progress.

Thenodes

are

visitedfrom

leftto

right.

Breadth

firstsearch

takes

onestep

alongeach

branch

atanodebefore

itcontinues.Theresultisatopto

bottom

search,much

likereadingEnglish

language

text.

Figure

19.3

show

sthebreadth

firstorder

upto

nodeW.

ET

IA

NM

SU

RW

Nothingbelow

Whasyet

beenvisited.

Dep

thfirstsearchusesadata

structure

know

nasastack.

Hereis

acode

segmentwithastack

thatsimply

displaysthenodes

ofthetree

indepth

firstorder.

S=

{morse_tree};

while~isempty(S)

N=

S{1};

S=

S(2:end);

if

~isempty(N)

fprintf(’%s’,N{1})

S=

{N{2}

N{3}

S{:}};

end

end

fprintf(’\n’)

Thestack

Sis

acellarray.

Initially,

ithasonecellcontainingthetree.Thewhile

Page 132: Experiments With MatLab Moled 2011

253

ET

IA

NM

SU

RW

..

..

Figure

19.3.A

breadth

firstsearchin

progress.

Thenodes

are

visitedfrom

topto

bottom.

loopcontinues

aslongas

thestack

isnotem

pty.W

ithin

thebodyoftheloopa

nodeisremoved

from

thetopofthestack

andthestack

shortened

byoneelem

ent.

Ifthenodeisnotem

pty,thesingle

character

representingthenodeisdisplayedand

twonew

nodes,thedotanddash

branches,are

inserted

into

thetopofthestack.

Thetraversalvisitsrecentlydiscoverednodes

before

itreturnsto

older

nodes.

Breadth

firstsearchusesadata

structure

know

nas

aqueue.

Hereis

another

codesegment,thistimewithaqueue,

thatdisplaysthenodes

ofthetree

inbreadth

firstorder.

Q=

{morse_tree};

while~isempty(Q)

N=

Q{1};

Q=

Q(2:end);

if

~isempty(N)

fprintf(’%s’,N{1})

Q=

{Q{:}

N{2}

N{3}};

end

end

fprintf(’\n’)

Thiscodeissimilarto

thestack

code.

Thedistinguishingfeature

isthatnew

nodes

254

Chapter19

.Morse

Code

are

inserted

attheend,rather

thatthebeginningofthequeue.

Aqueueisem

ployinga“First

In,First

Out”,or

FIFO,strategy,

whileastack

isem

ployinga“Last

In,First

Out”,or

LIFO,strategy.

Aqueueis

likealineat

agrocery

store

orticket

office.Customersat

thebeginningofthelineareserved

first

andnew

arrivalswaitattheendoftheline.

Withastack,new

arrivalscrow

din

at

thestart

oftheline.

Ourstack

andqueuecodes

arenotrecursive.

They

simply

loopuntilthereis

nomore

workto

bedone.

Hereis

differentap

proach

thatem

ploysrecursionto

do

adepth

firstsearch.Actually,

this

does

involveahidden

stack

because

computer

system

ssuch

asMatlabuse

stacksto

managerecursion.

functiontraverse(M)

if

nargin

==

0

M=

morse_tree;

%Initial

entry.

end

if

~isempty(M)

disp(M{1})

traverse(M{2})

%Recursive

calls.

traverse(M{3})

end

end%

traverse

Decodeanden

code

Decodingis

theprocess

oftranslatingdots

anddashes

into

text.

Encodingis

the

reverse.W

ithou

rbinary

tree,decodingis

easier

thanencodingbecause

thedots

anddashes

directlydeterminewhichlinksto

follow

.Hereisafunctionthatdecodes

onecharacter’s

worth

ofdots

anddashes.Thefunctionreturnsan

asterisk

ifthe

inputdoes

notcorrespondto

oneofthe26

lettersin

thetree.

functionch

=decode(dd)

M=

morse_tree;

fork

=1:length(dd)

ifdd(k)

==

’.’

M=

M{2};

elseifdd(k)==

’-’

M=

M{3};

end

ifisempty(M)

ch=

’*’;

return

end

end

ch

=M{1};

end%

decode

Page 133: Experiments With MatLab Moled 2011

255

Encodingis

alittle

more

work

because

wehaveto

searchthetree

untilwefind

thedesired

letter.Hereisafunctionthatem

ploysdepth

firstsearchto

encodeon

echaracter.

Astack

ofdots

anddashes

isbuiltupduringthesearch.

Again,an

asteriskis

returned

iftheinputcharacter

isnotin

thetree.

functiondd

=encode(ch)

S=

{morse_tree};

D=

{’’};

while~isempty(S)

N=

S{1};

dd

=D{1};

S=

S(2:end);

D=

D(2:end);

if

~isempty(N)

if

N{1}

==

ch;

return

else S=

{N{2}

N{3}

S{:}};

D=

{[dd

’.’]

[dd

’-’]

D{:}};

end

end

end

dd

=’*’;

end%

encode

Thesetw

ofunctionsarethecore

ofthedecodingandencodingaspectofmorse_gui.

Exten

sion

ET

IA

NM

SU

RW

DK

GO

HV

PJ

BX

CY

ZQ

Ö×

54

2+

À1

67

Ñ8

90

?.

@−

;,

:

Figure

19.4.TheMorsetree

extended

twolevels

toaccommodate

digits,

punctuation,andnon-E

nglishcharacters.

256

Chapter19

.Morse

Code

Abinary

tree

withfourlevelshas25−

1=

31nodes,countingtheroot.

Our

morse_treehasarootandon

ly26

other

nodes.So,thereare

fourem

pty

spots.

You

canseethem

onthedash

branches

ofU

andR

andon

both

branches

ofO.So

far,

ourdefinitionofMorsecodedoes

notprovideforthefoursequences

..--

.-.-

---.

----

How

should

thesebedecoded?Wealsowan

tto

addcodes

fordigitsan

dpunctuation

marks.

And,it

wou

ldbeniceto

provideforatleast

someof

thenon-E

nglish

charactersrepresentedwithumlauts

andother

diacriticalmarks.

Morsecodewasinvented100years

before

moderncomputers.Today,alpha-

bets,

keyboards,

character

sets

andfonts

vary

from

countryto

countryan

deven

from

computerto

computer.

Ourfunction

morse_table_extended

extendsthetree

twomore

levelsandad

ds10digits,

8punctuationcharacters,

and

7non-E

nglish

charactersto

the26charactersin

theoriginalmorse_table.Figure

19.4

show

stheresult.Theextendbuttonin

morse_guiaccessesthis

extension.

Someoftheissues

involved

inrepresentingtheseadditionalcharactersare

pursued

intheexercises.

Morseco

detable

Wepromised

thatwewou

ldnotuse

atable

todefineMorsecode.

Everythinghas

beenbasedonthebinary

tree.W

hen

anactualtable

isdesired

wecangenerate

onefrom

thetree.Ourfunctionisnamed

morse_codeanditem

ploystherecu

rsive

algorithm

traversefrom

theprevioussection.

Therecursion

carriesalongthe

emergingtable

Candagrowingstringddofdots

anddashes.

Indexinginto

thetable

isbasedupontheASCII

codeforcharacters.

The

ASCIIstandard

isan7-bitcodethatisthebasisforcomputerrepresentationoftext.

Seven

bitsprovidefor27

=128characters.

Thefirst32oftheseare

nonprinting

charactersthatwereoriginallyused

forcontrolofteletypes

and

are

now

largely

obsolete.Theremaining96

arethe52

upper

andlower

case

lettersoftheEnglish

alphabet,10digits,

and

32punctuation

marks.

InMatlab

thefunctionchar

convertsanumeric

valueto

acharacter.Forexample

char(65)

ans=

’A’

Thefunctiondoubleconvertsacharacter

toafloatingpointnumber

andthefunc-

tionuint8converts

acharacter

toanunsigned

8-bitinteger.Either

ofthesecanbe

usedasanindex.For

example

double(’A’)

ans=

65

Page 134: Experiments With MatLab Moled 2011

257

Acomputerbyte

is8bitsan

dso

theASCII

standard

isreadilyextended

byan

other

128characters.

Theactualgraphic

printedforsomeof

thesecharactersmay

vary

from

countryto

countryandfrom

fontto

font.

Ourfunctionmorse_codeproducesatableofboth

ASCIIandMorsecodefrom

either

morse_treeormorse_tree_extended.Therecu

rsivetraversealgorithm

isusedforthedepth

firstsearch.ASCII

codes

are

usedasindices

into

a256-element

cellarrayofdots

anddashes.Thesearchinsertsonly

26or51elem

ents

into

the

array,so

afinalstep

createsaprintable

table.

functionC

=morse_code(C,M,dd)

%MORSE_CODE

%C

=morse_code

%C

=morse_code(morse_tree)

%C

=morse_code(morse_tree_extended)

if

nargin

<3

%Choose

binary

tree

if

nargin

==

0

M=

morse_tree;

else M=

C;

end

C=

cell(256,1);

%The

temporary

code

table

dd

=’’;

%dots

and

dashes

end

if

~isempty(M)

%Depth

first

search

if

~isempty(M{1})

C{double(M{1})}=

dd;

%Use

ASCII

value

as

an

index

end

C=

morse_code(C,M{2},[dd

’.’]);

%Recursive

call

C=

morse_code(C,M{3},[dd

’-’]);

%Recursive

call

end

if

nargin

<3

%Final

processing,

convert

to

char.

c=

char(C{:});

k=

find(c(:,1)

~=

’’);

%Find

the

nonblank

entries.

b=

blanks(length(k))’;

C=

[char(k)

bb

int2str(k)

bb

char(C{k})];

end

Theou

tputfrom

morse_code

isthefollow

ing26lines.

A65

.-

B66

-...

258

Chapter19

.Morse

Code

C67

-.-.

D68

-..

E69

.

F70

..-.

G71

--.

H72

....

I73

..

J74

.---

K75

-.-

L76

.-..

M77

--

N78

-.

O79

---

P80

.--.

Q81

--.-

R82

.-.

S83

...

T84

-

U85

..-

V86

...-

W87

.--

X88

-..-

Y89

-.--

Z90

--..

You

should

run

morse_code(morse_tree_extended)

toseewhatoutputis

generatedon

yourcomputer.

Referen

ces

[1]W

ikipedia

article

onMorsecode.

See

thecomplete

Morsecodetree

attheend

ofthearticle.

http://en.wikipedia.org/wiki/Morse_code

Rec

ap

%%

Morse

Code

Chapter

Recap

%This

is

an

executable

program

that

illustrates

the

statements

%introduced

in

the

Morse

Code

Chapter

of

"Experiments

in

MATLAB".

%You

can

access

it

with

% %morse_recap

%edit

morse_recap

Page 135: Experiments With MatLab Moled 2011

259

%publish

morse_recap

% %Related

EXM

programs

% %morse_gui

%morse_tree

%morse_tree_extended

%morse_code

%%Cell

Arrays

C=

{’A’,’rolling’,’stone’,’gathers’,’momemtum’,’.’}

C{3}

C(3)

C(1:3)

C{1:3}

{C{1:3}}

%%Create

aMorse

Tree

%An

absurd

statement.

For

abetter

way,

see

morse_tree.

M=

{’’

...

{’E’...

{’I’{’S’{’H’{}

{}}

{’V’

{}

{}}}

...

{’U’{’F’{}

{}}

{}}}

...

{’A’{’R’{’L’{}

{}}

{}}

...

{’W’{’P’{}

{}}

{’J’

{}

{}}}}}

...

{’T’...

{’N’{’D’{’B’{}

{}}

{’X’

{}

{}}}

...

{’K’{’C’{}

{}}

{’Y’

{}

{}}}}

...

{’M’{’G’{’Z’{}

{}}

{’Q’

{}

{}}}

...

{’O’{}

{}}}}}

%%Follow

’-..-’

M=

morse_tree

M=

M{3}

M=

M{2}

M=

M{2}

M=

M{3}

%%Depth

first,

with

astack.

S=

{morse_tree};

while~isempty(S)

N=

S{1};

S=

S(2:end);

if

~isempty(N)

260

Chapter19

.Morse

Code

fprintf(’%s’,N{1})

S=

{N{2}

N{3}

S{:}};

end

end

fprintf(’\n’)

%%

Breadth

first,

with

aqueue.

Q=

{morse_tree};

while~isempty(Q)

N=

Q{1};

Q=

Q(2:end);

if

~isempty(N)

fprintf(’%s’,N{1})

Q=

{Q{:}

N{2}

N{3}};

end

end

fprintf(’\n’)

%%

Recursive

traversal.

%function

traverse(M)

%if

nargin

==

0

%M=

morse_tree;

%Initial

entry.

%end

%if

~isempty(M)

%disp(M{1})

%traverse(M{2})

%Recursive

calls.

%traverse(M{3})

%end

%end

%traverse

%%

ASCII

character

set

k=

reshape([32:127

160:255],32,[])’;

C=

char(k)

txt=

text(.25,.50,C,’interp’,’none’);

set(txt,’fontname’,’LucidaSansTypewriter’)

Exe

rcises

19.1

Greetings.W

hatdoes

this

say?

.....

.-..

.-..

---

.--

---

.-.

.-..

-..

19.2

Email.Use

theextendbuttonandtranslate

box

inmorse_guito

translate

you

rem

ailad

dress

into

Morsecode.

Page 136: Experiments With MatLab Moled 2011

261

19.3

dash.W

hydidn’t

Iuse

anunderscore,’_’,insteadofaminussign,’-’,to

representadash?

19.4

Note.W

hatmusicalnote

isusedbythesoundfeature

inmorse_gui?

19.5

Reverse

order.Findthis

statementin

functiondepthin

morse_gui.

S=

{N{2}

N{3}

S{:}};

WhathappensifyouinterchangeN{2}andN{3}like

this?

S=

{N{3}

N{2}

S{:}};

19.6

Exten

d.Usingthetree

attheendoftheW

ikipedia

article,addmore

characters

tomorse_code_extended.Ifyou

livein

alocale

thathasnon-E

nglish

charactersin

thealphabet,besure

toincludethem

.

19.7

Fourdashes.W

hydoes

thecharacter

withMorsecode’----’cause

aunique

diffi

cultyin

morse_code_extended?

19.8

YouTube.

Checkout“Morsecode”

onYouTube.

Besure

tolisten

tothe

“Morsecodesong”.W

howinstheMorsecodeversustextingcontest

onJay

Leno’s

Ton

iteshow

?

19.9

Trinary.

Whatdoes

this

function

do?

Whyis

itnamed

trinary.

What

determines

how

longitruns?

Whatcausesitto

term

inate?W

hyistheifstatement

necessary?

Modifytheprogram

tomakeit

use

adepth

firstsearch.Modifythe

program

tomakeitwork

withmorse_tree_extended.

functiontrinary

T=

[0

00

0];

Q=

{morse_tree};

whileany(T(1,:)<

2)

p=

T(1,:);

y=

polyval(p,3);

if

~isempty(Q{1})

fprintf(’%s

%d%d%d%d

%2d\n’,Q{1}{1},p,y)

Q=

{Q{2:end}

Q{1}{2}

Q{1}{3}};

else Q=

{Q{2:end}

{}

{}};

end

T=

[T(2:end,:);

[T(1,2:end)

1];

[T(1,2:end)

2]];

end

end%

trinary

19.10Cellarrays.Let

262

Chapter19

.Morse

Code

C=

{’A’

’rolling’

’stone’

’gathers’

’momentum’

’.’}

Explain

whyeach

ofthefollow

ingdoes

whatitdoes.

C’

char(C)

size(C)

size(char(C))

double(char(C))

upper(C)

C(end)

C{end}

C{3}(3)

fliplr(C)

[C{:}]

C(5:7)=

{’no’

’moss’

’.’}

19.11Fonts.Experim

entwithvariousfonts.See

theW

ikiped

iaarticleontheASCII

character

set.

Youcangenerate

aprintable

character

table

inMatlabwith

k=

reshape([32:127

160:255],32,[])’;

C=

char(k)

Thefirsthalfof

this

table

isstandard,butthesecondhalfdep

endsuponthefonts

you

areusing.

You

can

changefonts

inthecommand

window

byaccessingthe

“File”

menu,then

selecting“P

references”

and“F

onts”.Highlightthedesktopcode

fontanduse

theupan

ddow

narrow

keys.

Inmyopinionthebestfontforthe

Matlabcommandwindow

isLucidaSansTypew

riter

You

canalsodisplaythecharacter

table

inthefigure

window

with

txt=

text(.25,.50,C,’interp’,’none’);

Tochangedisplayfonts

inthefigure

window

,trycommandsliketheseworkonyou

rcomputer.

set(txt,’fontname’,’LucidaSansTypewriter’)

set(txt,’fontname’,’CourierNew’)

set(txt,’fontname’,’ComicSansMS’)

set(txt,’fontname’,’Wingdings’)

set(txt,’fontname’,’GiGi’)

Use

thefontnames

available

under

thecommandwindow

preferences.

Page 137: Experiments With MatLab Moled 2011

Chapter20

Music

Whatdoes

12√ 2

have

todowithmusic?

Inthetheory

ofmusic,

anoctave

isanintervalwithfrequencies

thatrange

over

afactorof

two.

Inmost

Western

music,

anoctaveis

divided

into

twelve

semitones

withequalfrequency

ratios.

Since

twelvesemitones

comprise

afactorof

two,onesemitoneis

afactorof

12√ 2

.Andbecause

this

quantity

occurs

sooften

inthis

chapter,

let

σ=

12√ 2

OurMatlabprogramsuse

sigma=

2^(1/12)

=1.059463094359295

Thinkofσasanim

portantmathem

aticalconstant,likeπandφ.

Key

board

Figure

20.1

show

sourminiature

pianokeyboard

with25

keys.

This

keyboard

has

twooctaves,withwhitekeyslabeled

CD

...

GA

B,plusanother

Ckey.Counting

bothwhitean

dblack,therearetw

elveskeysin

each

octave.

Thefrequency

ofeach

key

isasemitoneaboveandbelow

itsneighbors.Each

black

key

canberegarded

aseither

thesharp

ofthewhitebelow

itor

theflatofthewhiteaboveit.Sothe

black

key

betweenCandDis

bothC�andD�.

Thereis

noE�/F�orB�/C�.

Aconventionalfullpianokeyboard

has88keys.

Seven

complete

octaves

ac-

countfor7×

12=

84keys.

Thereare

threeadditionalkeysatthelower

left

and

onead

ditionalkey

attheupper

end.Iftheoctaves

are

numbered

0through8,then

Copyright

c ©2011CleveMoler

Matlab

R ©is

aregisteredtradem

ark

ofMath

Works,

Inc.

TM

October

4,2011

263

264

Chapter20

.Music

Figure

20.1.Miniature

pianokeyboard.

Figure

20.2.Middle

C.

akey

letter

follow

edbyanoctavenumber

specifies

auniquekey.In

this

notation,

twoim

portantkeysare

C4andA4.TheC4key

isnearthecenterof

thekeyboard

andso

isalsoknow

nasmiddle

C.A

pianois

usuallytuned

sothatthefrequency

oftheA4key

is440Hz.

C4is

ninekeysto

theleft

ofA4so

itsfrequen

cyis

C4=

440σ−9≈

261.6256

Hz

OurEXMprogram

pianoexusesC4asthecenterof

its25keys,so

thenumber

Page 138: Experiments With MatLab Moled 2011

265

rangeis-12:12.Thestatement

pianoex(0)

generatesan

dplaysthesoundfrom

asinewavewithfrequency

C4.Theresulting

visualdisplayis

show

nin

figure

20.2.

Thisforloopplaysatw

ooctavechromaticscalestartingcoveringall25

notes

onourminiature

keyboard.

forn

=-12:12

pianoex(n)

end

DoReMi

Oneofthefirstsongsyoulearned

tosingwas

DoReMiFaSoLaTiDo

Ifyoustart

atC4,youwould

besingingthemajorscale

inthekey

ofC.Thisscale

isplayed

onapianousingon

lythewhitekeys.

Thenotesare

notequallyspaced.

Most

ofthestepsskip

over

black

keysan

dso

are

twosemitones.

Butthesteps

betweenMiandFaandTiandDoare

thestepsfrom

Eto

FandBto

C.Thereare

nointerveningblack

keysandso

thesestepsare

only

onesemitone.

Interm

sof

σ,

theC-m

ajorscale

is

σ0σ2σ4σ5σ7σ9σ11σ12

Youcanplaythis

scale

onourminiature

keyboard

with

forn

=[0

24

57

911

12]

pianoex(n)

end

Thenumber

ofsemitones

betweenthenotesis

given

bythevector

diff([0

24

57

911

12])

=[2

21

22

21]

Thesequence

offrequencies

inourmost

commonscale

issurprising.W

hyare

there8notesin

theC-m

ajorscale?W

hydon’tthenotesin

thescale

haveuniform

frequency

ratios?

For

thatmatter,whyis

theoctavedivided

into

12semitones?

Thenotesin

“DoReMe”are

sofamiliarthatwedon’t

even

ask

ourselves

these

questions.

Are

theremathem

aticalexplanations?

Idon’t

havedefinitiveansw

ers,

butIcanget

somehints

bylookingatharm

ony,

chords,

andtheratiosofsm

all

integers.

Vibrationsandmodes

Musicalinstruments

create

soundthroughtheactionofvibratingstringsorvibrat-

ingcolumnsofair

that,

inturn,produce

vibrationsin

thebodyoftheinstrument

266

Chapter20

.Music

Figure

20.3.Thefirstninemodes

ofavibratingstring,

andtheirweightedsum.

andthesurroundingair.Mathem

atically,

vibrationscanbemodeled

byweighted

sumsofcharacteristicfunctionsknow

nasmodes

oreigenfunctions.

Differentmodes

vibrate

atdifferentcharacteristicfrequen

cies

oreigenvalues.Thesefrequen

cies

are

determined

byphysicalparameterssuch

asthelength,thicknessandtensionin

astring,orthegeometry

oftheaircavity.

Short,thin,tightlystretched

stringshave

highfrequencies,whilelong,thick,looselystretched

stringshavelow

frequencies.

Thesimplest

model

isaone-dim

ensionalvibratingstring,held

fixed

atits

ends.

Theunitsofthevariousphysicalparameterscanbechosenso

thatthelength

ofthestringis

2π.Themodes

are

then

simply

thefunctions

v k(x)=

sinkx,k=

1,2,...

Each

ofthesefunctionssatisfythefixed

endpointconditions

v k(0)=

v k(2π)=

0

Thetime-dep

endentmodalvibrationsare

uk(x,t)=

sinkxsinkt,

k=

1,2,...

andthefrequen

cyissimply

theinteger

k.(T

wo-andthree-dim

ensionalmodelsare

much

more

complicated,butthis

one-dim

ensionalmodel

isallweneedhere.)

OurEXMprogram

vibrating_stringprovides

adynamic

view.Figure

20.3

isasnapshotshow

ingthefirstninemodes

andtheresultingwavetravelingalong

thestring.Anexercise

asksyou

tochangethecoeffi

cients

intheweightedsum

toproduce

differentwaves.

Lissajousfigures

Lissajousfiguresprovidesomeinsightinto

themathem

aticalbehav

iorof

musical

chords.

Twodim

ensionalLissajousfiguresare

plots

oftheparametriccurves

x=

sin(at+α),

y=

sin(bt+β)

Page 139: Experiments With MatLab Moled 2011

267

Figure

20.4.x=

sint,y=

sin3/2t,z=

sin5/4

t.

Figure

20.5.x=

sint,y=

sinσ7t,z=

sinσ4t.

Threedim

ensionalLissajousfiguresare

plots

oftheparametriccurves

x=

sin(at+α),

y=

sin(bt+β),

z=

sin(ct+γ)

Wecansimplify

ourgraphicsinterface

byjust

considering

x=

sint,

y=

sinat

268

Chapter20

.Music

Figure

20.6.x=

sint,y=

sin5/4t.

Figure

20.7.x=

sint,y=

sinσ4t.

and

x=

sint,

y=

sinat,

z=

sinbt

Theexample

witha=

3/2

andb=

5/4

show

nin

figure

20.4.is

producedbythe

defaultsettingsin

ourexmprogram

lissajous.Thisprogram

allow

syou

tochange

Page 140: Experiments With MatLab Moled 2011

269

aandbbyenteringvalues

inedit

boxesonthefigure.Enteringb

=0resultsin

atw

odim

ensionalLissajousfigure

liketheoneshow

nin

figure

20.6.

Thesimplest,“cleanest”

Lissajousfiguresresultwhen

theparametersaandb

are

ratiosof

smallintegers.

a=

p q,b=

r s,

p,q,r,s

=sm

allintegers

This

isbecause

thethreefunctions

x=

sint,

y=

sinp qt,

z=

sinr st

allreturn

tozero

when

t=

2mπ,

m=

lcm(q,s)

wherelcm(q,s)istheleast

commonmultiple

ofqands.

When

aandbare

fractions

withlargenumerators

anddenominators,thecurves

oscillate

more

rapidly

andtake

longer

toreturn

totheirstartingvalues.

Intheextrem

esituationwhen

aandbare

irrational,thecurves

never

return

totheirstartingvalues

and,in

fact,eventuallyfilluptheentire

square

orcu

be.

Wehaveseen

thatdividingtheoctaveinto

12equalsizedsemitones

resultsin

frequencies

thatarepow

ersofσ,anirrationalvalue.

TheEkeyan

dGkeysare

four

andseven

semitones

aboveC,so

theirfrequen

cies

are

sigma^4

=1.259921049894873

sigma^7

=1.498307076876682

Theclosest

fractionswithsm

allnumeratoranddenominatorare

5/4

=1.250000000000000

3/2

=1.500000000000000

This

iswhywechose

5/4an

d3/2forourdefault

parameters.

Iftheirrational

pow

ersof

sigmaare

usedinstead,theresultsare

figures20.5

and20.7.

Infact,

thesefiguresare

merelytheinitialsnapshots.If

wewereto

lettheprogram

keep

running,theresultswould

notbepleasant.

HarmonyandIntonation

Harm

onyisanelusiveattribute.Dictionary

definitionsinvolveterm

slike“pleasing”,

“congruent”,“fittingtogether”.Forthepurposes

ofthischapter,let’ssaythattw

oormore

musicalnotesare

harm

oniousiftheratiosof

theirfrequencies

arerational

270

Chapter20

.Music

numberswithsm

allnumeratoran

ddenominator.

Thehumanearfindssuch

notes

fittogether

inapleasingmanner.

Strictlyspeaking,amusicalchord

isthreeormore

notessounded

simultane-

ously,

buttheterm

canalsoapply

totw

onotes.

Withthesedefinitions,

chords

madefrom

ascale

withequalsemitones

are

notexactly

harm

onious.

Thefrequency

ratiosare

pow

ersof

σ,whichis

irrational.

Tuningamusicalinstrumentinvolves

adjustingitsphysicalparametersso

thatitplaysharm

oniousmusicbyitselfan

din

conjunctionwithother

instruments.

Tuningapianois

adiffi

cult

process

thatis

doneinfrequently.

Tuningaviolinora

guitarisrelativelyeasy

andcanbedoneeven

duringbreaksin

aperform

ance.The

humansingingvoice

isan

instrumentthatcanundergocontinuousretuning.

For

hundredsof

years,musictheory

hasincluded

thedesignofscalesan

dthe

tuningofinstruments

toproduce

harm

oniouschords.

Ofthemanypossibilities,

let’sconsider

only

two–equaltemperamen

tandjust

intonation.

Equaltemperamentistheschem

ewe’ve

beendescribingso

farin

thischapter.

Thefrequency

ratiobetweenthenotesin

achord

canbeexpressed

interm

sof

σ.

Tuninganinstrumentto

haveequaltemperamentisdoneonce

andforall,without

regard

tothemusicthatwillbeplayed.A

single

base

note

ischosen,usuallyA=

440Hz,

andthatdetermines

thefrequency

ofalltheother

notes.

Pianosare

almost

alwaystuned

tohaveequaltemperament.

Just

intonationmodifies

thefrequen

cies

slightlyto

obtain

more

strictly

har-

moniouschords.

Thetuninganticipatesthekey

ofthemusicab

outto

beplayed.

Barbershopquartetsandacapella

choirscanob

tain

just

intonationdynamically

duringaperform

ance.

Hereis

aMatlabcodesegmentthatcomparesequaltemperamentwithjust

intonationfrom

astrictly

numericalpointof

view.Equaltemperamentis

defined

byrepeatedpow

ersofσ.Just

intonationis

defined

byasequence

offractions.

sigma=

2^(1/12);

k=

(0:12)’;

equal=

sigma.^k;

num=

[1

16

96

54

73

85

715

2]’;

den=

[1

15

85

43

52

53

48

1]’;

just=

num./den;

delta=

(equal

-just)./equal;

T=

[k

equal

num

den

just

delta];

fprintf(’%8d%12.6f%7d/%d%10.6f%10.4f\n’,T’)

kequal

just

delta

01.000000

1/1

1.000000

0.0000

11.059463

16/15

1.066667

-0.0068

21.122462

9/8

1.125000

-0.0023

31.189207

6/5

1.200000

-0.0091

41.259921

5/4

1.250000

0.0079

Page 141: Experiments With MatLab Moled 2011

271

51.334840

4/3

1.333333

0.0011

61.414214

7/5

1.400000

0.0101

71.498307

3/2

1.500000

-0.0011

81.587401

8/5

1.600000

-0.0079

91.681793

5/3

1.666667

0.0090

10

1.781797

7/4

1.750000

0.0178

11

1.887749

15/8

1.875000

0.0068

12

2.000000

2/1

2.000000

0.0000

Thelast

columnin

thetable,delta,istherelativedifference

betweenthetw

o.We

seethatdeltaisless

thanonepercent,exceptforonenote.Butthemore

important

considerationis

how

themusicsounds.

Chords

.

Figure

20.8.Dissonace

andbeats

betweentwoadjacentwhole

notes.

Chordsare

twoormore

notesplayedsimultaneously.

Withacomputerkey-

board

andmouse,wecan’t

clickonmore

thanon

ekey

atatime.

Sochordsare

producedwithpianoexbyselectingthetoggle

switches

labeled

1through12.The

switch

labeled

0is

alway

sselected

.Figure

20.8

show

sthevisualoutputgeneratedwhen

pianoexplaysachord

involvingtw

oadjacentwhitekeys,

inthis

case

CandD.Youcansee,

andhear,

the

phenomenonknow

nasbeating.

Thisoccurs

when

tones

withnearlyequalfrequencies

alternate

betweenadditivereinforcem

entan

dsubtractivecancellation.Therelevant

trig

identity

is

sinat+sinbt

=sina+b

2tcosa−

b

2t

272

Chapter20

.Music

Thesum

oftw

onotesisanote

withtheaverageofthetw

ofrequencies,modulated

byacosineterm

invo

lvingthedifference

ofthetw

ofrequencies.Theplayers

inan

orchestratuneupbylisten

ingforbeats

betweentheirinstruments

andareference

instrument.

Themost

importantthree-note

chord,ortriad,istheC

majorfifth.IfCisthe

lowest,

orroot,

note,thechord

isC-E-G.In

just

intonation,thefrequency

ratios

are

1:5 4:3 2

Theseare

theparameter

values

forourdefault

Lissajousfigure,show

nin

figure

20.4.Figures20.9

and20.10show

thevisualou

tputgeneratedwhen

pianoexplays

aC

majorfifthwithjust

intonationan

dwithequaltemperament.

Youcanseethat

thewaveform

sin

theoscilloscopeare

different,

butcanyouhearanydifference

inthesoundgenerated?

Figure

20.9.C

majorfifthwithjust

intonation.

Syn

thesizingMusic

Ourpianoexprogram

isnotapow

erfulmusicsynthesizer.Creatingsuch

aprogram

isahugeundertaking,way

beyondthescopeofthischapteror

thisbook

.Wemerely

wantto

illustrate

afew

oftheinterestingmathem

aticalconcepts

involved

inmusic.

Thecore

ofthepianoexisthecodethatgeneratesavectoryrepresentingthe

amplitudeofsoundasafunctionoftimet.Hereis

theportionof

thecodethat

handlesequaltemperament.

Thequantity

chordiseither

asingle

note

number,or

avectorlike[0

47]withthesettingsof

thechord

toggles.

sigma=

2^(1/12);

Page 142: Experiments With MatLab Moled 2011

273

Figure

20.10.C

majorfifthwithequaltemperamen

t.

C4

=440*sigma^(-9);

fs

=44100;

t=

0:1/fs:T;

y=

zeros(size(t));

forn

=chord

hz

=C4

*sigma^n;

y=

y+

sin(2*pi*hz*t);

end

y=

y/length(chord);

Hereisthecorrespondingportionofcodeforjust

intonation.Thevectorrofratios

isrepeatedafew

times,scaledbypow

ersof2,

tocoverseveraloctaves.

sigma=

2^(1/12);

C4

=440*sigma^(-9);

fs

=44100;

t=

0:1/fs:T;

r=

[1

16/15

9/8

6/5

5/4

4/3

7/5

3/2

8/5

5/3

7/4

15/8];

r=

[r/2

r2*r

4];

y=

zeros(size(t));

forn

=chord

hz

=C4

*r(n+13);

y=

y+

sin(2*pi*hz*t);

end

y=

y/length(chord);

Asm

allexample

ofwhatafullmusicsynthesizer

would

soundlikeis

provided

by

the“piano”toggle

onpianoex.This

synthesizer

usesasingle

sample

ofan

actual

274

Chapter20

.Music

Figure

20.11.C

majorfifthchord

withsimulatedpiano.

pianoplayingmiddle

C.Thissample

isloaded

duringtheinitializationofpianoex,

S=

load(’piano_c.mat’);

middle_c=

double(S.piano_c)/2^15;

set(gcf,’userdata’,middle_c)

Afunctionfrom

theMatlabSignalProcessingToolbox

isthen

usedto

generate

notesat

differentfrequencies.

middle_c=

get(gcf,’userdata’);

fs

=44100;

t=

0:1/fs:T;

y=

zeros(size(t));

forn

=chord

y=

y+

resamplex(middle_c,2^(n/12),length(y));

end

Figure

20.11displaysthepianosimulationoftheC

majorfith

chord.You

can

seethatthewaveform

ismuch

richer

thantheones

obtained

from

superpositionof

sinewaves.

Further

Rea

ding,andViewing

Thiswon

derfulvideo

show

saperform

ance

ofthe“DoReMi”

songfrom

“TheSound

ofMusic”

intheAntw

erpCentralRailway

Station.(I

hopetheURLpersists.)

http://www.youtube.com/watch?v=7EYAUazLI9k

Wikiped

iahashundredsofarticlesonvariousaspects

ofmusictheory.Hereisone:

Page 143: Experiments With MatLab Moled 2011

275

http://en.wikipedia.org/wiki/Music_and_mathematics

Wikipedia

onLissajouscurves:

http://en.wikipedia.org/wiki/Lissajous_curve

Rec

ap

%%Music

Chapter

Recap

%This

is

an

executable

program

that

illustrates

the

statements

%introduced

in

the

Music

Chapter

of

"Experiments

in

MATLAB".

%You

can

access

it

with

% %music_recap

%edit

music_recap

%publish

music_recap

% %Related

EXM

programs

% %pianoex

%%Size

of

asemitone,

one

twelth

of

an

octave.

sigma=

2^(1/12)

%%Twelve

pitch

chromatic

scale.

forn

=0:12

pianoex(n)

end

%%C

major

scale

forn

=[0

24

57

911

12]

pianoex(n)

end

%%Semitones

in

Cmajor

scale

diff([0

24

57

911

12])

%%Equal

temperament

and

just

intonation

[sigma.^(0:12)

116/15

9/8

6/5

5/4

4/3

7/5

3/2

8/5

5/3

7/4

15/8

2]’

%%C

major

fifth

chord,

equal

temperament

and

just

temperament

276

Chapter20

.Music

[sigma.^[04

7]

15/4

3/2]’

Exe

rcises

20.1

Strings.TheW

ikiped

iapage

http://en.wikipedia.org/wiki/Piano_key_frequencies/

hasatableheaded

“VirtualKeyboard”thatshow

sthefrequencies

ofthepianokeys

aswellasfivestringinstruments.Theopen

stringviolinfrequencies

aregiven

by

v=

[-14

-7

07]’

440*sigma.^v

Whatare

thecorrespondingvectors

fortheother

fourstringinstruments?

20.2

Vibratingstring.

Invibrating_string.m,findthestatement

a=

1./(1:9)

Changeitto

a=

1./(1:9).^2

or

a=

1./sqrt(1:9)

Also,changetheloopcontrol

fork

=1:9

to

fork

=1:2:9

or

fork

=1:3:9

Whateff

ectdothesechanges

haveon

theresultingwave?

20.3

Comet.Try

this:

a=

2/3;

b=

1/2;

Page 144: Experiments With MatLab Moled 2011

277

tfinal=

12*pi;

t=

0:pi/512:tfinal;

x=

sin(t);

y=

sin(a*t);

z=

sin(b*t);

comet3(x,y,z)

Whydid

Ichoose

this

particularvalueoftfinal?

How

does

this

tfinaldep

end

uponaandb?

20.4

DissonantLissajous.

Whatis

theLissajousfigure

correspondingto

twoor

threeadjacentkeys,

oradjacentwhitekeys,

onthepianokeyboard?

20.5Irrationalbiorhythms.

Thebiorhythmsdescribed

inour“C

alendars

andClocks”

chapterarebasedonthepremisethatourlives

are

governed

byperiodicfunctionsof

timewithperiodsof

23,28and33day

s.W

hatistheeff

ectofrevisingbiorhythms.m

sothattheperiodsare

irrationalvalues

nearthese?

20.6

Just

intonation.

Withjust

intonation,theratiosof

frequencies

ofadjacent

notesare

nolonger

equalto

σ.W

hataretheseratios?

20.7

Rationalintonation.Matlabalm

ost

hasthecapabilityto

discoverjust

intona-

tion.TheMatlabfunctionratcomputesrationalapproxim

ations.

Forexample,

thefollow

ingstatementcomputesthenumeratornanddenominatordin

arational

approxim

ationof

π.

[n,d]=

rat(pi)

n=

355

d=

113

This

gives

ustheapproxim

ationπ

≈355/1

13,whichis

accurate

to7significant

figures.

For

aless

accurate

approxim

ation,specifyatolerance

of2percent.

[n,d]=

rat(pi,.02)

n=

22

d=

7

This

gives

usthefamiliarπ≈

22/7.

(a)Let’shaverat,withatolerance

of.02,generate

rationalap

proxim

ationsto

the

pow

ersof

σ.Wecancompare

theresultto

therationalapproxim

ationsusedin

just

intonation.

Inou

rcodethatcomparesequaltemperamentwithjust

intonation,

changethestatements

thatdefinejust

intonationfrom

num=

[...]

278

Chapter20

.Music

den=

[...]

to

[num,den]=

rat(sigma.^k,.02);

You

should

seethatthebestrationalapproxim

ationagrees

withtheon

eusedby

just

intonationformost

ofthenotes.

Only

notesneartheendsofthescale

are

different.

•18/1

7vs.

16/15fork=1

•9/5vs.

7/4

fork

=10

•17/9

vs.

15/8

fork

=11

Theap

proxim

ationsfrom

ratare

more

accurate,butthedenominators

are

primes

orpow

ersofprimes

andso

areless

likelyto

becompatible

withother

de-

nominators.

(b)Changethetolerance

invo

lved

inusingratto

obtain

rationalapproxim

ations

topow

ersofσ.Replace

.02by.01or

.10.Youshould

findthat.02worksbest.

(c)Modifypianoexto

alsouse

therationalapproxim

ationsproducedbyrat.Can

you

detectanydifference

inthesoundgeneratedbypianoexiftheseratapproxi-

mationsareincorporated.

20.8

Musicalscore.Ourpianoexisable

toprocess

aMatlabfunctionthatrepre-

sents

amusicalscore.Thescore

isacellarraywithtw

ocolumns.

Thefirstcolumn

containsnote

numbersor

chord

vectors.Thesecondcolumncontainsdurations.

Ifthesecondcolumnis

notpresent,

allthenoteshavethesame,

default,duration.

For

example,hereis

aC-m

ajorscale.

s=

{0

24

57

91112}’

pianoex(s)

Amore

comprehensiveexample

istheportionof

Vivaldi’s“FourSeasons”

inthe

EXM

functionvivaldi.

typevivaldi

pianoex(vivaldi)

Frankly,Idonotfindthisattem

ptto

express

musicin

amacine-readable

form

very

satisfactory.Canyou

create

somethingbetter?