CMPT 102 Introduction toCMPT 102 Introduction to...

440
CMPT 102 Introduction to CMPT 102 Introduction to Scientific Computer Programming Brian Funt TASC 8025 Ph 778 782 3126 Phone 778-782-3126 [email protected] (c) 2009 Brian Funt, Simon Fraser University 1

Transcript of CMPT 102 Introduction toCMPT 102 Introduction to...

Page 1: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

CMPT 102 Introduction toCMPT 102 Introduction to Scientific Computer pProgramming

Brian FuntTASC 8025Ph 778 782 3126Phone [email protected]

(c) 2009 Brian Funt, Simon Fraser University 1

Page 2: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Administrative Issues

GradingAssignments 25%Midterm and quizzes 25%Final exam 50% However, must pass exam portion to pass the course

CheatingCan help each other understand materialCan help each other understand materialNot allowed to share code or workMay quote others but must include clear citation

(c) 2009 Brian Funt, Simon Fraser University 2

Page 3: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

About MeResearch area is colour

Colour in digital cameras, colour printers, displaysg p p yUnderstanding human colour perception

Been at SFU as a professor since 1980Student in 1967

U M tl bUse MatlabIn my research labIn CMPT 412 Computational Vision Introduced it to CMPT 102 since it’s so good for scientific computingg p g

Don’t want to pretend to know everythingDislike excuses and other trivia

Late penalty will be gradualI like questions and discussion. Any question is ok

Including “What’s the point?”I’d really like you to enjoy the course

(c) 2009 Brian Funt, Simon Fraser University 3

Page 4: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

About You

Who already knows some programming?Who already knows some programming?C, Basic, HP calculator, WORD, Excel

What are your majors?What are your majors?What would you like from the course?

4(c) 2009 Brian Funt, Simon Fraser University

Page 5: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

CMPT 102 in Matlab

Matlab: You’ll like it!Matlab is very widely used in science

Much less frustrating than C++ or JavaLots of ‘toolkits’ expand it to many areasLots of toolkits expand it to many areas

Medicine, business, simulation, physics, chemistry, biology, computer vision, databases, symbolic math (e.g. symbolic integration), control, optimization, and on and on.eg a o ), co o , op a o , a d o a d o

Interactive languageThe world’s most sophisticated programmable calculator

Learn some programming and computer scienceLearn some programming and computer scienceEmphasis on learning a useful toolI predict it to be useful in all your future work in science

5(c) 2009 Brian Funt, Simon Fraser University

Page 6: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Textbook

Title: Matlab for EngineersTitle: Matlab for Engineersby Holly MoorePearson Prentice Hall 2007Pearson Prentice Hall, 2007

Don’t let “Engineers” bother you

(c) 2009 Brian Funt, Simon Fraser University 6

Page 7: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture Slides

I’ll mail out or post lecture slidesI ll mail out or post lecture slidesSometimes will do it in advance of class

BUT….

Don’t skip class just because you get the notesyou get the notes.

(c) 2009 Brian Funt, Simon Fraser University 7

Page 8: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Information on CSIL

Course CentralCourse Centralweb pages under www.cs.sfu.ca/CCcourse outlines webpagescourse outlines, webpagessubmission server instructions, etc.

CSILCSILComputing Science Instructional Lab

Information under course centralo a o u de cou se ce awww.cs.sfu.ca/CC/Labs/

(c) 2009 Brian Funt, Simon Fraser University 8

Page 9: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Getting a CSIL Access Card

http://www.cs.sfu.ca/CC/Labs/card_access_faq.html#a-14(Or Google “csil access card”)

You’ll find directions on where to pick up your card (WMC 3101)From what I read on from that web page it seems that you won’t beFrom what I read on from that web page, it seems that you won t be able to pick up the access card to unlock the CSIL door until next Monday. However, you can still access Matlab over the Internet as I describe in the next few slides.

(c) 2009 Brian Funt, Simon Fraser University 9

Page 10: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Matlab at SFU and Home

Matlab is available on Windows and LinuxMatlab is available on Windows and LinuxIn CSIL

Also available over the InternetAlso available over the InternetRuns on CMPT servers

Cannot install it free on your own machineCannot install it free on your own machineCan run demo version for a month or soCan purchase student version for $120 (approx)p $ ( pp )

But you won’t need it

(c) 2009 Brian Funt, Simon Fraser University 10

Page 11: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Using Matlab over NetUse Remote Desktop from WindowsUse rdesktop from LinuxUse rdesktop from LinuxStart->Run (on Windows)

tmstscConnect to leto.csil.sfu.caUse your SFU computer account and passwordUse your SFU computer account and password

Sometimes it autofills [email protected]@

Delete the ‘@leto.csil.sfu.ca’ password not accepted

In the remote desktop window

(c) 2009 Brian Funt, Simon Fraser University 11

Start -> All Programs -> Matlab -> MATLAB R2008b

Page 12: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Using Matlab over NetFor Mac Users (Google “mac remote desktop”)

www microsoft com/mac/otherproducts/otherproductswww.microsoft.com/mac/otherproducts/otherproducts.aspx?pid=remotedesktopclient

(c) 2009 Brian Funt, Simon Fraser University 12

Page 13: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Get Started Now

Start today Don’t waitStart today. Don t wait.Learn by doing

Learning Strategy/AlgorithmLearning Strategy/Algorithm(1) Read a page(2) Try the examples(2) Try the examples(3) Turn pageIterate steps (1) (2) and (3)Iterate steps (1) (2) and (3)

A computer science ideaTry out your own ideas too

(c) 2009 Brian Funt, Simon Fraser University 13

y y

Page 14: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Matlab Does Symbolic Too

Not just numerical calculationNot just numerical calculatione.g. 3 + 5^2

Includes symbolic calculationIncludes symbolic calculationSymbolic equation solving

34

Symbolic integration

01023 34 =−− xxx

∫π

2y g

Symbolic differentiation

dxxx∫0

2)cos()sin(

(c) 2009 Brian Funt, Simon Fraser University 14

Symbolic differentiation

Page 15: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

CMPT 102 Lecture 2

Last timeLast timeIntroductionAdministrative issuesAdministrative issuesAccessing Matlab over the netVariablesVariables

(c) 2009 Brian Funt, Simon Fraser University 15

Page 16: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Is Computing Useful for MBB?

Biochemistry 218 - Biomedical Informatics 231 (Stanford)“Computational Molecular Biology (Biochem 218) is a practical, hands-on approach to

the field of computational molecular biology. The course is recommended for both molecular biologists and computer scientists desiring to understand the major issues concerning representation and analysis of genomes, sequences and proteins. Various existing methods will be critically described and the strengths and limitations of each will be discussed.”

MBB 441-3 (SFU) Bioinformatics “An overview of the newly emerging field ofMBB 441 3 (SFU) Bioinformatics An overview of the newly emerging field of bioinformatics, which is loosely defined as the intersection between the fields of molecular biology, genomics and computer science. A combination of lecture format and hands-on instruction is provided in the use of, and theory behind, bioinformaticalgorithms/software used in genomic and bioinformatic research. An introduction toalgorithms/software used in genomic and bioinformatic research. An introduction to the development of bioinformatic software/approaches is included, though only basic computer science and programming knowledge is required for this course.”

(c) 2009 Brian Funt, Simon Fraser University 16

Page 17: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Variables

Variables are names that will refer to valuesExample variable names

x, y, brian, help_me, x1, y34, Brian, Bri7an, xyCounterexample variable namesCounterexample variable names

help-me (because “-” means subtraction)help*me (because “*” means multiply)sin (because sin is for the sine function)sin (because sin is for the sine function)

AssignmentVariable gets a value by assignment using “=“

x=5y=6.2brian=x+y

(c) 2009 Brian Funt, Simon Fraser University 17

y

Page 18: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Scalar Values

IntegersIntegers510240056985790

Reals (also known as floating point)5 15.110.28240.056985790

Matlab generally stores integers as realsi.e., 293 is stored as 293.0

(c) 2009 Brian Funt, Simon Fraser University 18

Page 19: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

“Undefined” Variables>> x = 5

x =

5

>> x

x =x =

5

>> y??? Undefined function or variable'y'.

(c) 2009 Brian Funt, Simon Fraser University 19

y

Page 20: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

More Interesting Values

A variable can have a bunch of valuesA variable can have a bunch of valuesx = [3 2 4 5]x = [3 2 4 5] (commas are optional)x [3, 2, 4, 5] (commas are optional)y = [3.1 2.9 4.6 5.2 9.3 10.6]

The above are called vectorsThe above are called vectors

(c) 2009 Brian Funt, Simon Fraser University 20

Page 21: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Things to Try

Run Matlab on the machine where you’re sittingI t i blInvent some variable namesAssign some values to your variables

Try vector values tooTry vector values too

Try simple arithmeticUse different number formats (real, integer)

Guess at some other things that might work.Run Matlab on the leto “server” computer

Directions on next slideTry demo underHelp >Demos >Matlab >Graphics >Vibrating LogoHelp->Demos->Matlab->Graphics->Vibrating Logo

(c) 2009 Brian Funt, Simon Fraser University 21

Page 22: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Using Matlab over NetUse Remote Desktop from WindowsUse rdesktop from LinuxUse rdesktop from LinuxStart->Run (on Windows)

tmstscConnect to leto.csil.sfu.caUse your SFU computer account and passwordUse your SFU computer account and password

Sometimes it autofills [email protected]@

Delete the ‘@leto.csil.sfu.ca’ password not accepted

In the remote desktop window

(c) 2009 Brian Funt, Simon Fraser University 22

Start->All Programs->cmpt102->Matlab

Page 23: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Tabular Values

Variables can have table values tooVariables can have table values tooEntering to Matlab

z = [ 1 2 3 4; 5 6 7 8; 9 10 11 12][ ; ; ]Matlab outputs

z =1 2 3 45 6 7 89 10 11 129 10 11 12

The table form is called a matrix (pl. matrices)Matlab stands for “Matrix Laboratory”

(c) 2009 Brian Funt, Simon Fraser University 23

Matlab stands for Matrix Laboratory

Page 24: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Can Do Lots of Nice Things with Vectors and Matrices

[3 2 4 5]>> x = [3 2 4 5]x =

3 2 4 5

>> x*2ans =

6 4 8 106 4 8 10

>> x^2??? Error using ==> mpowerg pMatrix must be square.>> x.^2ans =

(c) 2009 Brian Funt, Simon Fraser University 24

9 4 16 25

Page 25: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Similarly with a Matrix

>> z = [ 1 2 3 4; 5 6 7 8; 9 10 11 12][ ; ; ]

z =

1 2 3 41 2 3 45 6 7 89 10 11 12

>> z.^3

ans =

1 8 27 64125 216 343 512729 1000 1331 1728

(c) 2009 Brian Funt, Simon Fraser University 25

Page 26: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

And More>> factorial(z)

ans =

1 2 6 24120 720 5040 40320

362880 3628800 39916800 479001600

>> sin(z)

ans =

0.8415 0.9093 0.1411 -0.7568-0.9589 -0.2794 0.6570 0.98940 4121 -0 5440 -1 0000 -0 5366

(c) 2009 Brian Funt, Simon Fraser University 26

0.4121 -0.5440 -1.0000 -0.5366

Page 27: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

More Stillmax(z)

mean(z)

ans =ans =

9 10 11 125 6 7 8

>> mean(mean(z))>> max(max(z))

ans =

>> mean(mean(z))

ans =

6 00012

>> min(min(z))

6.5000

>> min(min(z))

ans =

1

What else might you like to compute?

(c) 2009 Brian Funt, Simon Fraser University 27

1

Page 28: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Order of Evaluation (Operations)

%Anything after at "%" is ignored by Matlab. It's called a "comment.“%Compute area of cylinder%Compute area of cylinder>> radius=3radius =

3

>> height=5height =

5Each is πr2

Exponentiation

then5

>> surface_area = 2*pi*radius*height + 2*pi*radius^2

then

multiplication

thsurface_area =

150.7964>> %Note that pi is built-in

then

addition

(c) 2009 Brian Funt, Simon Fraser University 28

>> %Note that pi is built in

Page 29: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Evaluation (Parentheses)

Stuff in Parentheses is evaluated first

surface_area = 2*pi*radius*height + 2*pi*radius^(1.5+0.5)

surface_area =

150.7964

>> %Usually there are many ways to solve the same problem

surface_area = 2*pi*radius*(height + radius)

surface_area =

150.7964

(c) 2009 Brian Funt, Simon Fraser University 29

150.7964

Page 30: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try:

(1) (a) Calculate the surface area of box shown below (using Matlab of course)(b) Include a comment in your code

1.5cm

(b) Include a comment in your code

(2) Generalize your program to use variables for the width and heightvariables for the width and height.

(3) Enter a table of 2 rows and 3 columns

4.3 cm

( )(a) Square the elements(b) Find the mean of the square of the

elements(c) Find the arc tangent of the(c) Find the arc tangent of the

elements (use Google to find the right function name)

(c) 2009 Brian Funt, Simon Fraser University 30

Page 31: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

CMPT 102 Assignment 1 Fall 2009Due 6:00pm Monday, Sept. 21, 2009

D th i f th t tb k li t d b lDo the exercises from the textbook listed belowSave a copy of your Matlab command window to a file

Copy and paste it into a WORD fileShow all work, not just your final answerHighlight correct solutions with WORD’s yellow highlighterHighlight correct solutions with WORD s yellow highlighter.

Submit your WORD file as an e-mail attachment to Yi Cui (TA) at [email protected] Subject “CMPT 102 ASSIGNMENT 1 from Your Name and student number”

Exercises to do: 2.32.42.62.72.102 112.112.132.14 (but only for the above exercises)

(c) 2009 Brian Funt, Simon Fraser University 31

Page 32: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Late Penalty for Assignments

Grade you will receive will beGrade you will receive will beOn_time_grade*0.9(number_of_lecture_days_late)

No credit for assignments handing in after marks for others are postedfor others are posted.

(c) 2009 Brian Funt, Simon Fraser University 32

Page 33: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

CMPT 102 Lecture 3 Fall 2009

Last timeLast timeScalar, vector and matrix valuesOperator precedence (^ * +)Operator precedence ( , , +)

Parentheses as wellFunctions applied to valuespp

max, mean, factorialCalculating the area of a cylinder and a box

(c) 2009 Brian Funt, Simon Fraser University 33

Page 34: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Array/Matrix Operations

>> m = [1 2 n = [2 4 %Elementwise >> %Transpose[3 45 6]

m =

[6 810 12]

n =

%Elementwise% multiplication>> q=m.*n

>> %Transpose>> %Switch rows and columns>> n

m =1 23 45 6

n =2 46 8

10 12

q =

2 818 32

n =2 46 8

10 12

>> size(m)ans =

3 2

>> p=m+np =

3 6

50 7210 12

>> n'ans =

3 2 3 69 12

15 182 6 104 8 12

(c) 2009 Brian Funt, Simon Fraser University 34

Page 35: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Matrix Multiplicationm =

1 23 4

>> m*n??? Error using ==> mtimesI t i di i t5 6

n =

Inner matrix dimensions must agree.

>> m*nt

2 46 8

10 12

ans =

10 22 3422 50 78

>> nt=n'

nt =

22 50 7834 78 122

nt =

2 6 104 8 12

>> m.*nt??? Error using ==> timesMatrix dimensions must agree.

(c) 2009 Brian Funt, Simon Fraser University 35

Page 36: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Building Matrices out of Matricesm =

1 23 45 6

n =2 46 8

[m ; n]

ans =6 810 12

>> [m n]1 23 45 6

ans =

1 2 2 4

5 62 46 8

10 121 2 2 43 4 6 85 6 10 12

(c) 2009 Brian Funt, Simon Fraser University 36

Page 37: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Defining Matrices with “:”r = 1:3 u = 8:2:12

r =1 2 3

>> s = 1:1

u =8 10 12

v = 8: 2: 12>> s = -1:1

s =-1 0 1

v = -8:-2:-12

v =-8 -10 -12

%Use semicolon >> t=10:1000000;>> size(t)>> size(t)ans =

1 999991

(c) 2009 Brian Funt, Simon Fraser University 37

Page 38: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Cylinder Areas Table>> radii=0:0.1:1;>> heights=0:10;>> surface areas = 2*pi*radii *(heights + radii);

“.*” for element-wise multiplication

>> surface_areas = 2 pi radii. (heights + radii);

>> [radii' heights' surface_areas']ans = Transposes to turn

0 0 00.1000 1.0000 0.69120.2000 2.0000 2.76460 3000 3 0000 6 2204

Transposes to turn rows into columns

0.3000 3.0000 6.22040.4000 4.0000 11.05840.5000 5.0000 17.27880.6000 6.0000 24.8814

[…] is a matrix here composed of 3 columns0.7000 7.0000 33.8664

0.8000 8.0000 44.23360.9000 9.0000 55.98321.0000 10.0000 69.1150

columns

(c) 2009 Brian Funt, Simon Fraser University 38

1.0000 10.0000 69.1150

Page 39: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Being Too Terse

radii=0:0.1:1;heights=0:10;heights=0:10;[radii' heights' (2*pi*radii.*(heights + radii))']

ans =0 0 0

0.1000 1.0000 0.69120.2000 2.0000 2.76460.3000 3.0000 6.22040.3000 3.0000 6.22040.4000 4.0000 11.05840.5000 5.0000 17.27880.6000 6.0000 24.88140 7000 7 0000 33 86640.7000 7.0000 33.86640.8000 8.0000 44.23360.9000 9.0000 55.98321.0000 10.0000 69.1150

(c) 2009 Brian Funt, Simon Fraser University 39

Page 40: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try

Generate a table of box volumes as a function of width, depth and height.

Let the width and depth vary from 0 to 5 in steps of 0.5Let the height vary from 0 to 2 in steps of 0.2

(c) 2009 Brian Funt, Simon Fraser University 40

Page 41: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

linspace%Generate vector of 7 values evenly spaced over range 1 through 3a=linspace(1, 3, 7);>> a>> aa =

1.0000 1.3333 1.6667 2.0000 2.3333 2.6667 3.0000>> size(a)ans =

1 7

(c) 2009 Brian Funt, Simon Fraser University 41

Page 42: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

logspace

%Generate vector of values logarithmically spaced over range 101 through 104

b=logspace(1 4 4)b=logspace(1, 4 , 4)>> bb =

10 100 1000 10000

c=logspace(1,4,3) %Now generate only 3 valuesc =1.0e+004 * (note here the constant multiplier)1.0e 004 (note here the constant multiplier)

0.0010 0.0316 1.0000 (i.e, this is 10, 316, 1000)

l 10( ) %Thi i l b 10 N t l l ld b l ( )log10(c) %This is log base 10. Natural log would be log(c)ans =

1.0000 2.5000 4.0000 (i.e., they’re evenly spaced in log space)

(c) 2009 Brian Funt, Simon Fraser University 42

( , y y p g p )

Page 43: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Calculating Drag

Example in text page 33Example in text page 33Study the example on your own. It will help in understanding the concepts discussed so farunderstanding the concepts discussed so far

(c) 2009 Brian Funt, Simon Fraser University 43

Page 44: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Number Formats: Floating Point

Scientific notation in computer languagesScientific notation in computer languages2.9979 x 108 meters per second is speed of lightTo write it in Matlab (or most any other language)To write it in Matlab (or most any other language)

2.9979e8 (no spaces allowed)Use ‘e’ for exponent in base 10It’s not the irrational number e

Negative exponents are fine43 67 X 10 2643.67 X 10-26

43.67e-26

(c) 2009 Brian Funt, Simon Fraser University 44

Page 45: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Read On Your Own

More about number formats pages 37-39More about number formats pages 37 39About saving your work (Section 2.4)

(c) 2009 Brian Funt, Simon Fraser University 45

Page 46: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

CMPT 102 Lecture 4 (Draft)

Last timeLast timeMatrix operations

Creating matrices with […]g [ ]Combining matrices into matrices+, *, .* on matricessize()Creating matrices with “:” notation

Table of cylinder areasTable of cylinder areasCode looks like it’s about a single area

Matrix operations like + mean that it’s about all areas

(c) 2009 Brian Funt, Simon Fraser University 46

Page 47: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Yi Ciu office hour Friday Sept 18

Yi will come to CSIL 9804 (the smaller roomYi will come to CSIL 9804 (the smaller room next to where our class is) from 3pm to 4pm this Friday to help you as you work on your y p y y yassignment.

(c) 2009 Brian Funt, Simon Fraser University 47

Page 48: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Matlab Diary

diary file-to-save-command-window-indiary file to save command window indiary offdiary ondiary onWarning

M l b d ’ h i dMatlab doesn’t seem to save the window contents until either there’s ‘diary off’ or Matlab exitsMight lose work if matlab crashesMight lose work if matlab crashes.

(c) 2009 Brian Funt, Simon Fraser University 48

Page 49: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Matlab Windows

CommandCommandCan use arrow keys to select earlier lines

Command HistoryCommand HistoryCan double click lines

WorkspaceWorkspaceShows variables in use

Current DirectoryCurrent DirectoryMay need to change to point to where you store your code

(c) 2009 Brian Funt, Simon Fraser University 49

your code

Page 50: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Array (Matrix) Editor

Double click on value in workspaceDouble click on value in workspaceArray editor opensCan change values in cellsCan change values in cellsMatrix changes

“Array” and “Matrix” are almost synonymsArray and Matrix are almost synonymsMatrix contains only numbersArray can contain other types of dataArray can contain other types of data

(c) 2009 Brian Funt, Simon Fraser University 50

Page 51: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Chapter 3 Built-in Functions

Will cover this quicklyWill cover this quicklyWhat functions are there?

If you can think of it it’s probably availableIf you can think of it, it s probably availableI use Google to find documentation

e.g. google “sine matlab”e.g. google sine matlabgoogle “standard deviation matlab”google “square root matlab”

(c) 2009 Brian Funt, Simon Fraser University 51

Page 52: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Nesting Functions

Just as in regular math where you haveJust as in regular math where you havef(g(x))

Functions have zero or more parametersArguments passed to parameters can be scalars or arraysAlso the ‘value’ of a function can be an array too

sqrt(3)ans =

1.7321

b=[1 2; 3 4]b =

1 23 4

>> sin(sqrt(3))ans =

0.9870

3 4>> sin(sqrt(b))ans =

0.8415 0.98780 9870 0 9093

(c) 2009 Brian Funt, Simon Fraser University 52

0.9870 0.9093

Page 53: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Arguments and Parameters

An argument is passed to a parameter

sqrt(x) is a function with one parameter

sqrt(5) passes the value 5 to its parameter

sin(x) is a function of one parameter toosin(x) is a function of one parameter too

The value of sqrt(9) is passed to its parameter inq ( ) p psin(sqrt(9))

I th l ’5’ d ’ t(9)’ t

(c) 2009 Brian Funt, Simon Fraser University 53

In these examples, ’5’ and ’sqrt(9)’ are arguments

Page 54: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Parameter Passing (Many Variations in other languages)

Matlab uses “pass by value” ONLYMatlab uses pass by value ONLYFunction receives only the value(s)Means that function cannot change the value(s)Means that function cannot change the value(s) passed to itFunction can only return a valuey

Can’t have x=5

y=f(x)x3

(c) 2009 Brian Funt, Simon Fraser University 54

Page 55: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Functions with Multiple Parameters

Already saw linspaceAlready saw linspacerem(x,y) for computing remainder is another

rem(10.1,4.5)

ans =

1.1000

(c) 2009 Brian Funt, Simon Fraser University 55

Page 56: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

More Matlab Functions

% Absolute valueabs( 5)

% Sign of argumentsign( 2:2)

% exp(x) is ex

abs(-5)

ans =

sign(-2:2)

ans =exp(3)

ans =5

>> abs(-2:2)

-1 -1 0 1 1ans

20.0855

ans =

2 1 0 1 2

(c) 2009 Brian Funt, Simon Fraser University 56

Page 57: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Rounding Functions

% To closest integer % To integer nearer zero % T i t ∞% To closest integerround(31.49)ans =

31

% To integer nearer zerofix(31.6)

ans =

% To integer nearer -∞floor(31.6)ans =

31

>> round(31.5)ans =

31

>> fix(-31 6)

>> floor(-31.6)ans =

32ans 32

>> fix( 31.6)

ans =-31

-32

% ceil(x) is similar but % to +∞

(c) 2009 Brian Funt, Simon Fraser University 57

Page 58: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

sum

c =>> a=[2 1 3]

2 1 35 0 2

a =

2 1 3>> sum(c)

ans =

2 1 3

>> sum(a)

7 1 5ans =

6

(c) 2009 Brian Funt, Simon Fraser University 58

Page 59: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try

(1) Use Matlab to find the average of the absolute value of the numbers 5 8 9 4 2 Use a vector to hold the numbersof the numbers 5, -8, -9, 4, 2. Use a vector to hold the numbers.(Your solution should use abs only once)

(2) Suppose 4 people have in their pockets $1.35, $4.55, $3.98 and $5.69, respectively. Suppose they pool their money. Use Matlab to compute thetotal amount of money they have to the nearest dollar.

(3) If they are going to buy popcorn at $1 per bag use Matlab to find(3) If they are going to buy popcorn at $1 per bag, use Matlab to findhow many bags can they buy?

(c) 2009 Brian Funt, Simon Fraser University 59

Page 60: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Trig Functions

sin(x) sine of x expressed in radians)sin(x) sine of x expressed in radians)cos(x), tan(x)asin(x) inverse sine of xasin(x) inverse sine of xsinh(x) hyperbolic sine of x in radiansasinh(x) inverse hyperbolicsind(x) sine of x in degreescosd(x)asind(x) etc.

(c) 2009 Brian Funt, Simon Fraser University 60

( )

Page 61: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Data Analysis Functions

max (maximum)max (maximum)min (minimum)mean (average)mean (average)median sum (sum total of elements)prod (product)sort (sort elements)cumsum, cumprod (cummulative sum, prod)

(c) 2009 Brian Funt, Simon Fraser University 61

, p ( , p )

Page 62: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Example of min, and vector output

>> a = [2 1 3]

%min will return 2 values

>> [ i i l ti ] i ( )

%min works on%arrays too>> a = [2 1 3]

a =2 1 3

>> [minimum, location] = min(a)

minimum =a =

2 1 3

>> min(a)ans =

1

1

location =

b =4 0 2

2

>> minimum

>> min(a,b)

ans =

minimum =

1

2 0 2

(c) 2009 Brian Funt, Simon Fraser University 62

1

Page 63: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

If you can imagine it, it’s likely there

min and other functions[ b] min and other functions generalized to work on columns

c = [a ; b]c =

2 1 34 0 2

Here it finds the min of each columnTh t t i 2 t

>> [minimum, location] = min(c)

minimum = The output is 2 vectorsminima of columnslocation of min within

minimum =2 0 2

location of min within columnlocation =

1 2 2

(c) 2009 Brian Funt, Simon Fraser University 63

Page 64: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

meana =

2 1 3 %To get mean of rows

>> mean(a)

ans =2

>> mean(c')

ans =2 22

c =2 1 3

2 2

4 0 2

>> mean(c)[x y]=mean(c)

ans =

3.0000 0.5000 2.5000

[x y] mean(c)??? Error using ==> meanToo many output arguments.

(c) 2009 Brian Funt, Simon Fraser University 64

Page 65: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

sum and cumsum

c =% Of rows

2 1 34 0 2

% Of rows

cumsum(c')

>> sum(c)

ans =6 1 5

ans =

2 43 46 1 5

>> cumsum(c)

36 6

ans =2 1 36 1 5

(c) 2009 Brian Funt, Simon Fraser University 65

Page 66: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try

(1) Find the sum of the numbers 0 5 0 75 1 0 5 0(1) Find the sum of the numbers 0.5, 0.75, 1.0, …. 5.0(You’ll want to use ‘:’ notation from last lecture.)

(2) Test outa=0:360; %Create angles 0, 1, …, 360 degrees.plot(sind(a))

Then use Matlab to find the angles at which sind is minimum over theThen use Matlab to find the angles at which sind is minimum over the domain [0, 360] degrees.

(3) Find the total of sind over that range.

(4) Plot the cumulative sum of sind over [0, 360]

(c) 2009 Brian Funt, Simon Fraser University 66

Page 67: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

CMPT 102 Lecture 5

Last timeLast timemin and max with vector output

[mn loc] =min([3 -4 5 6])[ ] ([ ])Passing argument values to function parameters

Returning valuesDiary and saving workfloor, fix, ceil, round

(c) 2009 Brian Funt, Simon Fraser University 67

Page 68: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Example of min, and vector output

>> a = [2 1 3]

%min will return 2 values

>> [ i i l ti ] i ( )

%min works on%arrays too>> a = [2 1 3]

a =2 1 3

>> [minimum, location] = min(a)

minimum =a =

2 1 3

>> min(a)ans =

1

1

location =

b =4 0 2

2

>> minimum

>> min(a,b)

ans =

minimum =

1

2 0 2

(c) 2009 Brian Funt, Simon Fraser University 68

1

Page 69: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

If you can imagine it, it’s likely there

min and other functions[ b] min and other functions generalized to work on columns

c = [a ; b]c =

2 1 34 0 2

Here it finds the min of each columnTh t t i 2 t

>> [minimum, location] = min(c)

minimum = The output is 2 vectorsminima of columnslocation of min within

minimum =2 0 2

location of min within columnlocation =

1 2 2

(c) 2009 Brian Funt, Simon Fraser University 69

Page 70: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

meana =

2 1 3 %To get mean of rows

>> mean(a)

ans =2

>> mean(c')

ans =2 22

c =2 1 3

2 2

4 0 2

>> mean(c)[x y]=mean(c)

ans =

3.0000 0.5000 2.5000

[x y] mean(c)??? Error using ==> meanToo many output arguments.

(c) 2009 Brian Funt, Simon Fraser University 70

Page 71: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

sum and cumsum

c =% Of rows

2 1 34 0 2

% Of rows

cumsum(c')

>> sum(c)

ans =6 1 5

ans =

2 43 46 1 5

>> cumsum(c)

36 6

ans =2 1 36 1 5

(c) 2009 Brian Funt, Simon Fraser University 71

Page 72: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Saving your programs for easy running

Start new m file%test script filex=3;

2*3Start new .m fileJust as in WORD for .doc

Copy and paste code from command window

y=2*3;z=x+7

Copy and paste code from command windowremove any “>>”

Save the fileSave the fileDoes a “save as” just as in WORD

Now to run the codeNow to run the codesimply type the filename (without the .m) in the command windowcommand window

(c) 2007-08 Brian Funt, Simon Fraser University 72

Page 73: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

prod

d([1 2 3 4 5])>> prod([1 2 3 4 5])

ans =

120

>> factorial(5)

ans =

120

(c) 2009 Brian Funt, Simon Fraser University 73

Page 74: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

linspace (reminder)%Generate vector of 7 values evenly spaced over range 1 through 3a=linspace(1, 3, 7);>> a>> aa =

1.0000 1.3333 1.6667 2.0000 2.3333 2.6667 3.0000>> size(a)ans =

1 7

(c) 2009 Brian Funt, Simon Fraser University 74

Page 75: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

logspace (reminder)

%Generate vector of values logarithmically spaced over range 101 through 104

b=logspace(1 4 4)b=logspace(1, 4 , 4)>> bb =

10 100 1000 10000

c=logspace(1,4,3) %Now generate only 3 valuesc =1.0e+004 * (note here the constant multiplier)1.0e 004 (note here the constant multiplier)

0.0010 0.0316 1.0000 (i.e, this is 10, 316, 1000)

l 10( ) %Thi i l b 10 N t l l ld b l ( )log10(c) %This is log base 10. Natural log would be log(c)ans =

1.0000 2.5000 4.0000 (i.e., they’re evenly spaced in log space)

(c) 2009 Brian Funt, Simon Fraser University 75

( , y y p g p )

Page 76: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try (A1) Find the sum of the numbers 0.5, 0.75, 1.0, …. 5.0

(You’ll want to use ‘:’ notation from lecture 3.)(A2) Test out

0 360 %C l 0 1 360 da=0:360; %Create angles 0, 1, …, 360 degrees.plot(sind(a))

Then use Matlab to find the angle at which sind is minimum over the domain [0, 360] degrees.

Generate a table of box volumes and ‘perimeters’ (width+depth+height) as a function of width, depth and height. The table will have 5 columns, 1 for each of width, depth, height, volume and perimeter.

[0, 360] deg ees

(B1) Use linspace to define 7 widths and depths in the range 1 to 10Use logspace to define 7 heights in the range 10-9 to 10-5

Use prod to calculate the volume. Use sum to compute the ‘perimeter’.(Hint: linspace creates a row. You may want to switch it to a column)

(B2) Save your code in a script file so that you can run it simply using the file name

(B3) At the bottom of your table add a row giving the totals for each of the widths,depths, heights, volumes and perimeters of all the boxes in your table.

(c) 2009 Brian Funt, Simon Fraser University 76

Page 77: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

CMPT 102 Lecture 6 Fall 2009

Saving commands in a script fileSaving commands in a script fileFunctions like min that return multiple values

(c) 2009 Brian Funt, Simon Fraser University 77

Page 78: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Random Number Functions

Called pseudo-random numbersCalled pseudo random numbersThey’re random like throwing diceHowever they depend on the initial valueHowever, they depend on the initial value

Initial value is called the ‘seed’If you use the same seed, you get the same random numbers

Uniformly distributed random numbersrand(m,n) m by n matrix of random numbersrand(n) n by n matrix of random numbers

(c) 2009 Brian Funt, Simon Fraser University 78

Page 79: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Examples of rand

>> r=rand(3,1)% Don’t get same % Range and mean

r =0.05340.35670 4983

% thing twice>> rand(1,1)ans =

0.2009

% Range and mean

t=rand(100,1);>> plot(t)

0.4983

>> r=rand(3)

0.2009

>> rand(1,1)ans =

0 2731

>> [mean(t) max(t) min(t)]

ans =r =

0.4344 0.1133 0.79110.5625 0.8983 0.81500 6166 0 7546 0 6700

0.2731 a s0.5052 0.9862 0.0142

0.6166 0.7546 0.6700

(c) 2009 Brian Funt, Simon Fraser University 79

Page 80: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Roll a Die >> r=rand(4,1)r =

0 6557

Uniformly pick number from 1 to 6

0.65570.03570.84910.9340

>> r [eps; r; 1 eps]1 to 6rand gives numbers in interval (0,1)Converting to [1 6]

> eps

ans =

>> r=[eps; r; 1-eps]r =

0.00000.65570 0357Converting to [1,6]

Don’t want zeroDon’t want 7 either

Conversion

2.2204e-016

>> 1-eps

0.03570.84910.93401.0000

ConversionScale by 6

interval (0,6)Add 0 5

1 eps

ans =

1 0000

>> round(r*6+0.5)ans =

14Add 0.5

interval (0.5,6.5)round

1.0000 41666

(c) 2009 Brian Funt, Simon Fraser University 80

6

Page 81: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try

Write a script that will randomly choose aWrite a script that will randomly choose a number from the numbers 0.5, 1.5, …, 10.5

Try your code for 10,000 choicesTry your code for 10,000 choicescompute the mean and standard deviation (you’ll have to find the name of the Matlab function) of the choices

(c) 2007-08 Brian Funt, Simon Fraser University 81

Page 82: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Gaussian/Normal Random #’s

randn(m n)randn(m,n)randn(n) g=randn(1000,1);

>> plot(g)>> figureg>> plot(hist(g))

%How about “curve”%How about curve%of our class size>> g=randn(44,1);>> plot(hist(g))

(c) 2009 Brian Funt, Simon Fraser University 82

Page 83: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Sorting

sort(x)

a=[2 3; 9 -1 ; 4 2]a =

2 39 1sort(x)

sort each column into ascending order

9 -14 2

>> sort(a)ans =

2 -14 29 3

Both columns sorted

independently9 3 independently

(c) 2009 Brian Funt, Simon Fraser University 83

Page 84: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Sorting

sort(x)

a=[2 3; 9 -1 ; 4 2]a =

2 39 1sort(x)

sort each column into ascending order

9 -14 2

>> sort(a)sortrows(x,n)

sort rows ascending based on nth column

ans =2 -14 29 3

Both columns sorted based on nth column 9 3

>> sortrows(a,2)ans =

9 1

independently

9 -14 22 3

Rows are preserved

(c) 2009 Brian Funt, Simon Fraser University 84

Page 85: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try

Write a script that will randomly choose aWrite a script that will randomly choose a number from the numbers 0.5, 1.5, …, 10.5

Try your code for 10,000 choicesTry your code for 10,000 choicescompute the mean and standard deviation (you’ll have to find the name of the Matlab function) of the choices

(c) 2009 Brian Funt, Simon Fraser University 85

Page 86: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Chapter 4 Manipulating Matrices

Skipping from p 76 (first edition) to end ofSkipping from p 76 (first edition) to end of Chapter 3We’ve defined matrices beforeWe ve defined matrices before

e.g., a = [ 1 2 3; 4 5 6]Want to be able to access parts of the matrixWant to be able to access parts of the matrix

individual entriesgroups of entriesgroups of entries

(c) 2009 Brian Funt, Simon Fraser University 86

Page 87: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Matrix/Array Indexinga(1+1, 2^2-1)

a=[1 2 34 5 6]a =

Alternative to using semicolon

( , )ans =

6

>> sin(pi/2)1 2 34 5 6

>> size(a)

>> sin(pi/2)ans =

1 Can also use an >> size(a)

ans =2 3 Two rows, three

columns.

a(sin(pi/2),3)ans =

3

expression as index

>> a(2,1)ans =

4 Notation is analogous

a(2,[1 2])ans =

4 5

>> a(1,2)ans =

2

to a2,1 notation used for matrix elements in

linear algebra>> a(2,[1 3])ans =

4 6

(c) 2009 Brian Funt, Simon Fraser University 87

4 6

Page 88: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Colon Operator and Array Indexing

Colon Operator generates a list of numbersColon Operator generates a list of numbers

2:5 % Colon Indexa

%Colon with% i t

ans =

2 3 4 5

aa =

1 2 34 5 6

% increment

3:-1:1ans =

>> [2:5]

ans =

a(2,1:3)

ans =

3 2 1

>> a(2,3:-1:1)ans =

2 3 4 5

ans =

4 5 6ans =

6 5 42nd row

reversed

(c) 2009 Brian Funt, Simon Fraser University 88

Page 89: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Indexing Entire Rows or Columns

a =

1 2 34 5 6

% Entire 2nd column>> a(:,2)

ans =

%Entire matrix%stretched out

a(:)

%Entire 2nd row>> a(2,:)

ans =

25

a(:)

ans =

ans =

4 5 6

1425536

(c) 2009 Brian Funt, Simon Fraser University 89

Page 90: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Examples of array indexing

%Mi i f %Minimum of%Minimum of % 2nd row

min(a(2,:))

%Minimum of% entire matrix

min(min(a))(a( , ))

ans =

4

ans =

1

4%Alternative>> min(a(:))

ansans =

1

(c) 2009 Brian Funt, Simon Fraser University 90

Page 91: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

One More Indexing Feature: end

a(end 2)“end” means the last index. a(end,2)

ans =Here this means row 2

5

>> a(2, end)

ans =

6 Here it means column 3column 3

(c) 2009 Brian Funt, Simon Fraser University 91

Page 92: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try

>> M=magic(5)M =

Using Matlab’s array indexing(0) Practice with matrix indexing by trying a few examples like M(:,1), M(2,3:end), etc.M

17 24 1 8 1523 5 7 14 164 6 13 20 22

10 12 19 21 3

p ( , ), ( , ),(1)Compute the sum of the numbers in the 3rd row of M(2) Generalize (1) so that it will work for magic matrices of any size10 12 19 21 3

11 18 25 2 9magic matrices of any size(3) Compute the median and sum of the 9

central elements of M using indexing(4)Compute the sum of the elements in the ( ) p

odd rows of M. Make your method general so it will work for any matrix M

(5)Compute the standard deviation of every second element of M (i e of 17every second element of M (i.e., of 17, 1, 15, 4, 13, 22, 11, 25, 9). Use indexing to retrieve those values.

(c) 2009 Brian Funt, Simon Fraser University 92

Page 93: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

CMPT 102 Lecture 7 Fall 2009

Last timeLast timeRandom numbers with randGenerating random integers 1 2 6Generating random integers 1,2, …,6Matrix indexing

:end

(c) 2009 Brian Funt, Simon Fraser University 93

Page 94: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Chapter 6 User-Defined FunctionsSkipping from page 112 (1st ed) to end of Chapter 4Chapter 4

Will come back to some of this laterSkipping Chapter 5 on plotting for nowSkipping Chapter 5 on plotting for nowYou’ve seen Matlab functions

li d tmax, linspace, cos, rand, etc.Now let’s write our own functions

C lli f i ill b i di i i h blCalling your functions will be indistinguishable from calling built-in functionse g [x y] = brian(3 4 9)

(c) 2009 Brian Funt, Simon Fraser University 94

e.g. [x y] = brian(3, 4, 9)

Page 95: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Defining a Function

Create an “M-file”Create an M fileUse File->New from the Matlab menuDefine your functionDefine your functionSave the file contents

File name must be the same as the function nameFile extension is “.m”By default, Matlab automatically suggests the correct name for savingname for saving

(c) 2009 Brian Funt, Simon Fraser University 95

Page 96: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Defining Function sinsquared

% sinsquared(x) returns sin(x).^2% it works with vector inputsfunction sq = sinsquared(x)

s = sin(x);s sin(x);

sq = s.*s;

(c) 2009 Brian Funt, Simon Fraser University 96

Page 97: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Defining Function sinsquared

% sinsquared(x) returns sin(x).^2% it works with vector inputsfunction sq = sinsquared(x)

s = sin(x);s sin(x);

sq = s.*s;

(c) 2009 Brian Funt, Simon Fraser University 97

Page 98: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Defining Function sinsquared

% sinsquared(x) returns sin(x).^2% it works with vector inputsfunction sq = sinsquared(x)

s = sin(x);s sin(x);

sq = s.*s;

(c) 2009 Brian Funt, Simon Fraser University 98

Page 99: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Testing Function sinsquaredsinsquared(pi)ans =% sinsquared(x) returns sin(x).^21.4998e-032

>> sinsquared([0 1 2])ans =

% it works with vector inputs

function sq = sinsquared(x)ans =

0 0.7081 0.8268

>> sinsquared(0:pi/4:pi)

s = sin(x);

sq = s.*s; q ( p p )ans =

0 0.5000 1.0000 0.5000 0.0000

>> help sinsquaredsinsquared(x) returns sin(x).^2it works with vector inputs

(c) 2009 Brian Funt, Simon Fraser University 99

Page 100: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Defining a Function

% Note that functions must be stored in files. They can’t be defined% in the command window

function sq = sinsquared (x)??? function sq = sinsquared (x)

|Error: Function definitions are not permitted at the prompt or in scriptsError: Function definitions are not permitted at the prompt or in scripts.

(c) 2009 Brian Funt, Simon Fraser University 100

Page 101: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Roll Die as a Function

Name the function “roll”Name the function rollReturn a uniformly distributed random integer in the range [1 6]in the range [1,6]roll will take no arguments

(c) 2009 Brian Funt, Simon Fraser University 101

Page 102: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Defining roll

%Function roll takes has no arguments`

%Function roll takes has no arguments%It returns a random integer in [1,6]function face = roll()r=rand(); %Generate random number in [0,1]

*(5 99999999) 0 5 %S l d ff tr=r*(5.99999999)+0.5; %Scale and offset rface = round(r); %Make r into an integer

(c) 2009 Brian Funt, Simon Fraser University 102

Page 103: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Testing roll

%Function roll takes has no arguments >> roll `%Function roll takes has no arguments%It returns a random integer in [1,6]function face = roll()r=rand(); %Generate random number in [0,1]

*6 0 5 %S l d ff t

ans =5

r=r*6+0.5; %Scale and offset rface = round(r); %Make r into an integer >> roll()

ans =3

>> roll(1)??? Error using ==> roll??? Error using ==> rollToo many input arguments.

(c) 2009 Brian Funt, Simon Fraser University 103

Page 104: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Easy way to start editing a function

>>edit roll

(c) 2009 Brian Funt, Simon Fraser University 104

Page 105: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

rolln (n rolls of the die)

%Function rolln(n)%Function rolln(n)%It returns a vector of n random integers in [1,6]

function faceArray = rolln(n)

r=rand(n,1); %Generate random number in [0,1]r=r*6+0.5; %Scale and offset r valuesfaceArray = round(r); %Make r values into an integersy ( ); g

(c) 2009 Brian Funt, Simon Fraser University 105

Page 106: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try(1) Enter and test the function sinsquared

(2) Write and test a function that computes the average of 3 numbers. Call your function myaverage3. A sample call would be:

myaverage3(5, -9, 10)

(3) Define and test a function mymean(V) that computes the f ll th b i t V D ’t M tl b’mean of all the numbers in vector V. Don’t use Matlab’s mean

function. You may use any other built-in functions you need.

(4) Using sort, create a function mymax(V) that returns the ( ) g , y ( )maximum of a vector V.

(c) 2009 Brian Funt, Simon Fraser University 106

Page 107: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

CMPT 102 Lecture 8 Fall 2009

Last timeLast timeWriting your own functions

Assignment 2 was mailed out to you

(c) 2009 Brian Funt, Simon Fraser University 107

Page 108: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Defining a Function

Create an “M-file”Create an M fileUse File->New from the Matlab menuDefine your functionDefine your functionSave the file contents

File name must be the same as the function nameFile extension is “.m”By default, Matlab automatically suggests the correct name for savingname for saving

(c) 2009 Brian Funt, Simon Fraser University 108

Page 109: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Testing Function sinsquaredsinsquared(pi)ans =% sinsquared(x) returns sin(x).^21.4998e-032% it works with vector inputs

function sq = sinsquared(x)

s = sin(x);

sq = s.*s;

(c) 2009 Brian Funt, Simon Fraser University 109

Page 110: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Testing roll

%Function roll takes has no arguments >> roll `%Function roll takes has no arguments%It returns a random integer in [1,6]function face = roll()r=rand(); %Generate random number in [0,1]

*6 0 5 %S l d ff t

ans =5

r=r*6+0.5; %Scale and offset rface = round(r); %Make r into an integer >> roll()

ans =3

>> roll(1)??? Error using ==> roll??? Error using ==> rollToo many input arguments.

(c) 2009 Brian Funt, Simon Fraser University 110

Page 111: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

myaverage3%compute the average of 3 numbers%works for vectors toofunction av myaverage3(a b c)function av = myaverage3(a,b,c)av = (a+b+c)/3;

3(4 2 9)>> myaverage3(4, 2, 9)

ans =

5

>> myaverage3([4 5 6], [8 3 1], [6 2 4])

ans =

6.0000 3.3333 3.6667

(c) 2009 Brian Funt, Simon Fraser University 111

Page 112: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try(1) Write a function tax(amounts, rate) that given a vector of amounts and a single percentage tax rate will

return a vector of the amount of tax to be paid on each amount to the nearest penny.>> tax([8.50 90.25], 5)ans =

0 4300 4 51000.4300 4.5100

(2) Write a function pst(amounts) that will take a vector of amounts and return the provincial sales tax payable on each amount. Use your tax function within your pst function.

>> pst([45.61 109.99])pst([ 5 6 09 99])ans =

3.1900 7.7000

(3) Write a function gst(amounts) that will take a vector of amounts and return the federal sales tax payable on each amount. Use your tax function within your pst function.

>>gst([45.61 109.99])ans =

2.2800 5.5000

(4) Write a function total payable(amounts) that will take a vector of amounts and return the total payable(4) Write a function total_payable(amounts) that will take a vector of amounts and return the total payable for each amount (i.e., amount plus PST plus GST). Make use of your pst and gst functions within your tax function.

>> total_payable([45.61 109.99])ans =

(c) 2009 Brian Funt, Simon Fraser University 112

51.0800 123.1900

Page 113: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Rolling a Pair of Dice

Name the function roll diceName the function roll_diceIt will return two values, one for each dieIt will call/invoke our function roll diceIt will call/invoke our function roll_dice

(c) 2009 Brian Funt, Simon Fraser University 113

Page 114: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Testing roll_dice

[d1 d2] = roll dice[d1 d2] = roll_diced1 =

6d2 =

function [die1 die2] = roll_dice()die1=roll;die2=roll;

3

>> [d1 d2] = roll_diced1 =

die2 roll;

d1 6

d2 =1

>> die1??? Undefined function or variable 'die1'.

(c) 2009 Brian Funt, Simon Fraser University 114

Page 115: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To TryWrite a function stats that given vectors V and W as input, returns a vector containing the mean and median of the difference of V and W.

>> [a b]= stats([1 2 3] [ 1 2 3])>> [a b]= stats([1 2 3], [ 1 2 3])a =

0b =

0

>> x = [3 5 2];>> y = [4 2 3];

Differences here are -1, 3, -1th diff i 1/3>> y = [4 2 3];

>> [a b]= stats(x,y)

so the mean difference is 1/3and the median difference is -1

a =0.3333

b =-1

(c) 2009 Brian Funt, Simon Fraser University 115

1

Page 116: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lectures 9, 10, 11 were given by Yi Cui

(c) 2009 Brian Funt, Simon Fraser University 116

Page 117: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 9 Fall 2009

(c) 2009 Brian Funt, Simon Fraser University 117

Page 118: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Something I discovered about magic>> sort(ans(:))ans =

1

>> magic(4)

2345

ans =

16 2 3 13

567895 11 10 8

9 7 6 124 14 15 1

910111213141516

(c) 2009 Brian Funt, Simon Fraser University 118

16

Page 119: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Another Function Example

Write a function to evaluate a degree 3 polynomial of the form

ax3 + bx2 + cx + d

(c) 2009 Brian Funt, Simon Fraser University 119

Page 120: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Another function example (polyabcdx)

%E l t d 3 l i l i f th f%Evaluate a degree 3 polynomial given of the form% a*x^3 + b*x^2 + c*x + dfunction polyout = polyabcdx (a , b, c, d, x)

polyout=a*x^3 + b*x^2 + c*x + d;

>> polyabcdx(3,4,2,1,10)

ans =

3421

(c) 2009 Brian Funt, Simon Fraser University 120

Page 121: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try(1) Over the domain –π to π, the sine function can be expressed as the sum of an infinite series. ....

!7!5!3)sin(

753

+−+−=xxxxx

Write a function, mysinA(x), that computes an approximation to sine of x by summing the first 5 terms of the series. Do not use Matlab’s sin. You may use Matlab’s factorial(n) to compute n! Model your code on polyabcdx

(2) Write a function F2C that converts degrees Fahrenheit to Celsius To convert Fahrenheit(2) Write a function F2C that converts degrees Fahrenheit to Celsius. To convert Fahrenheit temperatures into Celsius, begin by subtracting 32 from the Fahrenheit number, then multiply by 5/9. E.g., F2C(68) returns the answer 20.

(3) Generalize (2) to work with vector arguments E g F2C([50 30 44])(3) Generalize (2) to work with vector arguments. E.g., F2C([50 30 44])

(c) 2009 Brian Funt, Simon Fraser University 121

Page 122: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

poly with coefficients in a vector

%Evaluate a degree 3 polynomial%Coeffs is a vector of the four coefficients%x is the value of the variablef ti l t l ff(C ff )function polyout = polycoeff(Coeffs, x)

polyout = Coeffs(1)*x^3 + Coeffs(2)*x^2 + Coeffs(3)*x + Coeffs(4);

>> polycoeff([3 4 2 1],10)

ans =

3421

(c) 2009 Brian Funt, Simon Fraser University 122

Page 123: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

polycoeffmult (command window example)>> x=10x =

10>> Terms= [x^3, x^2 , x, 1]Terms =

1000 100 10 1

>> Coeffs=[3 4 2 1]Coeffs =

3 4 2 1

>> 3*1000 + 4*100 + 2*10 + 1*1ans =

34213421

>> dot(Coeffs,Terms)ans =

3421

(c) 2009 Brian Funt, Simon Fraser University 123

3421

Page 124: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Dot product

a=[1 2 3];b=[4 5 6];

>> dot(a,b)ans =

A

ans 32

>> 1*4 + 2*5 + 3*6Bθ

ans =32

%dot product is commutative|A|cos(θ) = (A●B)/|B|

% p>> dot(b,a)ans =

32

(c) 2009 Brian Funt, Simon Fraser University 124

Page 125: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

poly using vector dot product

%Evaluate a degree 3 polynomial%Coeffs is a vector of the four coefficients%Coeffs is a vector of the four coefficients%x is the value of the variablefunction polyout = polycoeffmult(Coeffs, x)

Terms= [x^3, x^2 , x, 1];

%Take vector dot product of coefficients with the termspolyout = dot(Coeffs,Terms);

>> polycoeffmult([3 4 2 1],10)

ans =

3421

(c) 2009 Brian Funt, Simon Fraser University 125

3421

Page 126: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try

)sin(753

++=xxxxx

(1) Write a second version of sine, mysinB(x), modelled on polycoeffmult

....!7!5!3

)sin( +−+−= xx

(2) Write your own version of dot product. Call it mydot(2) Write your own version of dot product. Call it mydot

(3) Write a function Time2Minutes(hour, minute) that converts a combination of hours and minutes to just the total number of minutes. E.g. Time2Minutes(10,15) returns the answer 615.

(4) Write a function mymedian that computes the median of a(4) Write a function, mymedian, that computes the median of a vector of numbers

e..g., mymedian([3 5 6 9 10]) would return 6mymedian([6 3 5 10 9]) also returns 6

D t M tl b’ di

(c) 2009 Brian Funt, Simon Fraser University 126

Do not use Matlab’s median.

Page 127: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 10 Fall 2009

Last timeLast timePolynomial evaluation

Various stagesgLeft of with using dot product of coefficients and termsReview that now

(c) 2009 Brian Funt, Simon Fraser University 127

Page 128: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

poly using vector dot product

%Evaluate a degree 3 polynomial%Coeffs is a vector of the four coefficients%Coeffs is a vector of the four coefficients%x is the value of the variablefunction polyout = polycoeffmult(Coeffs, x)

Terms= [x^3, x^2 , x, 1];

%Take vector dot product of coefficients with the termspolyout = dot(Coeffs,Terms);

>> polycoeffmult([3 4 2 1],10)

ans =

3421

(c) 2009 Brian Funt, Simon Fraser University 128

3421

Page 129: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

polyn for arbitrary polynomialsp y y p y

IfIfx=5Coeffs=[3 4 2 1]

Then the polynomial is 3*53 + 4*52 + 2*5 + 1

How about the polyn if Coeffs=[3 5 6 7 8 3 1]?How about the polyn if Coeffs [3 5 6 7 8 … 3 1]?

One arbitrary coefficient example

(c) 2009 Brian Funt, Simon Fraser University 129

One arbitrary coefficient example

Page 130: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Step by Step -- if Coeffs=[3 5 6 7 8 … 3 1]p y p [ ]

if Coeffs=[3 5 6 7 8 3 1]if Coeffs [3 5 6 7 8 … 3 1]

Then the polynomial is3 n 1+5 n 2+6 n 3+7 n 4+8 n 5+ +3 +13xn-1+5xn-2+6xn-3+7xn-4+8xn-5+…+3x+1

xn 1+xn 2+xn 3+xn 4+xn 5+ +x+1

Coeffs=[3 5 6 7 8 … 3 1]Dot product

xn-1+xn-2+xn-3+xn-4+xn-5+…+x+1

?(c) 2009 Brian Funt, Simon Fraser University 130

?

Page 131: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Step by Step -- if coefficient is arbitraryp y p y

xn-1+xn-2+xn-3+xn-4+xn-5+ +x+1? x +x +x +x +x +…+x+1?

The length of (Coeffs=[3 5 6 7 8 … 3 1])

(x, x, x, x, x, …, x, x).^(n-1, n-2, n-3, n-4, n-5, …, 1, 0)

Element-by-element exponentiation

(c) 2009 Brian Funt, Simon Fraser University 131

Element by element exponentiation

Page 132: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Step by Step -- if coefficient is arbitraryp y p y

Length = n = length of Coeffs

(x, x, x, x, x, …, x, x) (n-1, n-2, n-3, n-4, n-5, …, 1, 0)

(1, 1, 1, 1, 1, …, 1, 1) * x

n-1:-1:0ones(1,n)

(c) 2009 Brian Funt, Simon Fraser University 132

Page 133: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Step through polyn_script in command windowx=5Coeffs=[3 4 2 1]

n = length(Coeffs) %n as the number of termsxs = ones(1 n)*xxs = ones(1,n) x %Create vector of n copies of the value of x

exponents = n 1: 1:0

Bottom-UpDesignexponents = n-1:-1:0

%vector of n-1, n-2, ...,0 to use as exponentspowers = xs.^exponents% t f ^( 1) ^( 2) 1

Design

%vector of x^(n-1), x^(n-2),...,1

polyout = dot(Coeffs,powers) %d t d t f ffi i t ith

(c) 2009 Brian Funt, Simon Fraser University 133

%dot product of coefficients with powers

Page 134: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

polyn for arbitrary polynomials

%Evaluate a polynomial of arbitrary degree%Coeffs is a vector of coefficients [a b c ]%Coeffs is a vector of coefficients [a b c ....]%x is the value of the variablefunction polyout = polyn(Coeffs, x)

n = length(Coeffs); %n as the number of termsxs = ones(1,n)*x; %Create vector of n copies of the value of x

exponents = n-1:-1:0; %vector of n-1, n-2, ...,0 to use as exponentspowers = xs.^exponents; %vector of x^(n-1), x^(n-2),...,1

polyout = dot(Coeffs, powers); %dot product of coefficients with powers

(c) 2009 Brian Funt, Simon Fraser University 134

Page 135: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try

)i (753 xxx

(1) Basing your function on the strategy illustrated by polyn, write a third version of sin, mysinC(x,n), that evaluates the first n terms of the series

....!7!5!3

)sin( +−+−= xx

Also from last lecture

(2) Write a function Time2Minutes(hour, minute) that converts a combination of hours and minutes to just the total number of minutes E g Time2Minutes(10 15) returns the answerof minutes. E.g. Time2Minutes(10,15) returns the answer 615.

(3) Write a function, mymedian, that computes the median of a vector of numbers

e..g., mymedian([3 5 6 9 10]) would return 6mymedian([6 3 5 10 9]) also returns 6

Do not use Matlab’s median

(c) 2009 Brian Funt, Simon Fraser University 135

Do not use Matlab s median.

Page 136: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 11 Fall 2009

Last timeLast timeEvaluating polynomials of an arbitrary number of termsWorking on the “To Try” mysinC(x,n) to modelledon polyn(coefficientvector, x)

(c) 2009 Brian Funt, Simon Fraser University 136

Page 137: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try at Last Time

Basing your function on the strategy illustrated by l it thi d i f i i C( )polyn, write a third version of sin, mysinC(x,n),

that evaluates the first n terms of the series

753 xxx ....!7!5!3

)sin( +−+−=xxxxx

(c) 2009 Brian Funt, Simon Fraser University 137

Page 138: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Step through polyn_script in command window

x=5Coeffs=[3 5 6 7 8 3 1]

3xn-1+5xn-2+6xn-3+7xn-4+8xn-5+…+3x+1Coeffs=[3 5 6 7 8 … 3 1]

n = length(Coeffs)n = length(Coeffs) %n as the number of termsxs = ones(1,n)*x %Create vector of n copies of the value of x

Bottom-UpDesign%Create vector of n copies of the value of x

exponents = n-1:-1:0 %vector of n-1, n-2, ...,0 to use as exponents

^ t

Design

powers = xs.^exponents%vector of x^(n-1), x^(n-2),...,1polyout = dot(Coeffs,powers) %d t d t f ffi i t ith

(c) 2009 Brian Funt, Simon Fraser University 138

%dot product of coefficients with powers

Page 139: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Solution Steps -- if Coeffs=[3 5 6 7 8 … 3 1]

n-1:-1:0

ones(1, n)

(1, 1, 1, 1, 1, …, 1, 1) xn 1: 1:0

*

(x, x, x, x, x, …, x, x) (n-1, n-2, n-3, n-4, n-5, …, 1, 0).^

(xn-1, xn-2, xn-3, xn-4, xn-5, …, x, 1) Coeffs=[3 5 6 7 8 … 3 1]Dot

3xn-1+5xn-2+6xn-3+7xn-4+8xn-5+…+3x+1(if Coeffs=[3 5 6 7 8 3 1])

(c) 2009 Brian Funt, Simon Fraser University 139

(if Coeffs=[3 5 6 7 8 … 3 1])

Page 140: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Solution Steps -- ....!7!5!3

)sin(753

+−+−=xxxxx

1:2:2n-1ones(1, n) factorial(1:2:2n-1)

(1, 1, 1, 1, …, 1) x

1:2:2n 1

*0:1:n-1

factorial(1, 3, 5, 7, 9, …, 2n-1)

(1 1 1 1 1 ) / (1 3! 5! 7! 9! )

-1 (0, 1, 2, 3, …, n-1).^

(x, x, x, x, …, x) (1, 3, 5, 7, …, 2n-1).^(1, -1, 1, -1, 1, …) ./ (1, 3!, 5!, 7!, 9!, …)

(x, x3, x5, x7, …, x2n-1) Dot

7!5!3!i ( ) 753

,...)9!1,7!1,5!1,3!1(1, +−+−

(c) 2009 Brian Funt, Simon Fraser University 140

...7!x5!x3!xxsin(x) 753 +−+−=

Page 141: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try ....!7!5!3

)sin(753

+−+−=xxxxx

(1) Write a SCRIPT to evaluate sine. Call it mysinsript.m At the beginning of the script file assign values to the variables n and x. Compute the sin(x) using n terms of the sin series. Leave semicolons off your Matlab statements so that o can see the intermediate res lts as o r script r nsstatements so that you can see the intermediate results as your script runs.

(2) After your script runs correctly, copy and paste it into a function mysinC(x,n). Add semi-colons to suppress the intermediate results.pp

Also from before

(3) W it f ti Ti 2Mi t (h i t ) th t t bi ti(3) Write a function Time2Minutes(hour, minute) that converts a combination of hours and minutes to just the total number of minutes. E.g. Time2Minutes(10,15) returns the answer 615.

(4) Write a function, mymedian, that computes the median of a vector of numbers. E.g., mymedian([3 5 6 9 10]) would return 6

mymedian([6 3 5 10 9]) also returns 6Do not use Matlab’s median

(c) 2009 Brian Funt, Simon Fraser University 141

Do not use Matlab’s median.

Page 142: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 12 Fall 2009

Last three lectures with YiLast three lectures with YiEvaluating polynomials

Example of increasing generalityp g g yand of increasing sophistication

In case you’re wonderingMidterm has not been scheduled yet

(c) 2009 Brian Funt, Simon Fraser University 142

Page 143: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Reading and Display Images

Images are just matricesImages are just matricesimagematrix = imread(filename)image values range from 0 255image values range from 0-255To save memory, storage format is special

W ’ll i hi i fWe’ll ignore this issue for now.However, must convert format using “double”

i d bl (i d(‘i fil j ’))e.g., img=double(imread(‘image_file.jpg’));Display image in Matlab figure window with

imshow(img, [0 255])(c) 2009 Brian Funt, Simon Fraser University 143

Page 144: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To TryWrite the following functions

(1) myimread(filename)(1) myimread(filename)Reads in an image from the named file and converts it to double and returns the image as a matrix

(2) myimshow(input_image)Displays the image input_image using imshow with the range [0 255]

(3) Test myimshow(myimread(‘VeniceBW.jpg’))

(4) scalebrightness(in_image, factor)Scales the intensities of the image contained in the matrix input_image by the amount specified by factor. Test with values 0 < factor < 10. Also testthe amount specified by factor. Test with values 0 factor 10. Also test with small ‘images’ such as magic(4) as well as the full Venice image that I sent you by e-mail.

(c) 2009 Brian Funt, Simon Fraser University 144

Page 145: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Computing Area of a Polygon

“Programming Project”Programming ProjectFrom C Program Design for Engineers, Hanlyand Koffman, 2001, page 359., , p g

Polygon to be input as series of (x,y) coordinatesas series of (x,y) coordinateslast point must equal the first

Formula to use for n points:Formula to use for n points:

∑−

++ −+=2

11 ))((21 n

iiii yyxxA

(c) 2009 Brian Funt, Simon Fraser University 145

∑=02 i

Page 146: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Representing the Polygon>> points=[4 0; 4 7.5; 7 7.5; 7 3; 9 0; 7 0; 4 0]points =

4 0000 04.0000 04.0000 7.50007.0000 7.50007.0000 3.00009.0000 07.0000 04.0000 0

>> polygon_area(points)ans =

25.5000

>> polygon_area([4 0; 4 7.5; 7 7.5; 7 3; 9 0; 7 0; 4 0])ans =

25 5000

(c) 2009 Brian Funt, Simon Fraser University 146

25.5000

Page 147: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

polygon_area(points)%Input points is a nx2 matrix of (x,y) coordinates defining a polygon%The last point must equal the first point for the polygon to be closed.

function area = polygon_area(points)x=points(:,1); %create vectors of the x and y's separatelyy=points(:,2);

x_i = x(1:end-1); %copy of all x's excluding the last oney_i = y(1:end-1);

x_i1 = x(2:end); %copy of all x's excluding first oney_i1 = y(2:end);%Calculate area based on the formula from p 359 of%"C Program Design for Engineers " Hanly and Koffman 2001% C Program Design for Engineers, Hanly and Koffman, 2001% area = 0.5*abs(sum((x_i1 + x_i) .* (y_i1 - y_i)));sumx = x_i1 + x_i;diffy = y_i1 - y_i;

0 5* b ( ( * diff )) ∑−

++ −+=2

11 ))((21 n

iiii yyxxA

(c) 2009 Brian Funt, Simon Fraser University 147

area = 0.5*abs(sum(sumx .* diffy)); ∑=

++0

112 iiiii

Page 148: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

points = [0 0; 0 2 ; 4 2; 4 0; 0 0]0 00 20 24 24 00 0

>> x_i1 = x(2:end)x i1=

>> x=points(:,1)x =

0

_04400

044

0

>> sumx = x_i1 + x_i

0

>> x_i = x(1:end-1)x i =

sumx =048

0+00+44+4x_i

0044

84

4+44+0

(c) 2009 Brian Funt, Simon Fraser University 148

4

Page 149: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

points = [0 0; 0 2 ; 4 2; 4 0; 0 0]>> y=points(:,2)y =

>> diffy = y_i1 - y_idiffy =y

0220

diffy20

-200

0

>> y i = y(1:end-1)

0

sumx =0 y_i y(1:end 1)

y_i =022

0484

20

>> y_i1 = y(2:end)

sumx .* diffyans =

0y_ y( )y_i1 =

220

0-16

0

(c) 2009 Brian Funt, Simon Fraser University 149

00

Page 150: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Script version of polygon_area

%script for demonstrating polygon_area%f nction area pol gon area(points)%function area = polygon_area(points)points=[4 0; 4 7.5; 7 7.5; 7 3; 9 0; 7 0; 4 0]

x=points(:,1)p ( )y=points(:,2)

x_i = x(1:end-1)y i = y(1:end 1)y_i = y(1:end-1)

x_i1 = x(2:end) y_i1 = y(2:end)

sumx = x_i1 + x_idiffy = y_i1 - y_iarea = 0 5*abs(sum(sumx * diffy))

(c) 2009 Brian Funt, Simon Fraser University 150

area 0.5 abs(sum(sumx . diffy))

Page 151: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 13 Fall 2009

Last lectureLast lectureImagesProgramming ‘project’ of polygon areaProgramming project of polygon area

Quiz will be Wednesday October 21, 2009y

(c) 2009 Brian Funt, Simon Fraser University 151

Page 152: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Computing Area of a Polygon

“Programming Project”Programming ProjectFrom C Program Design for Engineers, Hanlyand Koffman, 2001, page 359., , p g

Polygon to be input as series of (x,y) coordinatesas series of (x,y) coordinateslast point must equal the first

Formula to use for n points:Formula to use for n points:

∑−

++ −+=2

11 ))((21 n

iiii yyxxA

(c) 2009 Brian Funt, Simon Fraser University 152

∑=02 i

Page 153: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Representing the Polygon>> points=[4 0; 4 7.5; 7 7.5; 7 3; 9 0; 7 0; 4 0]points =

4 0000 04.0000 04.0000 7.50007.0000 7.50007.0000 3.00009.0000 07.0000 04.0000 0

>> polygon_area(points)ans =

25.5000

>> polygon_area([4 0; 4 7.5; 7 7.5; 7 3; 9 0; 7 0; 4 0])ans =

25 5000

(c) 2009 Brian Funt, Simon Fraser University 153

25.5000

Page 154: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

polygon_area(points)%Input points is a nx2 matrix of (x,y) coordinates defining a polygon%The last point must equal the first point for the polygon to be closed.

function area = polygon_area(points)x=points(:,1); %create vectors of the x and y's separatelyy=points(:,2);

x_i = x(1:end-1); %copy of all x's excluding the last oney_i = y(1:end-1);

x_i1 = x(2:end); %copy of all x's excluding first oney_i1 = y(2:end);%Calculate area based on the formula from p 359 of%"C Program Design for Engineers " Hanly and Koffman 2001% C Program Design for Engineers, Hanly and Koffman, 2001% area = 0.5*abs(sum((x_i1 + x_i) .* (y_i1 - y_i)));sumx = x_i1 + x_i;diffy = y_i1 - y_i;

0 5* b ( ( * diff )) ∑−

++ −+=2

11 ))((21 n

iiii yyxxA

(c) 2009 Brian Funt, Simon Fraser University 154

area = 0.5*abs(sum(sumx .* diffy)); ∑=

++0

112 iiiii

Page 155: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

points = [0 0; 0 2 ; 4 2; 4 0; 0 0]0 00 20 24 24 00 0

>> x_i1 = x(2:end)x i1=

>> x=points(:,1)x =

0

_04400

044

0

>> sumx = x_i1 + x_i

0

>> x_i = x(1:end-1)x i =

sumx =048

0+00+44+4x_i

0044

84

4+44+0

(c) 2009 Brian Funt, Simon Fraser University 155

4

Page 156: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

points = [0 0; 0 2 ; 4 2; 4 0; 0 0]>> y=points(:,2)y =

>> diffy = y_i1 - y_idiffy =y

0220

diffy20

-200

0

>> y i = y(1:end-1)

0

sumx =0 y_i y(1:end 1)

y_i =022

0484

20

>> y_i1 = y(2:end)

sumx .* diffyans =

0y_ y( )y_i1 =

220

0-16

0

(c) 2009 Brian Funt, Simon Fraser University 156

00

Page 157: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try(1) Write a script verticalscript m to compute the biggest vertical (i e y) change (up or(1) Write a script verticalscript.m to compute the biggest vertical (i.e., y) change (up or down) along a path. The path will be represented as a matrix of vertices. Model your script on the polygon_area function. Leave off semi-colons so you can see the intermediate results. Each vertex is one row in the matrix. At the beginning of the script assign a variable named path to the matrix of points Unlike the polygon case the last point doesvariable named path to the matrix of points. Unlike the polygon case, the last point does not need to equal the first one since the path does not have to be closed. A sample path ispath = [0 0; 0 1; 1 1; 1 0; 3 2; 6 1]

(2) Use “Save As” to make a copy of your script file in into a file vertical m and then edit(2) Use Save As to make a copy of your script file in into a file vertical.m and then edit the new file to become a function vertical(path). Add semicolons.>> vertical([0 0; 0 1; 1 1; 1 0; 3 2; 6 1])ans =

22

(3) Modify vertical.m so that it returns both the biggest change and the coordinates of the 2 points it occurs between.[change point1 point2]=vertical([0 0; 0 1; 1 1; 1 0; 3 2; 6 1])[change point1 point2]=vertical([0 0; 0 1; 1 1; 1 0; 3 2; 6 1])change =

2point1 =

1 0

(c) 2009 Brian Funt, Simon Fraser University 157

1 0point2 =

3 2

Page 158: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Land Boundary Survey

Programming Project 1 page 479Programming Project 1 page 479C Program Design for EngineersInput a matrix of points as for polygon area caseInput a matrix of points as for polygon_area caseCalculate

Total length of property boundaryg p p y yTotal area of the property

Distance between points (xi,yi) and (xj, yj) is

22 )()( jiji yyxxd −+−=

(c) 2009 Brian Funt, Simon Fraser University 158

jj

Page 159: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

distance(p1, p2)%compute the Euclidean distances between pairs of points %contained in the rows of p1 and p2%Works for points in n dimensions%Works for points in n dimensions.%sample input call distance([1 2; 3 4],[5 6; 8 9])

function dist = distance (p1, p2)

vec = p1-p2;squares= vec.^2dist = sqrt(sum(squares')); %transpose included so we sum the rowsdist sqrt(sum(squares )); %transpose included so we sum the rowsdist = dist' %return a column vector of distances

B t f th t i t ti i th t th d l k lik it’ fBeauty of the matrix notation is that the code looks like it’s fora single pair of points, but it works for a whole group of points.

(c) 2009 Brian Funt, Simon Fraser University 159

Page 160: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Distance example for 3 pairs of points

distance([1 2; 3 4; 0 1],[0 0; -3 -3; 1 -1])

ans =

2.23619 21959.21952.2361

(c) 2009 Brian Funt, Simon Fraser University 160

Page 161: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

p1=[1 2; 3 4]

1

squares= vec.^2

p1 =

1 23 4

squares =

16 1625 25

>> p2=[5 6; 8 9]

p2 =

25 25

>> squares'

dist = sqrt(sum(squares'))

dist =p2 =

5 68 9

ans =

16 2516 25

5.6569 7.0711

dist'

>> vec = p1-p2

vec =

16 25

>> sum(squares')ans =

5 6569vec =

-4 -4-5 -5

ans =

32 50

5.65697.0711

(c) 2009 Brian Funt, Simon Fraser University 161

Page 162: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

survey(points)

%Compute perimeter and area as in Project 1 of%Compute perimeter and area as in Project 1 of % Hanly and Koffman p. 479function [perimeter area] = survey(points)% simple test input points=[0 0; 0 1; 1 1; 1 0; 0 0]

g1=points(1:end-1,:);g2=points(2:end,:);

dists = distance(g1,g2);

perimeter = sum(dists);area = polygon area(points);area = polygon_area(points);

(c) 2009 Brian Funt, Simon Fraser University 162

Page 163: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Script version of survey

%function [perimeter area] = survey(points)%function [perimeter area] survey(points)

points=[0 0; 0 1; 1 1; 1 0; 0 0]

1 i (1 d 1 )g1=points(1:end-1,:)g2=points(2:end,:)

dists = distance(g1,g2)dists distance(g1,g2)

perimeter = sum(dists)

l ( i t )area = polygon_area(points)

(c) 2009 Brian Funt, Simon Fraser University 163

Page 164: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 14 Fall 2009

Last lectureLast lectureProgramming ‘project’ of land survey

distance functionperimeter

(c) 2009 Brian Funt, Simon Fraser University 164

Page 165: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Land Boundary Survey

Programming Project 1 page 479Programming Project 1 page 479C Program Design for EngineersInput a matrix of points as for polygon area caseInput a matrix of points as for polygon_area caseCalculate

Total length of property boundaryg p p y yTotal area of the property

Distance between points (xi,yi) and (xj, yj) is

22 )()( jiji yyxxd −+−=

(c) 2009 Brian Funt, Simon Fraser University 165

jj

Page 166: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

distance(p1, p2)%compute the Euclidean distances between pairs of points %contained in the rows of p1 and p2%Works for points in n dimensions%Works for points in n dimensions.%sample input call distance([1 2; 3 4],[5 6; 8 9])

function dist = distance (p1, p2)

vec = p1-p2;squares= vec.^2dist = sqrt(sum(squares')); %transpose included so we sum the rowsdist sqrt(sum(squares )); %transpose included so we sum the rowsdist = dist' %return a column vector of distances

B t f th t i t ti i th t th d l k lik it’ fBeauty of the matrix notation is that the code looks like it’s fora single pair of points, but it works for a whole group of points.

(c) 2009 Brian Funt, Simon Fraser University 166

Page 167: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

survey(points)

%Compute perimeter and area as in Project 1 of%Compute perimeter and area as in Project 1 of % Hanly and Koffman p. 479function [perimeter area] = survey(points)% simple test input points=[0 0; 0 1; 1 1; 1 0; 0 0]

g1=points(1:end-1,:);g2=points(2:end,:);

dists = distance(g1,g2);

perimeter = sum(dists);area = polygon area(points);area = polygon_area(points);

(c) 2009 Brian Funt, Simon Fraser University 167

Page 168: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

CMPT 102 Assignment 3 Hint Fall 2009

Write a function fourfold(image) that returnsWrite a function fourfold(image) that returns an image containing 4 copies of the input image. gResulting image will be

twice as high and widetwice as high and widefour times the area

(c) 2009 Brian Funt, Simon Fraser University 168

Page 169: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Venice fourfold img=myimread('VeniceBW.jpg');>> v4 = fourfold(img);>> v4 = fourfold(img);>> myimshow(v4)

(c) 2009 Brian Funt, Simon Fraser University 169

Page 170: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

fourfold(image)

%Produce an image that contains 4 copies of the input imagefunction fi = fourfold(img)

[r,c] = size(img);

fi=zeros(size(img)*2); %create 'image' of zeroes to hold 4 copies

fi(1:r,1:c) = img; %copy into upper left quadrantfi(r+1:end,1:c)= img; %copy into lower left quadrantfi(1:r,c+1:end)= img; %upper right quadrantfi(r+1:end,c+1:end) = img; %lower right quadrant

imshow(fi,[0,255]) %display the resulting image

(c) 2009 Brian Funt, Simon Fraser University 170

Page 171: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try(1) Generalize ‘distance’ to work with points in 3D. Distance between points (xi,yi,zi,) and (xj, yj,zj) is

222 )()()( jijiji zzyyxxd −+−+−=

(2) Write a function biggest_segment(path) that returns a matrix with 2 rows in which the rows contain the neighbouring points along the path with the biggestwhich the rows contain the neighbouring points along the path with the biggest distance between them. For example,>> path = [0 0 0; 0 1 0; 1 1 1; 1 1 0; 3 2 3; 6 1 5 ;7 2 5];>> biggest_segment(path)ans =

1 1 03 2 3

(3) Write a function mark_spot(image, loc) that marks the pixel specified by loc with a “+” made up as( ) _ p ( g ) p p y p000000000111001111111 (but use 255’s for the 1’s shown here). 11111111111111 111111100111000000000

(c) 2009 Brian Funt, Simon Fraser University 171

Page 172: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

mark_spot example>> a=myimread('VeniceBW.jpg');>> b=mark_spot(a,[500 600]);>> myimshow(b)

You can hardly see the spot but it’s there inside the red ellipseinside the red ellipse. It’s more obvious when you zoom the image.g

(c) 2009 Brian Funt, Simon Fraser University 172

Page 173: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 15 Fall 2009

Last lectureLast lecture

Example of fourfoldpLand survey

Spent a long time on the To Try

(c) 2009 Brian Funt, Simon Fraser University 173

Page 174: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Histogramming using histA histogram gives the frequency of occurrence of values

N = HIST(Y,X), where X is a vector, returns the distribution of Y among bins

Can plot a histogram as a bar graph

a=[ 1 2 1 3 4 5 5 5 5 1 2 3]h hi t( [1 5])returns the distribution of Y among bins

with centers specified by X. The first bin includes data between -Inf and the first center and the last bin includes d t b t th l t bi d I f

>> h=hist(a,[1:5])h =

3 2 2 1 4>> bar(h)data between the last bin and Inf. ( )

Bar graph shows histogram of

[ 1 2 1 3 4 5 5 5 5 1 2 3]

(c) 2009 Brian Funt, Simon Fraser University 174

Page 175: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try (briefly)n=9s=0.1a=rand(n 1);a=rand(n,1);b=hist(a,s/2:s:1-s/2);bar(b)

(1) Try the above code

(2) Experiment with different values of n and s

(3) Try using randn instead of rand as below

a=randn(n,1);>> b=hist(a,-5:.1:5);>> bar(b)

(c) 2009 Brian Funt, Simon Fraser University 175

Page 176: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

A sample program fromA sample program from previous CMPT 102 text

(c) 2009 Brian Funt, Simon Fraser University 176

Page 177: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

(c) 2009 Brian Funt, Simon Fraser University 177

Page 178: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

(c) 2009 Brian Funt, Simon Fraser University 178

Page 179: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

// indicates a comment

Variable declarations required

Open disk data fileand read data into grid array

Done by Matlab’s ‘hist’

(c) 2009 Brian Funt, Simon Fraser University 179

Done by Matlab’s ‘max’

Page 180: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

O t tti th ltOutputting the result

Total of 30 lines of C

(c) 2009 Brian Funt, Simon Fraser University 180

Page 181: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

function [direction percentage] = wind_analysis (wind_table)

%An array of the possible directions in human-readable formdirections= ['N '; 'NE'; 'E '; 'SE'; 'S '; 'SW'; 'W '; 'NW'];

%Histogram all the values in wind table%Histogram all the values in wind_table%There are 8 wind directions N, NE, E, etc. so histogram with 8 bins.histogram = hist(wind_table(:),1:7);

%Find where the max histogram count occurs%highest bin count is the dominant wind direction[maxval, numerical_direction]=max(histogram(:));

%Each row of directions is 2 characters long as in 'N ' and 'NE'direction=directions(numerical_direction,1:2);

%Percentage of time the wind is from that direction is maxval%normalized by total number of elements in the wind_tablepercentage = maxval/length(wind_table(:))* 100;

(c) 2009 Brian Funt, Simon Fraser University 181

Total of 6 lines of Matlab

Page 182: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Script version of wind_analysis

%Script to demonstrate workings of%function [direction percentage] = wind analysis (wind table)%function [direction percentage] = wind_analysis (wind_table)

wind_table = [4 4 5 5 4; 3 4 4 4 5; 4 5 4 4 4; 4 4 4 4 4; 4 4 4 4 5]

directions= ['N '; 'NE'; 'E '; 'SE'; 'S '; 'SW'; 'W '; 'NW']

histogram = hist(wind_table(:),1:8)

[maxval, numerical_direction]=max(histogram(:))

direction=directions(numerical_direction,1:2)

percentage = maxval/length(wind_table(:))* 100

(c) 2009 Brian Funt, Simon Fraser University 182

Page 183: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Chapter 8 Logic Function & Control Structures

In programming we clearly need some way ofIn programming we clearly need some way of saying things like,

“If it’s raining, then I’ll use my umbrella, otherwise I won’t”“If it’s raining and it’s not windy, I’ll use my umbrella.”“If SFU’ 50 th l b t ”“If SFU’s age = 50 then celebrate.”

(c) 2007 Brian Funt, Simon Fraser University 183

Page 184: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Relational Operators

<<><=<=>>=== Equals. Need == to tell from assignment~= Not equal

(c) 2007 Brian Funt, Simon Fraser University 184

Page 185: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

False is zero. True is non-zero>> 5<8ans =

1

%With variables too>> x=5; y=8

1

>> 8<5ans =

y =8

>> x < y0

>> 6=6??? 6=6

>> x < yans =

1

??? 6=6Error: The expression to the left of the equals sign is not a valid target for an assignment.

%With vectors too>> a=1:3; b=3:-1:1;>> a == b

>> 6==6ans =

1

ans =

0 1 0

(c) 2007 Brian Funt, Simon Fraser University 185

1

Page 186: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

>> a=ones(3)a =

>> a<bans =a

1 1 11 1 11 1 1

ans =1 0 11 1 11 1 1

>> b=magic(3)b =

8 1 6

>> a>bans =

0 0 03 5 74 9 2

>> a==b

0 0 00 0 00 0 0

b>> a==bans =

0 1 0

>> a~=bans =

1 0 10 0 00 0 0

1 0 11 1 11 1 1

(c) 2007 Brian Funt, Simon Fraser University 186

Page 187: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Logical Operators

& (for and)>> 2<3 & 3<2

& (for and)~ (for not)| (for or)

ans =0

| (for or) >> 2<3 & ~3<2

ans =11

>> 2<3 | 3<2

ans =

1

(c) 2007 Brian Funt, Simon Fraser University 187

Page 188: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try

Write a function similar(M,N) that compares the elements of matrix MWrite a function similar(M,N) that compares the elements of matrix M to those in matrix N and returns True (i.e., 1) if 50% or more of them are the same, and False (i.e. 0) otherwise. You may assume M and N are the same size. Some examples follow:

similar(magic(3), magic(3)')ans =

0>> similar(magic(3) magic(3))>> similar(magic(3), magic(3))ans =

1>> similar([1 2 3],[0 2 3])ans =ans

1>> similar([1 2 3],[0 2 4])ans =

0

(c) 2007-08 Brian Funt, Simon Fraser University 188

0

Page 189: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try from earlier

(3) Write a function mark_spot(image, loc) that marks the pixel specified by loc with a “+” made up as000000000111001111111 (but use 255’s for the 1’s shown here). ( )1111111 1111111001110000000000000000

See sample output included in Lecture 14 slides.

(c) 2009 Brian Funt, Simon Fraser University 189

Page 190: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 16 Fall 2009

Last lectureLast lecture

Histogramming with histg gWind analysis projectRelational operators pLogical operators

(c) 2009 Brian Funt, Simon Fraser University 190

Page 191: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Relational Operators

<<><=<=>>=== Equals. Need == to tell from assignment~= Not equal

(c) 2007 Brian Funt, Simon Fraser University 191

Page 192: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

False is zero. True is non-zero>> 5<8ans =

1

%With variables too>> x=5; y=8

1

>> 8<5ans =

y =8

>> x < y0

>> 6=6??? 6=6

>> x < yans =

1

??? 6=6Error: The expression to the left of the equals sign is not a valid target for an assignment.

%With vectors too>> a=1:3; b=3:-1:1;>> a == b

>> 6==6ans =

1

ans =

0 1 0

(c) 2007 Brian Funt, Simon Fraser University 192

1

Page 193: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Logical Operators

& (for and)>> 2<3 & 3<2

& (for and)~ (for not)| (for or)

ans =0

| (for or) >> 2<3 & ~3<2

ans =11

>> 2<3 | 3<2

ans =

1

(c) 2007 Brian Funt, Simon Fraser University 193

Page 194: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Skipping 8.3 (for now only)

Skipping discussion of “find”find() is very useful but we’ll do it laterfind() is very useful, but we ll do it laterpp. 247-253 (first edition)pp 262-268 (second edition)pp. 262 268 (second edition)

(c) 2007 Brian Funt, Simon Fraser University 194

Page 195: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Printing with ‘disp’disp - Display text or array (quoting Matlab documentation)

Syntax disp(X)

Description

disp(X) displays an array without printing the array name If X contains a textdisp(X) displays an array, without printing the array name. If X contains a text string, the string is displayed.

Another way to display an array on the screen is to type its name, but this y p y y yp ,prints a leading "X=," which is not always desirable.

>> disp(5)55

>> disp(magic(2))1 3

(c) 2009 Brian Funt, Simon Fraser University 195

4 2

Page 196: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

if StatementIdea is just like ‘if’ in English

Form is:

if l i l i

>> a=1;b=2;

if b

>> a=1;b=2;

if logical-comparisonstatement1statement2

>> if a < ba=a+1;disp(a);end

>> if a > ba=a+1;disp(a);end

….end

end2

>>

end

%note nothing prints

(c) 2007 Brian Funt, Simon Fraser University 196

Page 197: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

if with elseLike ‘otherwise’ in English a=1;b=2;

if a < bdisp(a);

Form is:

if logical-comparison

p( );elseb=b+1;disp(b);endif logical comparison

statement1statement2

a=1;b=2;

end1

….else

statement1

>> if a > bdisp(a);elseb=b+1;statement2

….end

b=b+1;disp(b);end

3

(c) 2007 Brian Funt, Simon Fraser University 197

end

Page 198: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

elseif (else combined with another if)if logical-comparison

statement1d = 2;

if d == 1statement2….

elseif logical-comparison

disp('one');

elseif d == 2disp('two');elseif logical comparison

statement1statement2

disp( two );

elseif d ==3;disp('three');

….else

statement1else

disp(‘Not 123');end

statement2….

end

end

two>>

(c) 2007 Brian Funt, Simon Fraser University 198

end

Page 199: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Evaluating the weather

HotHotOver 30

WarmWarmOver 20 and up to 30

CoolCoolOver 5 and up to 20

ColdCold5 and under

(c) 2007 Brian Funt, Simon Fraser University 199

Page 200: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

% weather(temperature) evaluates the weather in terms of it% being hot, warm, cool, or cold.f ti th (t)function e = weather(t)if (t>30) e = 'hot';elseif (t>20) e ='warm'; %Note it’s not t<=30 & t>20elseif (t>5) e='cool';( ) ;else e='cold';end;

>> weather(20)ans =cool

>> weather(20.1)ans =warm

>> weather(30.1)ans =hot

(c) 2007 Brian Funt, Simon Fraser University 200

hot

Page 201: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try

(1) Write a function numericgrade2lettergrade(g) that takes as input(1) Write a function numericgrade2lettergrade(g) that takes as input a number g representing a grade in the range 0 to 100, and returns the corresponding letter grade. You can use whatever conversion ranges you want (e.g., A above 85, and so on), but to k thi i l j t t t A B C D F D ’tkeep things simple just convert to A, B, C, D, F. Don’t worry about A+, A- etc.

(2) Write a function boxtype(width, depth, height) that determines ( ) yp ( , p , g )whether a box of those dimensions is:(1) cubical

(2) square top and bottom width(2) square top and bottom

(3) neither (1) or (2)

(c) 2007-08 Brian Funt, Simon Fraser University 201

Page 202: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Switch-Case Consider estimating temperature as a function

switch variablecase option1

Consider estimating temperature as a function of words like hot, warm, cool, cold.

%Guess temperature given a description of the weatherstatement1statement2….

%Guess temperature given a description of the weather.function [] = temperature(weather)

switch weather….case option2

statement1statement2

case 'hot'disp('I guess it''s about 33 degrees.')

case 'warm'disp('I guess it''s about 24 degrees ')statement2

….otherwise

disp( I guess it s about 24 degrees. )case 'cool'

disp('I guess it''s about 16 degrees.')case 'cold'

statement1….

end

disp('I guess it''s about 5 degrees.')otherwise

disp('Could you explain further please?')end

(c) 2007 Brian Funt, Simon Fraser University 202

end end

Page 203: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

menu with switch

in=menu(‘message’, ‘button1’, ‘button2’,…)in menu( message , button1 , button2 ,…)Very simple way to create menu-based user interactionThe message is displayedg p yButtons are displayed with corresponding labels

menu returns the number of the button clicked onConvenient to use switch to deal with the button cases

(c) 2007 Brian Funt, Simon Fraser University 203

Page 204: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

menu-based temperature guessing

%Print a guess as to the temperature given a description of the weather.function [] = temperature menu()function [] = temperature_menu()

weather=menu('How would you describe the weather?', 'hot', 'warm', 'cool', 'cold');switch weather

case 1 %Selection is by button number, not button label.disp('I guess it''s about 33 degrees.')

case 2disp('I guess it''s about 24 degrees.')disp( I guess it s about 24 degrees. )

case 3disp('I guess it''s about 16 degrees.')

case 4di ('I it'' b t 5 d ')disp('I guess it''s about 5 degrees.')

otherwisedisp('Error in button reading')

end

(c) 2007 Brian Funt, Simon Fraser University 204

Page 205: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 17 Fall 2009

Last lectureLast lectureif statementswitch statementswitch statement

(c) 2009 Brian Funt, Simon Fraser University 205

Page 206: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Repetition using for and while

General Form of for Useful when you want

for index = [matrix]

statement1

to do the same operations over and over againstate e t

statement2….

end

over again.

Repeating statements is called:iterationlooping

Matlab is clever (and efficient) in that it has built-in looping features

(c) 2009 Brian Funt, Simon Fraser University 206

Page 207: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

for loop examples

for k = 1:3 disp(k); end >> for k = [8 -1 7] disp(k); endp( );123

[ ] p( );8

-17

>> for k = 1:3 disp(k)end

1

for k = ['b' 'x'] disp(k); end;b

123

x

“;” needed unless we go to a new line

(c) 2009 Brian Funt, Simon Fraser University 207

Page 208: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

for and if togetherfor i=2:5

if isprime(i)disp('Prime');disp(i);

endend

Prime2

P iPrime3

Prime

(c) 2009 Brian Funt, Simon Fraser University 208

Page 209: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

for and if and else togetherfor i=2:5

if isprime(i) disp('Prime'); disp(i)

elseelse disp('Not prime'); disp(i)

end %the end of the ifend %then end of the for

Prime2

Prime3

N t iNot prime4

Prime

(c) 2009 Brian Funt, Simon Fraser University 209

5

Page 210: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Summing elements of a vector

%sumfor(v) sums the elements of vector v. function s=sumfor(v)function s=sumfor(v)

%Check that v is a vector, not a matrix.if min(size(v))>1 I expect error checking in

d fs = 'ERROR';else

s=0;for i=1:length(v)

your code from now on

“S t I d t” d “T t”for i=1:length(v) s=s+v(i);

endend

“Smart Indent” under “Text” menu in editor

(c) 2009 Brian Funt, Simon Fraser University 210

Page 211: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

sumfor with disps added >> sumfor([30 20 40])

%sumfor(a) sums the elements of vector v. function s=sumfor(v)

1

0

%Check that v is a vector, not a matrix.if min(size(v))>1

s = 'ERROR';else

2

30else

s=0;for i=1:length(v)

disp(i);

3

50disp(s);s=s+v(i);

endend

50

ans =end

90

(c) 2009 Brian Funt, Simon Fraser University 211

Page 212: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try(1) Write a function prodfor (vec) that uses a for loop to

compute the product of the elements of a vector. df ([3 6 2])>> prodfor([3 6 2])

ans =36

(2) Write a function sumeven(n) that uses a for loop to sum all the even numbers from 1 to n

>> sumeven(9)

ans =

20

(c) 2009 Brian Funt, Simon Fraser University 212

Page 213: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Multiplying a vector by a scalar%Multiply vector v by scalar s using a for loopfunction sv = scalarmultiply(s,v)

sv = v; %Make up a vector that's as big as v. Contents don't matter.len = length(v);

for i=1:lensv(i) = s*v(i);

end

>> scalarmultiply(3, [4 2 -1])

ans =ans

12 6 -3

(c) 2009 Brian Funt, Simon Fraser University 213

Page 214: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Computing Factorial with a for loopfactorial of n is n! = 1*2*3* …*n

% Computing factorial with a for loopfunction fact = factorial(n)

if n<1 %Error checking section. disp('Factorial requires argument >= 1'); fact=[];

lelsefact = 1; %Have to initialize before entering the loopfor i = 1:n

fact = fact * i;fact fact i;end

end

(c) 2009 Brian Funt, Simon Fraser University 214

Page 215: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Factorial with Implicit Looping

% Computing factorial without explicit loopingfunction fact = factorial2(n)function fact = factorial2(n)

if n<1 %Error checking section. disp('Factorial requires argument >= 1'); fact=[];

elsefact = prod(1:n);

endend

>> tic; factorial(10000);tocElapsed time is 0 016227 secondsElapsed time is 0.016227 seconds.

>> tic; factorial2(10000);tocElapsed time is 0.003786 seconds.

(c) 2009 Brian Funt, Simon Fraser University 215

>>

Page 216: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To try

Write a function cumulative(v) that returns a vector with the cummulative sum of v. This is like Matlab’s cumsum. Don’t use cumsum.

>> cumulative([4 2 -1 99])

ans =

4 6 5 104

(c) 2009 Brian Funt, Simon Fraser University 216

Page 217: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

CMPT 102 Lecture 18 Fall 2009

Quiz todayQuiz todayOct 21, 2009

(c) 2009 Brian Funt, Simon Fraser University 217

Page 218: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 19 Fall 2009

Last lectureLast lecturequizbefore that for loopsbefore that, for loops

(c) 2009 Brian Funt, Simon Fraser University 218

Page 219: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Repetition using for and while

General Form of for Useful when you want

for index = [matrix]

statement1

to do the same operations over and over againstate e t

statement2….

end

over again.

Repeating statements is called:iterationlooping

(c) 2009 Brian Funt, Simon Fraser University 219

Page 220: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

for and if and else togetherfor i=2:5

if isprime(i) disp('Prime'); disp(i)

elseelse disp('Not prime'); disp(i)

end %the end of the ifend %then end of the for

Prime2

Prime3

N t iNot prime4

Prime

(c) 2009 Brian Funt, Simon Fraser University 220

5

Page 221: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Summing elements of a vector

%sumfor(v) sums the elements of vector v. function s=sumfor(v)function s=sumfor(v)

%Check that v is a vector, not a matrix.if min(size(v))>1 I expect error checking in

d fs = 'ERROR';else

s=0;for i=1:length(v)

your code from now on

“S t I d t” d “T t”for i=1:length(v) s=s+v(i);

endend

“Smart Indent” under “Text” menu in editor

(c) 2009 Brian Funt, Simon Fraser University 221

Page 222: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Multiplying a vector by a scalar%Multiply vector v by scalar s using a for loopfunction sv = scalarmultiply(s,v)

sv = v; %Make up a vector that's as big as v. Contents don't matter.len = length(v);

for i=1:lensv(i) = s*v(i);

end

>> scalarmultiply(3, [4 2 -1])

ans =ans

12 6 -3

(c) 2009 Brian Funt, Simon Fraser University 222

Page 223: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Nested loops

General Form of for

for index = [matrix]

statement1

for index = [matrix]

statement1state e tstatement2

….end

statement1

for index2 = [matrix2]statementastatementb….

end….

end

(c) 2009 Brian Funt, Simon Fraser University 223

Page 224: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Matrix Addition Example with Error Checking

%addm(a,b) returns the matrix addition a+bfunction sm = addm(a,b)

% t t i f th ltsm = a; %create matrix for the result[rows cols] = size(a);

%Comparison of sizes is vector comparison of both rows p p%and columnsif size(a) == size(b)

for r = 1:rowsfor c = 1:colsfor c = 1:cols

sm(r,c) = a(r,c) + b(r,c);end

endelse disp('Error: matrix dimensions do not match.');end

(c) 2009 Brian Funt, Simon Fraser University 224

Page 225: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Efficiency (lack thereof) of Explicit Loops

a=ones(5000);

>> tic; addm(a a); toc>> tic; addm(a,a); tocElapsed time is 1.124263 seconds.

>> tic; a+a; tocElapsed time is 0.125576 seconds.

(c) 2009 Brian Funt, Simon Fraser University 225

Page 226: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try

Using nested for loops, write a function square(M) that when passed fa matrix M returns a new matrix with every entry of M squared. In

other words square(M) has the same effect as M.^2 but without using the built-in element-wise exponentiation operator.

square(magic(2))

ans =

1 916 4

Continued on next page

(c) 2009 Brian Funt, Simon Fraser University 226

Page 227: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To TryUsing nested for loops, write a function mytranspose(m) which returns the transpose of matrix m. Do not Matlab’s apostrophe operator or its built-in transpose function.

>> m=[magic(3) magic(3)]m =

8 1 6 8 1 6 mytranspose(m)==m'8 1 6 8 1 63 5 7 3 5 74 9 2 4 9 2

>> m transpose(m)

mytranspose(m) m

ans =

1 1 1>> mytranspose(m)ans =

8 3 41 5 9

1 1 11 1 11 1 11 1 1

6 7 28 3 41 5 96 7 2

1 1 11 1 1

(c) 2009 Brian Funt, Simon Fraser University 227

6 7 2

Page 228: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Computing Factorial with a for loopfactorial of n is n! = 1*2*3* …*n

% Computing factorial with a for loopfunction fact = factorial(n)

if n<1 %Error checking section. disp('Factorial requires argument >= 1'); fact=[];

lelsefact = 1; %Have to initialize before entering the loopfor i = 1:n

fact = fact * i;fact fact i;end

end

(c) 2009 Brian Funt, Simon Fraser University 228

Page 229: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Factorial using Factorial% Computing factorial recursivelyfunction fact = factorial3(n)

if n<1 %Error checking section. disp('Factorial requires argument >= 1'); fact=[];

elseif n == 1 fact=1; %Base caseelse fact = n * factorial3(n-1); %Recursive call to factorial3endend

end

f t i l3(1) %T ti b f t i l3(5)factorial3(1) %Testing base caseans =

1

>> factorial3(5)ans =

120

(c) 2009 Brian Funt, Simon Fraser University 229

Page 230: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

while loops

while logical-test

a=0;while a<=10disp(a)a=a+2;

statement1statement2

a a 2;end

0

2….end

2

4

hil 0 i t('E t ') 6

8

while 0 ~= input('Enter zero: ') disp('pay attention')endEnter zero: 8

10 pay attentionEnter zero: 9pay attentionEnter zero: 0

(c) 2009 Brian Funt, Simon Fraser University 230

Enter zero: 0

Page 231: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Factorial using a while loop% Computing factorial4 with a while loopfunction fact = factorial4(n)

if 1 %E h ki iif n<1 %Error checking section. disp('Factorial requires argument >= 1'); fact=[];

elseelsefact = 1; %Have to initialize before entering the loopi=1; %Initialize the looping indexwhile i <= nf t f t*ifact = fact*i;i=i+1;end

end

(c) 2009 Brian Funt, Simon Fraser University 231

Page 232: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 20 Fall 2009

Last lectureLast lectureDiscussed quiz answersnested for loopsnested for loops

(c) 2009 Brian Funt, Simon Fraser University 232

Page 233: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Nested loops

General Form of for

for index = [matrix]

statement1

for index = [matrix]

statement1state e tstatement2

….end

statement1

for index2 = [matrix2]statementastatementb….

end….

end

(c) 2009 Brian Funt, Simon Fraser University 233

Page 234: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Matrix Addition Example with Error Checking

%addm(a,b) returns the matrix addition a+bfunction sm = addm(a,b)

% t t i f th ltsm = a; %create matrix for the result[rows cols] = size(a);

%Comparison of sizes is vector comparison of both rows p p%and columnsif size(a) == size(b)

for r = 1:rowsfor c = 1:colsfor c = 1:cols

sm(r,c) = a(r,c) + b(r,c);end

endelse disp('Error: matrix dimensions do not match.');end

(c) 2009 Brian Funt, Simon Fraser University 234

Page 235: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Factorial using Factorial% Computing factorial recursivelyfunction fact = factorial3(n)

if n<1 %Error checking section. disp('Factorial requires argument >= 1'); fact=[];

elseif n == 1 fact=1; %Base caseelse fact = n * factorial3(n-1); %Recursive call to factorial3endend

end

f t i l3(1) %T ti b f t i l3(5)factorial3(1) %Testing base caseans =

1

>> factorial3(5)ans =

120

(c) 2009 Brian Funt, Simon Fraser University 235

Page 236: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

while loops

while logical-test

a=0;while a<=10disp(a)a=a+2;

statement1statement2

a a 2;end

0

2….end

2

4

hil 0 i t('E t ') 6

8

while 0 ~= input('Enter zero: ') disp('pay attention')endEnter zero: 8

10 pay attentionEnter zero: 9pay attentionEnter zero: 0

(c) 2009 Brian Funt, Simon Fraser University 236

Enter zero: 0

Page 237: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Factorial using a while loop% Computing factorial4 with a while loopfunction fact = factorial4(n)

if 1 %E h ki iif n<1 %Error checking section. disp('Factorial requires argument >= 1'); fact=[];

elseelsefact = 1; %Have to initialize before entering the loopi=1; %Initialize the looping indexwhile i <= nf t f t*ifact = fact*i;i=i+1;end

end

(c) 2009 Brian Funt, Simon Fraser University 237

Page 238: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try

Write a function sumwhile(v) that sums the elements of vector v using a while loop.

w = [3 5 -9 6 2.5];sumwhile(w)

(c) 2009 Brian Funt, Simon Fraser University 238

Page 239: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

findzero to find first zero in vector

>> findzero([1 2; 0 3])>> findzero([1 2; 0 3])findzero only works with vectorsans =

[]

Error checking case

>> findzero([1 2 0 3])ans =

3zero is third element

>> findzero([1 2 4 3])ans =

1-1 is returned to indicate

f-1 no zero was found

(c) 2009 Brian Funt, Simon Fraser University 239

Page 240: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

while with break

% findzero(vector) returns location of the first zero, -1 if there isn’t onefunction loc = findzero(vector)( )[rows cols] = size(vector);if rows ~=1 %Error checking section. Input must be a vector.

disp('findzero only accepts vectors');loc = [];loc = [];

elseloc = 1;while vector(loc)~= 0 %Keep looping until a zero is found (if ever).

loc=loc+1; %Increment loc by one each time through the loopif loc > cols %If the loc is beyond the end of the vector

loc=-1; %Return -1 indicating no zero was found.break %exit the while loop if execution gets herebreak %exit the while loop if execution gets here.

endend

end

(c) 2009 Brian Funt, Simon Fraser University 240

Page 241: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

findzero using for and break

% findzero(vector) returns the location of the first zero entry% It returns -1 if there is no zerof ti l fi d 2( t )function loc = findzero2(vector)[rows cols] = size(vector);

if rows ~=1 %Error checking section. Input must be a vector.g pdisp('findzero only accepts vectors');loc = [];

elseloc= 1; %Initialize for the case of no zero foundloc=-1; %Initialize for the case of no zero foundfor i = 1:cols

if vector(i)==0;loc=i; %Found the zero, so save its locationbreak %Exit the for loop. Stop searching further.

endend

end

(c) 2009 Brian Funt, Simon Fraser University 241

end

Page 242: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try

U i hil l d ith t i M tl b’Using a while loop and without using Matlab’s sum, write a function sumtofirstzero(v) that returns the sum of all the numbers up until the first zero in vector v. If there is no zero, it ,returns the sum of all the numbers in v.

sumtofirstzero([ 3 4 2 0 5 7 9])ans =ans =8

(c) 2009 Brian Funt, Simon Fraser University 242

Page 243: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 21 Fall 2009

Lecture 21 was entirely lab time for everyone to catch up y y pon “To Try” examples and the current assignment.

(c) 2009 Brian Funt, Simon Fraser University 243

Page 244: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 22 Fall 2009

Last lecture was lab time

Previous lecturehil lwhile loops

break (in both for and while loops)

(c) 2009 Brian Funt, Simon Fraser University 244

Page 245: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Writing our own max

Initialize max value M to –infinityInitialize max value M to infinityEnter loop

If indexed value is > M then set M to indexedIf indexed value is > M then set M to indexed value

(c) 2009 Brian Funt, Simon Fraser University 245

Page 246: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

maxfor

%maxfor(a) computes the maximum of vector af ti f ( )function max = maxfor(a)if size(a,1)~=1

disp('maxfor requires vector input');else

max = -Inf; %Initialize max to lowest possiblefor i=1:length(a)

if max < a(i)max = a(i); % a(i) is bigger so it becomes the new maximummax = a(i); % a(i) is bigger, so it becomes the new maximum

endend

end

(c) 2009 Brian Funt, Simon Fraser University 246

Page 247: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

maximum of a matrix with nested for

%maxformatrix(a) computes the maximum of matrix mfunction max = maxfor(m)

[rows cols] = size(m); % Get the number of rows and columns in mmax = -Inf; %Initialize max to lowest possiblefor i=1:rows;

for j=1:cols;if max < m(i,j) % m(i,j) is bigger, so it's the new maximum

max = m(i,j);endend

endend

(c) 2009 Brian Funt, Simon Fraser University 247

Page 248: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Finding zero the Matlab way with findfind(logical_condition_on_matrix)

returns the 1 dimensional indices of the locations satisfying the conditionreturns the 1-dimensional indices of the locations satisfying the condition

%Can do findzero directly with findfind([1 2 0 3] == 0) %matrix exampled([ 0 3] 0)ans =

3

>> fi d([1 2 0 3 0 5] 0)

>> find([1 2; 0 3] == 0)ans =

2%Note that 0’s in the second>> find([1 2 0 3 0 5] == 0)

ans =3 5

%Note that 0 s in the second %location in column-major order>> [r c] = find([1 2; 0 3] == 0)r =

2

c =1

(c) 2009 Brian Funt, Simon Fraser University 248

1

Page 249: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

find for locating and assigningSet the minimum value of a matrix to -1

a=magic(3)a =

8 1 68 1 63 5 74 9 2

i ( ( ))

>> a(find(a==1))=-1

>> am=min(a(:))am =

1

a =

8 -1 63 5 7>> find(a==1)

ans =4

3 5 74 9 2

(c) 2009 Brian Funt, Simon Fraser University 249

Page 250: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

finding all primes and setting to zero

a=magic(3) >> p=find(isprime(a))

a =

8 1 63 5 7

p =

253 5 7

4 9 2

>> isprime(a)

589

p ( )

ans =

0 0 0

>> a(p)=0

a =0 0 01 1 10 0 1

8 1 60 0 04 9 0

(c) 2009 Brian Funt, Simon Fraser University 250

Page 251: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Dot product

a=[1 2 3];b=[4 5 6];

>> dot(a,b)ans =

A

ans 32

>> 1*4 + 2*5 + 3*6Bθ

ans =32

%dot product is commutative|A|cos(θ) = (A●B)/|B|

% p>> dot(b,a)ans =

32

(c) 2009 Brian Funt, Simon Fraser University 251

Page 252: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try(1) Use a for loop to find the minimum of a vector

(2) Write your own version of dot product called dotfor that uses a for loop.dotfor([2 3 1], [4 3 2])ans =

192*4+3*3+1*2ans =

19

(4) Use ‘find’ to change all negative numbers in a vector to zero

Given [3 -2 5 -1 -4 7 8] you’ll get [3 0 5 0 0 7 8]

(5) Use find to list all the negative numbers in a vector

Given [3 -2 5 -1 -4 7 8] you’ll get [-2 -1 -4]

(6) Use find to list the row-column location of the maximum value in a matrix

(c) 2009 Brian Funt, Simon Fraser University 252

Given [2 4 6; 7 2 9; 0 7 8] you’ll get [2 3]

Page 253: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 23 Fall 2009

Previous lecturemax using explicit looping

Matlab’s find function

(c) 2009 Brian Funt, Simon Fraser University 253

Page 254: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Debugger Example%Simple function to show how setting breakpoints with the debugger works%and how the values of variables are available to print and in the%workspace%workspacefunction r = debugger_example(a)b=2*a; %Set a breakpoint here so that can then use dbstepc=3*a;d=debug helper(b c);d debug_helper(b,c);e=10*d;r=e;

%f ti t b ll d f d b l t d t t%function to be called from debug_example to demonstrate%dbstep in%and%dbstep outf nction s deb g helper(a b)function s = debug_helper(a,b)x=a;y=b;z=a+b;s z;

(c) 2009 Brian Funt, Simon Fraser University 254

s=z;

Page 255: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Debugger and Breakpoints

>> debugger_example(1)5 b 2* %S t b k i t h th t th5 b=2*a; %Set a breakpoint here so that can then use dbstepK>> aa =

11K>> dbstep6 c=3*a;K>> bb

K>> dbstep8 e=10*d;K>> ddb =

2K>> dbstep7 d=debug_helper(b,c);K

d =5

K>> dbcontans =

K>> cc =

3

50

(c) 2009 Brian Funt, Simon Fraser University 255

Page 256: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

>> debugger_example(1)5 b=2*a; %Set a breakpoint here so that can then use dbstepK>> dbstep6 c=3*a;K>> dbstep7 d=debug_helper(b,c);K>> dbstep in6 x=a;6 x a;K>> bb =

3K>> aa =

2K>> dbstack> In debug_helper at 6In debugger example at 7gg _ p

K>> dbstep7 y=b;K>> dbstep out8 e=10*d;K>> dK>> dd =

5K>>

(c) 2009 Brian Funt, Simon Fraser University 256

Page 257: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To TryCopy my debugger_example and debug_helper functions into your directory

(1) Set a breakpoint at line 6 (c=3*a;) of debugger example(1) Set a breakpoint at line 6 (c=3 a;) of debugger_example(2) Run debugger_example(2)

(1) When it stops, check the values of the variables(2) Use dbstep and check any new values(3) Try dbstep another time or two(4) Try dbcont to continue execution of the function

(3) Remove the breakpoint from line 6(4) Set a breakpoint at line 7 (d=debug helper(b c);)(4) Set a breakpoint at line 7 (d debug_helper(b,c);)

(1) Try “dbstep in” to enter the function debug_helper(2) Check values of variables. Which ones are visible?(3) dbstep again and check more variables(4) db k(4) dbstack(5) dbstep out

(1) Where is it stopped now? Which variables are visible?(6) dbcont

(c) 2009 Brian Funt, Simon Fraser University 257

(6) dbcont

Page 258: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Dot product

a=[1 2 3];b=[4 5 6];

>> dot(a,b)ans =

A

ans 32

>> 1*4 + 2*5 + 3*6Bθ

ans =32

%dot product is commutative|A|cos(θ) = (A●B)/|B|

% p>> dot(b,a)ans =

32

(c) 2009 Brian Funt, Simon Fraser University 258

Page 259: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Matrix Multiplication

⎤⎡ bb

⎥⎦

⎤⎢⎣

⎡••••

=⎥⎥⎤

⎢⎢⎡

⎥⎦

⎤⎢⎣

⎡ 21112221

1211131211 colrowcolrow

babababa

bbbb

aaaaaa

⎦⎣ ••⎥⎥⎦⎢

⎢⎣⎦⎣ 2212

3231232221 colrowcolrow baba

bbaaa

(c) 2009 Brian Funt, Simon Fraser University 259

Page 260: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Matrix Multiplication

⎤⎡ bb

⎥⎦

⎤⎢⎣

⎡••••

=⎥⎥⎤

⎢⎢⎡

⎥⎦

⎤⎢⎣

⎡ 21112221

1211131211 colrowcolrow

babababa

bbbb

aaaaaa

⎦⎣ ••⎥⎥⎦⎢

⎢⎣⎦⎣ 2212

3231232221 colrowcolrow baba

bbaaa

(c) 2009 Brian Funt, Simon Fraser University 260

Page 261: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Matrix Multiplication

⎤⎡ bb

⎥⎦

⎤⎢⎣

⎡••••

=⎥⎥⎤

⎢⎢⎡

⎥⎦

⎤⎢⎣

⎡ 21112221

1211131211 colrowcolrow

babababa

bbbb

aaaaaa

⎦⎣ ••⎥⎥⎦⎢

⎢⎣⎦⎣ 2212

3231232221 colrowcolrow baba

bbaaa

(c) 2009 Brian Funt, Simon Fraser University 261

Page 262: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Matrix Multiplication

⎤⎡ bb

⎥⎦

⎤⎢⎣

⎡••••

=⎥⎥⎤

⎢⎢⎡

⎥⎦

⎤⎢⎣

⎡ 21112221

1211131211 colrowcolrow

babababa

bbbb

aaaaaa

⎦⎣ ••⎥⎥⎦⎢

⎢⎣⎦⎣ 2212

3231232221 colrowcolrow baba

bbaaa

(c) 2009 Brian Funt, Simon Fraser University 262

Page 263: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try

(4) By hand, multiply [ 1 2 3; 2 1 1] by [4 2; 3 1; 1 2]. i.e.,

1 2 32 1 12 1 1

by

4 24 23 11 2

Compare your result using Matlab’s * operator.

(c) 2009 Brian Funt, Simon Fraser University 263

Page 264: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Sorting

There’s nothing on sorting in the text

(c) 2009 Brian Funt, Simon Fraser University 264

Page 265: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Suggestions on how to sort a vector?

5 3 6 2 9 1

sort into descending order

9 6 5 3 2 1

sort into descending order

(c) 2009 Brian Funt, Simon Fraser University 265

Page 266: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 24 Fall 2009

Previous lecturedebuggingM tl b’ d bMatlab’s debugger

dbstepdbstep indbstep indbcontdbstack

Matrix multiplication

(c) 2009 Brian Funt, Simon Fraser University 266

Page 267: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Bubble Sort

3425

(c) 2009 Brian Funt, Simon Fraser University 267

Page 268: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Bubble Sort

3425

(c) 2009 Brian Funt, Simon Fraser University 268

Page 269: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Bubble Sort

3 4425

325

(c) 2009 Brian Funt, Simon Fraser University 269

Page 270: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Bubble Sort

3 4425

325

(c) 2009 Brian Funt, Simon Fraser University 270

Page 271: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Bubble Sort

3 4 4425

325

352

(c) 2009 Brian Funt, Simon Fraser University 271

Page 272: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Bubble Sort

3 4 4 4425

325

352

532

(c) 2009 Brian Funt, Simon Fraser University 272

Page 273: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Bubble Sort

3 4 4 4 5425

325

352

532

432

(c) 2009 Brian Funt, Simon Fraser University 273

Page 274: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Bubble Sort% sortbubble(v) sorts vector v into decreasing % order via bubble sort.f ti t d tb bbl ( )function sorted = sortbubble(v)swap=1; % Set swap flag to truewhile swap %Keep going until no swapping occurs

swap = 0; %Initialize to no swap

sortbubble([3 4 2 5])4 3 5 2

4 5 3 2p ; pfor i = 1:length(v)-1

if v(i+1) > v(i) %Since next one is bigger, swap themtemp=v(i); %Hang on to v(i) for momentv(i) = v(i+1);

4 5 3 2

5 4 3 2

v(i) = v(i+1);v(i+1)=temp; %Set v(i+1) to be v(i)swap=1; %Indicate that a swap has occurred

end

5 4 3 2

ans =enddisp(v);

endsorted=v;

ans =

5 4 3 2

(c) 2009 Brian Funt, Simon Fraser University 274

sorted=v;

Page 275: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

2D Plotting

plot(X,Y)plots values in Y versus values in X

xlabel(‘string’)L b l i ith ‘ t i ’Labels x-axis with ‘string’

ylabel(‘string’)L b l i ith ‘ t i ’Labels y-axis with ‘string’

title(‘string’)Labels entire plot with ‘string’Labels entire plot with string’

grid on; grid offOverlays a grid on the plotOverlays a grid on the plot

(c) 2009 Brian Funt, Simon Fraser University 275

Page 276: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

2D Plotting Example

Plot temperature in degrees versus time inPlot temperature in degrees versus time in hoursSuppose we have measurements madeSuppose we have measurements made every 12 hours

d=[15 8 16 9 16 10 13 6 14 5];t=0:12:(length(d)-1)*12t =

0 12 24 36 48 60 72 84 96 108

>> plot(t,d)

(c) 2009 Brian Funt, Simon Fraser University 276

Page 277: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

plot(t,d)

(c) 2009 Brian Funt, Simon Fraser University 277

Page 278: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Labeling the Plot

xlabel('hours')ylabel('degrees Celsius')ylabel( degrees Celsius )title('Vancouver Weather')

(c) 2009 Brian Funt, Simon Fraser University 278

Page 279: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Adding a Grid

>> grid on>>

(c) 2009 Brian Funt, Simon Fraser University 279

Page 280: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Saving the Plot as an Image

In the Figure windowIn the Figure windowFile -> Save As ->

select the save-as type to be JPEGselect the save as type to be JPEG

(c) 2009 Brian Funt, Simon Fraser University 280

Page 281: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try: Create a properly labeled graph of stock prices versus year, and then save a copy as an image. (5 minutes)p g

Stock priceVersus year

1999 20.12000 15.52001 16.22002 17 0Versus year 2002 17.02003 16.92004 18.12005 18.42006 21.22007 22.52008 10.22009 8 6

(c) 2009 Brian Funt, Simon Fraser University 281

2009 8.6

Page 282: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Multiple Plots on Same Figure>>holdCurrent plot held>> d2 =[12 10 12 9 13 11 12 9 11 7 ];[ ];>> plot(t,d2)>> holdCurrent plot released

(c) 2009 Brian Funt, Simon Fraser University 282

Page 283: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Plotting 2 at once in different colours

>> plot(t,d,t,d2)

%We get exactly the same result withds=[d ; d2]ds [d ; d2]ds =15 8 16 9 16 10 13 6 14 512 10 12 9 13 11 12 9 11 7plot(t, ds)plot(t, ds)

(c) 2009 Brian Funt, Simon Fraser University 283

Page 284: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Controlling the Line Colours

>> plot(t,d,'r',t,d2,'g')

(c) 2009 Brian Funt, Simon Fraser University 284

Page 285: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Choosing Line Style

>> plot(t, d, ':r',t, d2, '--g')>> plot(t, d, 'r:', t ,d2, '--g')>> plot(t, d, ':r', t, d2, 'g--') plot(t, d, :r , t, d2, g )

“Red” line looked redder in the original Matlab figureoriginal Matlab figure.

Page 143 of text hasPage 143 of text has table of line styles and colours

(c) 2009 Brian Funt, Simon Fraser University 285

Page 286: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Adding a Legend

>> plot(t, d, ':r', t, d2, 'g--')>> legend('d data' 'd2 data')>> legend( d data , d2 data )

(c) 2009 Brian Funt, Simon Fraser University 286

Page 287: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try: Create a properly labeled graph of 3 stocks versus year Use different line styles and colours for eachversus year. Use different line styles and colours for each stock. Include a legend.

Stock A Stock B Stock C

Stock priceVersus year

1997 10.01998 12.51999 13.62000 14 5

1997.5 91998.5 121999.5 152000 5 14

1997 50.01998 52.51999 53.62000 54 5Versus year 2000 14.5

2001 4.22002 5.62003 5.4

2000.5 142001.5 92002.5 52003.5 6

2000 54.52001 44.22002 45.62003 45.4

2004 5.92005 6.22006 7.82007 7 2

2004.5 52005.5 62006.5 82007 5 7

2004 45.92005 46.22006 47.82007 47 2

(c) 2009 Brian Funt, Simon Fraser University 287

2007 7.2 2007.5 7 2007 47.2

Page 288: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Log plotting

x=1:50;x=1:50;>> y=exp(x);>> plot(x,y)

>>figure>> semilogy(x,y)

Log scaleLog scaleon y axis

(c) 2009 Brian Funt, Simon Fraser University 288

Page 289: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Plot Types

plotplotlinear versus linear

semilogy and semilogxsemilogy and semilogxlinear versus logarithmic

logloglogloglogarithmic versus logarithmic

polar(angle in radians radius)polar(angle_in_radians, radius)plot in polar coordinates

polar isn’t generalized to handle multiple curvespolar isn t generalized to handle multiple curves

(c) 2009 Brian Funt, Simon Fraser University 289

Page 290: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Plots of sin and cos

angles=0:pi/100:pi;g p psinradii=sin(angles);cosradii=cos(angles);plot(angles,sinradii,'og')holdholdplot(angles,cosradii, '--b')

(c) 2009 Brian Funt, Simon Fraser University 290

Page 291: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Function plots using fplot

fplot(‘function expression’, range)p ( _ p , g )Automatically evaluates the expression over the range

fplot('sin(x)', [0 2*pi])l t i th 0 t 2* iplots sine over the range 0 to 2*pi

fplot('x^2', [0 2*pi])fplot('g^2', [0 2*pi])fplot('sin(s)^2', [0 2*pi])

(c) 2009 Brian Funt, Simon Fraser University 291

Page 292: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

plot in 3d

plot3(X,Y,Z)same idea as plot in 2D (name now is plot3)add third componentX Y Z are each vectorsX,Y,Z are each vectors

Each (xi , yi , zi) represents a point

>> x=0:pi/100:10*pi;>> l t3( ( ) i ( ))>> plot3(x, cos(x), sin(x))

(c) 2009 Brian Funt, Simon Fraser University 292

Page 293: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Extra parameters possible as before

Rotate the figure using the figure menu

plot3(x,cos(x),sin(x),'g',x,sin(x),cos(x),'b')

(c) 2009 Brian Funt, Simon Fraser University 293

Page 294: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Mini-Exercises(1) Try comet3

x=0:pi/100:10*pi; comet3(x, cos(x), sin(x))

Make sure the figure window is closed first

(2) Try rotating a plot3 plot( ) y g p p

(c) 2009 Brian Funt, Simon Fraser University 294

Page 295: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

3D Surface Plotting with Mesh. x from rows, y f l l ( )from columns, plot z(x,y)>> x=[0 1]x =

0 1>> y=[0 1]y =

0 10 1mesh(x,y,[3 4; 4 4])title('mesh(x,y,[3 4; 4 4])')xlabel('x')l b l(' ‘)ylabel('y‘)

(0, 0, 3)3 4

x0 10(1, 0, 4)

(0, 1, 4)(1, 1, 4)

3 44 4

0 1 y

(c) 2009 Brian Funt, Simon Fraser University 295

Page 296: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Changing one corner

mesh(x,y,[3 3.5; 4 4])( )>> xlabel('x')

>> ylabel('y')>> title('mesh(x,y,[3 3.5; 4 4])')

(0, 0, 3) xx0 10(1, 0, 3.5)

(0, 1, 4)(1, 1, 4)

3 3.54 4

y

0 1 y

(c) 2009 Brian Funt, Simon Fraser University 296

y

Page 297: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Changing another corner

mesh(x,y,[3 3.5; 3.2 4])( ( ) )title('mesh(x,y,[3 3.5; 3.2 4])')

xlabel('x')ylabel('y')

(0, 0, 3)3 3 5

xx0 10(1, 0, 3.5)

(0, 1, 3.2)(1, 1, 4)

3 3.53.2 4

0 1 y

(c) 2009 Brian Funt, Simon Fraser University 297

Page 298: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

An image as a surfacez=double(imread('VeniceBW.jpg'));[r c] = size(z);x=1:c;%Reverse direction to match imagey=r:-1:1; mesh(x,y,z)xlabel('Rows')xlabel( Rows )ylabel(‘Columns')zlabel('Intensity')title('VeniceBW')

(c) 2009 Brian Funt, Simon Fraser University 298

Page 299: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 25 Fall 2009

Previous lectureSortingPl ttiPlotting

(c) 2009 Brian Funt, Simon Fraser University 299

Page 300: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Integrating a Function Numerically

2/))(( 1

1

1 iii

n

i yyxxA +−= +

+∑1i=

y)( 1 ii xx −+

2/)( 1 ii yy ++

x

(c) 2009 Brian Funt, Simon Fraser University 300

Page 301: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Integrating with a for loop%integrate_sin1(start,finish) integrates sine(x) over the%interval [start, finish]function area = integrate sin1(start finish)function area = integrate_sin1(start, finish)intervals=200; % Specify how many rectangles to use in the approximationincrement = (finish-start)/intervals; %Width of each rectanglearea = 0; %Initialize integral to be zerox=start; %Initialize first x valuefor i = 1:intervals

area = area + ((sin(x)+sin(x+increment))/2)*increment;x=x+increment; %Move on to next x valuex x+increment; %Move on to next x value

end

integrate_sin1(0,pi/2)ans = >> integrate sin1(0 2*pi)ans

1.0000>> integrate_sin1(0,pi)ans =

2 0000

>> integrate_sin1(0,2 pi)ans =-9.7594e-015

(c) 2009 Brian Funt, Simon Fraser University 301

2.0000

Page 302: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Integrating with a for loop using Matlab’sindex generation%integrate_sin(start,finish) integrates sine(x) over the%i t l [ t t fi i h]%interval [start,finish]function area = integrate_sin(start, finish)intervals=200; % Specify how many rectangles to use in the approximationincrement = (finish-start)/intervals; %Width of each rectangle( ) ; garea = 0;for x = start:increment:(finish-increment) %x's for all left sides of rectangles

area = area + ((sin(x)+sin(x+increment))/2)*increment;endend

>> integrate_sin(0,pi)ans =

2.0000>> integrate_sin(0,pi/2)ans =

1 0000

(c) 2009 Brian Funt, Simon Fraser University 302

1.0000

Page 303: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Integrating sine with implicit looping %integrate_sin2(start,finish) integrates sine(x) over the%interval [start,finish]function area = integrate sin2(start, finish)g _ ( , )

intervals=200; % Specify how many rectangles to use in approximatingincrement = (finish-start)/intervals; %Width of each rectangle

y = sin(start:increment:finish); %Generate vector of sine values

y0 = y(1:end-1); %Set up two vectors of y’s shifted by one relative toy1 = y(2:end); %one anotherarea=sum((y1+y0)/2)*increment;

( / )integrate_sin2(0,pi/2)ans =

1.0000

(c) 2009 Brian Funt, Simon Fraser University 303

Page 304: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Function Handles Using @

“@f” indicates that a ‘handle’ to function f@f indicates that a handle to function f rather than the function itself

>> @sinans =

@sin

>> sin(pi/2)ans =

1

>> f=@sinf =

@sin

>> f(pi/2)ans =

1@sin 1

(c) 2009 Brian Funt, Simon Fraser University 304

Page 305: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Numerical Integration of Arbitrary f(x)%integrate(f, start, finish) integrates function f(x) over the%interval [start, finish]f ti i t t (f t t fi i h)function area = integrate(f, start, finish)

intervals=200; % Specify how many rectangles to use in approximatingincrement = (finish-start)/intervals; %Width of each rectangle( ) ; gif ~isa(f, 'function_handle') %Check that f is a function

disp('integrate requires a function handle as its first argument');else

y = f(start:increment:finish); %Generate vector of f(x) valuesy = f(start:increment:finish); %Generate vector of f(x) valuesy0 = y(1:end-1); %Set up two vectors of y’s shifted by one relative toy1 = y(2:end); %one anotherarea=sum((y1+y0)/2)*increment;

end

(c) 2009 Brian Funt, Simon Fraser University 305

Page 306: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Numerical Integration of Arbitrary f(x)“@f” indicates that a ‘handle’ to function f

rather than the function itself

>> integrate(@sin,0,pi/2)ans =ans

1.0000>> integrate(@cos,0,pi/2)ans =

1 00001.0000>> integrate(@exp,0,pi/2)ans =

3.8105>> integrate(@sqrt,0,pi/2)ans =

1.3123

(c) 2009 Brian Funt, Simon Fraser University 306

Page 307: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try

(1) Using function handles and a for loop, write a function sumf1(f,v) that computes

∑ ivf )( >> sumf1(@sqrt,[4 9])ans =i ans =

5>> sumf1(@sin, [pi pi/2])ans =

1.0000

(2) Write sumf2(f,v) using implicit looping. You may assume that f allows(2) Write sumf2(f,v) using implicit looping. You may assume that f allows vector inputs the way most Matlab functions do (e.g., sqrt).

(c) 2009 Brian Funt, Simon Fraser University 307

Page 308: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 26 was midterm review

(c) 2009 Brian Funt, Simon Fraser University 308

Page 309: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 27 Review To Try

(1) Sometime ago, you wrote mysin(x) based on evaluating a fixed number of >> s=mysint(pi/3)

terms of the series

....!7!5!3

)sin(753

+−+−=xxxxx

s =

0.8660

Write another version of mysin that evaluates the series until the term to add is less than 0 000001 I suggest using a while loop

>> [s terms]=mysint(pi)0.000001. I suggest using a while loop. Depending on how you write it you may or may not find a break useful.

s =

-7.7279e-007(3) Modify your function to return both the value of sine and the number of terms used. terms =

9

(c) 2009 Brian Funt, Simon Fraser University 309

Page 310: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Midterm Exam Day

(c) 2009 Brian Funt, Simon Fraser University 310

Page 311: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 28 Fall 2009

Previous lecture was the midterm

T d ill fi t t idt d diToday will first return midterm and discuss answers

(c) 2009 Brian Funt, Simon Fraser University 311

Page 312: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Volumetric Data

From Mayo Clinichtt // li i /h lth/ t /FL00065

(c) 2009 Brian Funt, Simon Fraser University 312

http://www.mayoclinic.com/health/ct-scan/FL00065

Page 313: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

3D is built up from 2D slices

From Mayo Clinichtt // li i /h lth/ t /FL00065http://www.mayoclinic.com/health/ct-scan/FL00065

(c) 2009 Brian Funt, Simon Fraser University 313

Page 314: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Multidimensional Arrays

a=ones(2,2,2) >> a(:,:,1)=magic(2)

a(:, :, 1) =

1 1

a(:, :, 1) =

1 31 1

a(: : 2)

1 34 2

( 2)a(:, :, 2) =

1 11 1

a(:, :, 2) =

1 11 1

3 dimensions

(c) 2009 Brian Funt, Simon Fraser University 314

3 d e s o s

Page 315: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

4 Dimensionsb(2 1 1 2) 4

>> find(b>0)ans =

10>> b=zeros(2,2,2,2)b(:,:,1,1) =

>> b(2,1,1,2)=4

b(:,:,1,1) =0 0

10>> b(:)ans =

00 00 0

b(: : 2 1)

0 00 0

b(:,:,2,1) =0 0

0000b(:,:,2,1) =

0 00 0

0 00 0

b(:,:,1,2) =

0000

b(:,:,1,2) =0 00 0

( )0 04 0

b(: : 2 2) =

0400

b(:,:,2,2) =0 00 0

b(:,:,2,2) =

0 00 0

00000

(c) 2009 Brian Funt, Simon Fraser University 315

0

Page 316: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Colour Images as 3 Dimensional Data

A colour image is three grayscale (black and white) images displayed in red, green, blue,in red, green, blue, respectively.

(c) 2009 Brian Funt, Simon Fraser University 316

Page 317: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Colour Image c=imread('wilmer5098_crop.jpg');>> imshow(c)

From the Figure menu tryTools -> Data CursorTools -> Data Cursor

>> size(c)ans =

973 947 3973 947 3

>> c(100, 201,2)ans =

6363>> c(100, 201,:)ans(:,:,1) =

96ans(:,:,2) =

63ans(:,:,3) =

9

(c) 2009 Brian Funt, Simon Fraser University 317

9

Page 318: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Red, Green and Blue Images

(c) 2009 Brian Funt, Simon Fraser University 318

Page 319: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Why You Might Want 4D Arrays

MoviesMoviesR,G,B, Time

CT-slices over timeCT-slices over timeThis would be 3D with X,Y,Time

Volumetric CT over time is 4DVolumetric CT over time is 4DX,Y,Z,TimeFor example a 3D scans of a beating heartFor example, a 3D scans of a beating heart

(c) 2009 Brian Funt, Simon Fraser University 319

Page 320: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try

(1) Display the colour image and use data cursor from the Figure window(2) Display each of the R, G, B colour images as independent grayscale

imagesg(3) Convert the colour image to a greyscale image based on the average of

the R, G, and B at each pixel. Compare it to the separate R,G,B images of (2).

(c) 2009 Brian Funt, Simon Fraser University 320

Page 321: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 29 Fall 2009

Previous lecture

R t d idtReturned midterm

Multi-dimensional arraysMulti dimensional arrays

(c) 2009 Brian Funt, Simon Fraser University 321

Page 322: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Selection Sort

3 3 3402

4

2

4 4

0 2 3 40 20

320

320

(c) 2009 Brian Funt, Simon Fraser University 322

Page 323: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

remove(V,i) %remove(V,i) returns a vector V with its ith element removedfunction less = remove(V,i)

if ~isvector(V)disp('remove requires a vector as input');

elseless = [V(1:i-1) V(i+1:end)]; %Works for i==1 because 1:0 returns

%the empty matrix.end

remove(1:4,2)ans=ans

1 3 4>> remove(1:4,1)ans =

2 3 4

(c) 2009 Brian Funt, Simon Fraser University 323

2 3 4

Page 324: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Iterative Selection Sort

%sortselection2(V) sorts row vector V into decreasing order using%selection sort algorithm Implementation is iterative%selection sort algorithm. Implementation is iterative.function S = sortselection2(V)

if ~isvector(V)disp('remove requires a vector as input');

elseelems = length(V);S = []; %Initialize sorted vector as empty vectorS []; %Initialize sorted vector as empty vectorelemsleft = elems; %Initialize number of elements remainingwhile elemsleft > 0 %When no elements are left, exit loop[m loc] = min(V); %Find the min value and its location.S [ S] %P t l t f t f i ti tS = [m S]; %Put new element a front of existing vectorV=remove(V,loc); %Get rid of the current minimum from Velemsleft = elemsleft - 1; %One less element left to do nowend

(c) 2009 Brian Funt, Simon Fraser University 324

end

Page 325: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Will do Recursive Selection Sort

As Practice: Summing recursivelyAs Practice: Summing recursively1 + 2 + 3 + 4 + 5 + 6+ 7 + 8

1 + 2 + 3 + 4 5 + 6+ 7 + 8

1 2 3 4 5 6 7 8

+

1 + 2 3 + 4+

(c) 2009 Brian Funt, Simon Fraser University 325

Page 326: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Summing Recursively

% sumr(A) sums the elements of vector A. Algorithm is recursive.function s=sumr(A)len=length(A); %Find number of elements to sumg ( );half=ceil(len/2); %What’s half the number of elementsif len==0; %If there are no elements, sum is zero

s=0;elseif len==1; %If there is only 1 element sum is itelseif len==1; %If there is only 1 element, sum is it

s=A(1);else %Total is addition of sums of left and right halves

s=sumr(A(1:half))+sumr(A(half+1:end));end

(c) 2009 Brian Funt, Simon Fraser University 326

Page 327: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Tree of the Summation

+36

+

+ +

+

153 7 11

1026

+ + + +

1 2 3 654 7 8

15

(c) 2009 Brian Funt, Simon Fraser University 327

Page 328: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Recursive Selection Sort

%sortselection(V) sorts row vector V into decreasing order using%selection sort algorithm Implementation is recursive%selection sort algorithm. Implementation is recursive.function S = sortselection(V)

if ~isvector(V)( )disp('remove requires a row vector as input');

elseif length(V) ==1S = V; %When there's only one element we're doneS = V; %When there s only one element, we re done

else[m loc] = min(V);S = [sortselection(remove(V,loc)) m];%Sort the other elements and

%place m after them. end

(c) 2009 Brian Funt, Simon Fraser University 328

Page 329: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try

W it f ti ( ) th t t th 1 2 i lWrite a function rsum(n) that computes the sum 1+2+…+n recursively.

Write a function rmult(a,b) that for scalars a and b computes a*b recursively.

(c) 2009 Brian Funt, Simon Fraser University 329

Page 330: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 30 Fall 2009

Previous lecture

S l ti t lSelection sort example

RecursionRecursion

(c) 2009 Brian Funt, Simon Fraser University 330

Page 331: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Cell ArraysChapter 10

Starting at Section 10 4 (1st and 2nd ed )Starting at Section 10.4 (1 and 2 ed.)Until now arrays had to contain uniform elementselements

Usually all numbersWe also briefly touched on character arraysWe also briefly touched on character arrays

Each entry was a character

Would like an array of mixed data typesWould like an array of mixed data typesJeremy B+ 79Judith A 91Judith A 91

(c) 2009 Brian Funt, Simon Fraser University 331

Page 332: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Cell Arrays (continued)s = {'john' 'B+' [ 75 79 80]; 'judith' 'A' [90 91 92]}s =

{ …} is the cell array constructor

'john' 'B+' [1x3 double]'judith' 'A' [1x3 double]

>> s(2 3)

Saves space to just print size

>> s(2,3)ans =

[1x3 double]Only data description is returned

>> s{2,3}ans =

90 91 92

Curly brackets retrieve contents

>> s{2,3}(2)ans =

91

Combining both notations{2,3} retrieves the 3-elementvector [90 91 92]

(c) 2009 Brian Funt, Simon Fraser University 332

[ ]

Page 333: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Displaying entire contents of cell array

>> celldisp(s)>> celldisp(s)s{1,1} =johns{2,1} =j dithjudiths{1,2} =B+s{2,2} ={ , }As{1,3} =

75 79 80s{2 3} =s{2,3} =

90 91 92

(c) 2009 Brian Funt, Simon Fraser University 333

Page 334: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Nested Cell ArraysCell arrays can have anything in their cells.

Can they have cell arrays as cell contents?

>> a = {1 [2 3] 'four'}a =

>> c{2}ans =

Can they have cell arrays as cell contents?

[1] [1x2 double] 'four'

>> b = {[5 6] 7 'eight'}b =

ans [1x2 double] [7] 'eight'

>> c{2}{1}b

[1x2 double] [7] 'eight'

>> c={a;b}

ans =5 6

>> c{2}{1}(2)c =

{1x3 cell}{1x3 cell}

{ }{ }( )ans =

6

(c) 2009 Brian Funt, Simon Fraser University 334

Page 335: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Weights of pretty rocks at beachSuppose 4 people go out and collect pretty rocks at the beach.

>> weights = {[3 4 2] ; [9 4 5 6 4]; [4 6]; [8 4 3 7]}

We then weigh each rock. Varying numbers of rocks per person.

weights = [1x3 double][1x5 double][1x5 double][1x2 double][1x4 double]

( i ht {2})>> sum(weights{2})ans =

28

(c) 2009 Brian Funt, Simon Fraser University 335

Page 336: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try

Write a function avggrade(s) that returns a column vector of the f th i d f h t d t h th d t i t

s = {'john' 'B+' [ 75 79 80]; 'judith' 'A' [91 92]; ' Tom ' ' B ' [76 82 83 79]}

average of the numeric grades for each student when the data is enter in the same format as the following

s = { john B+ [ 75 79 80]; judith A [91 92]; Tom B [76 82 83 79]}

>>avggrade(s)ans =7891.580

(c) 2009 Brian Funt, Simon Fraser University 336

Page 337: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Structure arraysLike cell arrays, but indexing is by field names

>> item.fieldA = 'hi‘item =

fieldA: 'hi'

>> item.fieldB = 'there‘item =

fieldA: 'hi'fieldB: 'there'

>> item.fieldAans =ans

hi

(c) 2009 Brian Funt, Simon Fraser University 337

Page 338: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Using Structure Arrays for Grade Data>> grades.name='john‘grades =

name: 'john'%Second entry of structuregrades(2).name='judith'

>> grades.letter = 'B+‘grades =

name: 'john'

g ( ) jgrades = 1x2 struct array with fields:

nameletterj

letter: 'B+'

>> grades.assignments = [79 81 78]grades =

letterassignments

>> grades(2).namegrades =

name: 'john'letter: 'B+'

assignments: [79 81 78]

ans =judith

>> grades(1) name

>> grades.letterans =B+

>> grades(1).nameans =john

(c) 2009 Brian Funt, Simon Fraser University 338

B+

Page 339: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

%Fill in the other fields for J dith>> grades(:).assignments

%Fill in the other fields for Judith>> grades(2).letter = 'A'

grades =

ans =

79 81 78g

1x2 struct array with fields:nameletter

ans =letterassignments

>> grades(2).assignments = [90 91 95];

90 91 95

>> mean(grades(:).assignments)>> mean(grades(2).assignments)

ans =

??? Error using ==> sumDimension argument must be a positive integer scalar in the range 1 to 2^31.

92 Error in ==> mean at 31y = sum(x,dim)/size(x,dim);

(c) 2009 Brian Funt, Simon Fraser University 339

Page 340: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Cell and Structure Arrays Summary

Useful when data is non-uniform in type orUseful when data is non uniform in type or numberStructure arrays allow indexing by namesStructure arrays allow indexing by names rather than numbers

Structures are very common in other languagesStructures are very common in other languagesOften heavily used (but not by me)They’re fine, but don’t faciliate the speed of Matlab’s array operations

(c) 2009 Brian Funt, Simon Fraser University 340

Page 341: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Character Strings

‘Hi There’Hi ThereIt’s called a stringIt’s an array of elements of type charIt s an array of elements of type charCharacters are represented as numbers

In Matlab and all other languagesg gLike 1 for a, 2 for b, etc. but those aren’t the exact codes

num2str(n)converts the number n to its string representation

(c) 2009 Brian Funt, Simon Fraser University 341

Page 342: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

String examplesa = 'hi there‘a = hi therea =hi there

>> v = 1:4v =

1 2 3 4

>> num2str(v)ans =1 2 3 4

>> [a v]ans =hi there

>> [a num2str(v)]ans =hi there1 2 3 4

(c) 2009 Brian Funt, Simon Fraser University 342

hi there1 2 3 4

Page 343: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Trick for printing apostrophe marks

Use two apostrophes in a row to get oneUse two apostrophes in a row to get one

>> disp('Brian''s dream');>> disp( Brian s dream );Brian's dream

(c) 2009 Brian Funt, Simon Fraser University 343

Page 344: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Outputting values

dispdispfor simple “printing”

fprintffprintffor formatted printinguse when you want to controluse when you want to control

overall spacingsignificant digits of numbersformat of numbers

(c) 2009 Brian Funt, Simon Fraser University 344

Page 345: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Formatted Printing using fprintf

Want complete control over how everything isWant complete control over how everything is printed

Should numbers be printed as integers or realsShould numbers be printed as integers or realsControlling the number of significant digitsControlling spacing between itemsg p gControlling line spacing

fprintf(formattingstring1, variable1,fprintf(formattingstring1, variable1, formattingstring2, variable2, …)fprintf is common to Fortran C Java etcfprintf is common to Fortran, C, Java, etc.

(c) 2009 Brian Funt, Simon Fraser University 345

Page 346: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

fprintf formattingstring

Use % sign to indicate a formatting itemUse % sign to indicate a formatting item%f means print fixed point

With a decimal point, but no exponent

students =24

>> fprintf('There are %f students in CMPT 102' students);>> fprintf( There are %f students in CMPT 102 , students);There are 24.000000 students in CMPT 102>>

(c) 2009 Brian Funt, Simon Fraser University 346

Page 347: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

%f %e and %g

%f for fixed point without exponent%f for fixed point without exponent%e decimal with exponent%g prints whatever is shortest including%g prints whatever is shortest, including without a decimal point

>> fprintf('There are %e students in CMPT 102', students);There are 2.400000e+001 students in CMPT 102>>

>> fprintf('There are %g students in CMPT 102', students);There are 24 students in CMPT 102>>

(c) 2009 Brian Funt, Simon Fraser University 347

There are 24 students in CMPT 102>>

Page 348: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Printing on the next line

fprintf doesn’t move to the next linefprintf doesn t move to the next line unless specifically told to do so

To move to the next line use \n The commandTo move to the next line use \nLike %, \ is a special formatting character

f i tf('Th % t d t i CMPT 102' t d t )

The command prompt is on the

same line

>> fprintf('There are %e students in CMPT 102', students);There are 2.400000e+001 students in CMPT 102>>

>> fprintf('There are %e students in CMPT 102 \n', students);There are 2.400000e+001 students in CMPT 102

(c) 2009 Brian Funt, Simon Fraser University 348

Page 349: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Backslash “\” Uses

Note that “\” is not the same “/”Note that \ is not the same /\n linefeed

linefeed means go to next linelinefeed means go to next line\r “carriage return” from old typewriters

same as linefeedsame as linefeed\t tab\b b k\b backspace

likely don’t need with modern character font sets

(c) 2009 Brian Funt, Simon Fraser University 349

Page 350: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Formatted Printing: fprintf

Use % sign to indicate a formatting itemUse % sign to indicate a formatting item%f means print fixed point

With a decimal point, but no exponent

students =24

>> fprintf('There are %f students in CMPT 102' students);>> fprintf( There are %f students in CMPT 102 , students);There are 24.000000 students in CMPT 102>>

(c) 2009 Brian Funt, Simon Fraser University 350

Page 351: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Width and Precision Controls

%f format is generalized to% f%w.pf

Forces the number to be w spaces wideFixed width is useful for tablesFixed width is useful for tables

Forces there to be p places after the decimalThe “f” is required, but could be “e” or “g” as well

>> fprintf('There are %15.2f students in CMPT 102 \n', students);There are 24.00 students in CMPT 102 >>

>> fprintf('There are %15.2e students in CMPT 102 \n', students);There are 2.40e+001 students in CMPT 102

(c) 2009 Brian Funt, Simon Fraser University 351

Page 352: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Multiple Format Strings>> x=1; y=2; z=3;>> fprintf('one: %5.1f \ntwo: %10.2e \nthree: %g \n', x, y, z);one: 1.0 two: 2.00e+000 three: 3 >>

>> fprintf('one: %5.1f \n two: %10.2e \nthree: %g \n', x, y, z);one: 1.0 two: 2.00e+000 three: 3three: 3

>> fprintf('one: %5.1f \n two: %10.2e \nthree: %g \n', x, y, z , z, y, x);one: 1.0 two: 2 00e+000two: 2.00e+000 three: 3 one: 3.0 two: 2.00e+000 th 1

(c) 2009 Brian Funt, Simon Fraser University 352

three: 1

Page 353: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 31 Fall 2009

Previous lecture

C llCell arrays

Record structures (struct arrays)Record structures (struct arrays)

Formatted printing with fprintf

(c) 2009 Brian Funt, Simon Fraser University 353

Page 354: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Symbolic Mathematics (see chapter in text)

Completely different form of program

Computing with symbolic expressions, not with numbers

(c) 2009 Brian Funt, Simon Fraser University 354

Page 355: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Maple and Matlab’s Symbolic Toolkit

Matlab’s toolkit is from Maplesoft IncMatlab s toolkit is from Maplesoft Inc.University of Waterloo professors started itNow a company in WaterlooNow a company in WaterlooDr. Michael Monagan, SFU Math and others in the SFU Computer Algebra Group have had a lot to gdo with Maple development as well.

(c) 2009 Brian Funt, Simon Fraser University 355

Page 356: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Symbolic Manipulation may save you from looking stupid.

96)3(2

2

2

+++

=xx

xyFor example, write a function to evaluate

)96(2 2

That’s not hard to do, but consider expanding the numerator then

296

)96(22

2

=++++

=xxxxy

We hardly need to write a function that simply returns 2 all the time.

(c) 2009 Brian Funt, Simon Fraser University 356

Page 357: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Can manipulate algebraic expressions symbolically by hand and by Matlab

Solve expressions symbolicallySimplify expressions symbolicallySimplify expressions symbolicallyIntegrate expressions symbolicallyDiff ti t i b li llDifferentiate expressions symbolically….

(c) 2009 Brian Funt, Simon Fraser University 357

Page 358: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Begin: Need to Create Symbolic Variables%To create a symbolic variable use

>> syms x>> x

%When we enter

x = 5

>> x

x =

%We create a numerical variablex

%Note that the value of ‘x’ is ‘x’

%To create multiple symbolic variables >> syms a b c>> b

b =

b

(c) 2009 Brian Funt, Simon Fraser University 358

b

Page 359: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Symbolic Expressions

)3(2 2+=

xyTo enter the equation from earlier962 ++ xx

yTo enter the equation from earlier

syms x%We don’t have to say “syms y” if the expression is all of symbols>> y = 2*(x+3)^2/(x^2+6*x+9)

y =

2Never look foolish again!

(c) 2009 Brian Funt, Simon Fraser University 359

Page 360: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Slight variation

)3( 2+=

xqyCh 2 t 962 ++ xxyChange 2 to q

>> syms x q>> y = q*(x+3)^2/(x^2+6*x+9)

y =y

q

(c) 2009 Brian Funt, Simon Fraser University 360

Page 361: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Avoiding automatic simplification

>> y = sym('q*(x+3)^2/(x^2+6*x+9)') Note it’s sym not syms here

y =

q*(x+3)^2/(x^2+6*x+9)q ( ) ( )

>> y y =q*(x+3)^2/(x^2+6*x+9)q*(x+3)^2/(x^2+6*x+9)

>> simplify(y)ans =q

(c) 2009 Brian Funt, Simon Fraser University 361

Page 362: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Manipulating symbolic expressions>> yq*(x+3)^2/(x^2+6*x+9)

%recreate the original%separate numerator and denominator>> [n d] = numden(y)

>> n/dans =q*(x+3)^2/(x^2+6*x+9)

n =q*(x+3)^2

d =

>> simplify(n/d)ans =qd

x^2+6*x+9

>> n*d>> simplify((n/d)^2)ans =q^2ans =

q*(x+3)^2*(x^2+6*x+9)q 2

(c) 2009 Brian Funt, Simon Fraser University 362

Page 363: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Symbolic Equations rather than Expressions

newt = sym('f = 2*m*a/2')newt sym( f 2 m a/2 )

newt =f = 2*m*a/2

>> simplify(newt)

ans =

f = m*a

(c) 2009 Brian Funt, Simon Fraser University 363

Page 364: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try

a) Enter the expression 1257515 23 −+− xxxa) Enter the expression

into Matlab

25102 +− xx

(1) print its numerator(2) print its denominator(3) multiply the numerator by 4( ) p y y(4) compose a new expression with the new numerator and the original denominator(5) Simplify the new expression

2b) Enter the formula adv 22 =

(c) 2009 Brian Funt, Simon Fraser University 364

Page 365: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Solving Equations

010 =+zTo solve an equation like

>> syms z>> solve(z+10)

%Also can have as a variable>> e = z + 10( )

ans =

10

e z 10e =z+10

>> l ( )-10 >> solve(e)ans =-10

(c) 2009 Brian Funt, Simon Fraser University 365

Page 366: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Solving full equations with =

>> solve('z+10=0')

ans =

-10

>> solve('z^2-90=10')

ans =10

>> solve('z+10=5')

10-10

ans =

-5

(c) 2009 Brian Funt, Simon Fraser University 366

Page 367: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try

36122 +− xx

Assign the above expression to a variable

Si lif th iSimplify the expression

Solve for the expression equal zero

(c) 2009 Brian Funt, Simon Fraser University 367

Page 368: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 32 Fall 2009

Previous lecture

S b li M th C tiSymbolic Math Computing

symssyms

sym

(c) 2009 Brian Funt, Simon Fraser University 368

Page 369: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Begin: Need to Create Symbolic Variables%To create a symbolic variable use

>> syms x>> x

%When we enter

x = 5

>> x

x =

%We create a numerical variablex

%Note that the value of ‘x’ is ‘x’

%To create multiple symbolic variables >> syms a b c>> b

b =

b

(c) 2009 Brian Funt, Simon Fraser University 369

b

Page 370: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Symbolic Expressions

)3(2 2+=

xyTo enter the equation from earlier962 ++ xx

yTo enter the equation from earlier

syms x%We don’t have to say “syms y” if the expression is all of symbols>> y = 2*(x+3)^2/(x^2+6*x+9)simplify(y)p y(y)ans =

2

(c) 2009 Brian Funt, Simon Fraser University 370

Page 371: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Symbolic Equations rather than Expressions

newt = sym('f = 2*m*a/2')newt sym( f 2 m a/2 )

newt =f = 2*m*a/2

>> simplify(newt)

ans =

f = m*a

(c) 2009 Brian Funt, Simon Fraser University 371

Page 372: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Working out the Quadratic Formula

cbxax 02 =++

aacbb

242 −±−

>> solve('a*x^2+b*x+c')

ans =

1/2/a*(-b+(b^2-4*a*c)^(1/2))

It’s not as pretty, but it’s correct.

1/2/a (-b+(b 2-4 a c) (1/2))1/2/a*(-b-(b^2-4*a*c)^(1/2))

(c) 2009 Brian Funt, Simon Fraser University 372

Page 373: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Which variable is solved for?We kind of expect to solve for x in

l (' * ^2+b* + ')

>> solve('a*x^2+b*x+c','x')

solve('a*x^2+b*x+c')

but that isn’t the only option. Perhaps we wanted to solve for a, b or c.

ans =1/2/a*(-b+(b^2-4*a*c)^(1/2))

1/2/a*(-b-(b^2-4*a*c)^(1/2)),

>> solve('a*x^2+b*x+c','a')

ans =(b* + )/ ^2-(b*x+c)/x^2

>> solve('a*x^2+b*x+c','b')ans =

-(a*x^2+c)/x

(c) 2009 Brian Funt, Simon Fraser University 373

Page 374: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

If Symbols Declared, Don’t Need Quotes

bsyms a b c x

>> solve(a*x^2+b*x+c,b)

ans =

-(a*x^2+c)/x

(c) 2009 Brian Funt, Simon Fraser University 374

Page 375: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Converting expressions to numberse=sym('5*x^2+6*x+3=10')

e =e =5*x^2+6*x+3=10

>> es = solve(e)

es =-3/5+2/5*11^(1/2)-3/5-2/5*11^(1/2)-3/5-2/5 11 (1/2)%es is still a symbolic expression

%Use double to convert it>> double(es)ans =

0.7266-1 9266

(c) 2009 Brian Funt, Simon Fraser University 375

1.9266

Page 376: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Solving Simultaneous EquationsSamantha has 30 coins, quarters and dimes, which total $5.70. How many of each does she have?

70.51.25.30=+

=+dd

dqLet q and d be the number of quarters and dimes

70.51.25. + dd

We have 2 equations in 2 unknowns.

(c) 2009 Brian Funt, Simon Fraser University 376

Page 377: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Solving 2 simultaneous equations

>> [d q] = solve(e1,e2)d =705125

30=+

=+dd

dqd =12.

q =

70.51.25. =+ dd

>> e1 = sym('q+d=30')

18.

%Variables are returned in alphabetical order>> [q d] = solve(e1,e2)

e1 =q+d=30

[q d] solve(e1,e2) q =12.

d

>> e2 = sym('.25*q+.1*d=5.70')

e2 =25*q+ 1*d=5 70 d =

18.

.25 q+.1 d 5.70

(c) 2009 Brian Funt, Simon Fraser University 377

Page 378: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try (short)

Find the intersection of the lines

y = 3x + 4y= 2x+1y= -2x+1

(c) 2009 Brian Funt, Simon Fraser University 378

Page 379: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Equations Can be NON-LinearThe square of the number of coins Samantha has is 468. They are quarters and dimes, which total $5.70. How many of each d h h ?does she have?

Previously she had 12 dimes and 18 quarters. I made up this problem then by using 12^2+18^2 = 468p y g

46822 =+dq70.51.25.

468=+

=+dq

dq

(c) 2009 Brian Funt, Simon Fraser University 379

Page 380: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Equations Can be NON-Linear>> [q d] = solve(e1,e2)q =3.7241379310344827586206896551724

1270.51.25.

46822

=+=+dq

dq

>> e1 = sym('q^2+d^2=468')

12.d =

21.31034482758620689655172413793118.>> e1 = sym( q 2+d 2=468 )

e1 = q^2+d^2=468

%Long numbers are Maple format%convert to Matlab format>> double(d)ans =

>> e2 = sym('.25*q+.1*d=5.70')

e2 =

ans =21.310318.0000

e2 .25*q+.1*d=5.70 >> double(q)

ans =3.724112 0000

(c) 2009 Brian Funt, Simon Fraser University 380

12.0000

Page 381: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Intersection of a line and a circle

222 yxrbmxy

+=

+=

Circle of radius r centered at the originy Circle of radius r centered at the origin

>> circle = sym('x^2+y^2=r^2') >> [x y]= solve(circle line)y ( y )

circle =x^2+y^2=r^2

>> [x y] solve(circle, line)

x =-3/10+1/10*(-1+10*r^2)^(1/2)3/10 1/10*( 1 10* ^2)^(1/2)

>> line = sym('y=3*x+1')

-3/10-1/10*(-1+10*r^2)^(1/2)

y =line =y=3*x+1

y 1/10+3/10*(-1+10*r^2)^(1/2)

1/10-3/10*(-1+10*r^2)^(1/2)

(c) 2009 Brian Funt, Simon Fraser University 381

Page 382: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

22912yx

xy+=

+= Numerical Case: At what (x,y) do this line of slope 2 and circle of radius 3 intersect?9 yx +=

>> line = sym('y=m*x+b')line =

[b m r x y] =solve(circle, radius, slope, intercept, line)line =

y=m*x+b

>> circle = sym('x^2+y^2=r^2')

line)x =-2/5+2/5*11^(1/2)

-2/5-2/5*11^(1/2)circle =x^2+y^2=r^2>> radius = sym('r=3')radius =

y =1/5+4/5*11^(1/2)

1/5-4/5*11^(1/2)>> double(x)radius

r=3>> slope = sym('m=2')slope =

2

doub e( )ans =

0.9266-1.7266

>> double(y)m=2>> intercept = sym('b=1')intercept =b=1

>> double(y)ans =

2.8533-2.4533

(c) 2009 Brian Funt, Simon Fraser University 382

Page 383: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

subs> syms x y m b r>> circle = sym('x^2+y^2=r^2')circle =x^2+y^2=r^2>> line = sym('y=m*x+b')line =y=m*x+b

This is just the general case from earliery=m x+b>> [x y]= solve(circle, line)x =1/2/(1+m^2)*(-2*m*b+2*(r^2- 222 yxr

bmxy+=

+=

b^2+m^2*r^2)^(1/2))1/2/(1+m^2)*(-2*m*b-2*(r^2-b^2+m^2*r^2)^(1/2))y =

yxr +=

y 1/2*m/(1+m^2)*(-2*m*b+2*(r^2-b^2+m^2*r^2)^(1/2))+b1/2*m/(1+m^2)*(-2*m*b-2*(r^2-b^2+ ^2* ^2)^(1/2))+b

(c) 2009 Brian Funt, Simon Fraser University 383

b^2+m^2*r^2)^(1/2))+b

Page 384: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

subs for substituting values for variables> syms x y m b r>> circle = sym('x^2+y^2=r^2')circle =

>> subs(x,{m,b,r},{2,1,3})

x^2+y^2=r^2>> line = sym('y=m*x+b')line =y=m*x+b

ans =

0.92661 7266y=m x+b

>> [x y]= solve(circle, line)x =1/2/(1+m^2)*(-2*m*b+2*(r^2-

-1.7266

>> subs(y,{m,b,r},{2,1,3})

b^2+m^2*r^2)^(1/2))1/2/(1+m^2)*(-2*m*b-2*(r^2-b^2+m^2*r^2)^(1/2))y =

ans =

2.85332 4533y

1/2*m/(1+m^2)*(-2*m*b+2*(r^2-b^2+m^2*r^2)^(1/2))+b1/2*m/(1+m^2)*(-2*m*b-2*(r^2-b^2+ ^2* ^2)^(1/2))+b

-2.4533

(c) 2009 Brian Funt, Simon Fraser University 384

b^2+m^2*r^2)^(1/2))+b

Page 385: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

ezplot

ine = sym('y=3*x+1')y ( y )

line =

y=3*x+1y=3*x+1

>> ezplot(line)p ( )>>

(c) 2009 Brian Funt, Simon Fraser University 385

Page 386: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

ezplot of sine

s =

sin(t)

>> ezplot(s)

Default range is -2*pi to +2*pi

(c) 2009 Brian Funt, Simon Fraser University 386

Page 387: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

5 cycles of sine

s =

sin(t)sin(t)

>> ezplot(s, [0 10*pi])

(c) 2009 Brian Funt, Simon Fraser University 387

Page 388: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Golf Ball Range

0 )cos(tvd = θ v0 Initial Velocity

20

0

21)sin(

)cos(

gttvd

tvd

y

x

−= θ

θ v0 Initial Velocityg gravityt timetheta initial angle from horizontal

How far will the ball go?

(c) 2009 Brian Funt, Simon Fraser University 388

Page 389: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

L t’ l th ti bitLet’s explore the equations a bit before solving the general problemg g p

(c) 2009 Brian Funt, Simon Fraser University 389

Page 390: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

2

0

1)sin(

)cos(

gttvd

tvdx

−=

=

θ

θ

syms v0 t theta g

0 2)sin( gttvd y = θ

>> dx=v0*t*cos(theta)dx =v0*t*cos(theta)

Declare the symbols

Express the equations in Matlab form

>> dy=v0*t*sin(theta) -0.5*g*t^2dy =v0*t*sin(theta)-1/2*g*t^2

>> dys=subs(dy,{v0 theta g},{20 pi/4 9.8})dys =10*t*2^(1/2)-49/10*t^210 t 2 (1/2) 49/10 t 2

(c) 2009 Brian Funt, Simon Fraser University 390

Page 391: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

2

0

1)sin(

)cos(

gttvd

tvdx

−=

=

θ

θ

syms v0 t theta g

0 2)sin( gttvd y = θ

>> dx=v0*t*cos(theta)dx =v0*t*cos(theta)

Declare the symbols

Express the equations in Matlab form

>> dy=v0*t*sin(theta) -0.5*g*t^2dy =v0*t*sin(theta)-1/2*g*t^2

>> dys=subs(dy,{v0 theta g},{20 pi/4 9.8})dys =10*t*2^(1/2)-49/10*t^210 t 2 (1/2) 49/10 t 2

(c) 2009 Brian Funt, Simon Fraser University 391

Page 392: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

2

0

1)sin(

)cos(

gttvd

tvdx

−=

=

θ

θ

syms v0 t theta g

0 2)sin( gttvd y = θ

>> dx=v0*t*cos(theta)dx =v0*t*cos(theta)

>> dy=v0*t*sin(theta) -0.5*g*t^2dy =v0*t*sin(theta)-1/2*g*t^2

>> dys=subs(dy,{v0 theta g},{20 pi/4 9.8})dys =10*t*2^(1/2)-49/10*t^2

Substitute in some actual valuesfor v0, theta, and g.

10 t 2 (1/2) 49/10 t 2

(c) 2009 Brian Funt, Simon Fraser University 392

Page 393: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

2

0

1)sin(

)cos(

gttvd

tvdx

−=

=

θ

θ

syms v0 t theta g

0 2)sin( gttvd y = θ

>> dx=v0*t*cos(theta)dx =v0*t*cos(theta)

>> dy=v0*t*sin(theta) -0.5*g*t^2dy =v0*t*sin(theta)-1/2*g*t^2

>> dys=subs(dy,{v0 theta g},{20 pi/4 9.8})dys =10*t*2^(1/2)-49/10*t^210 t 2 (1/2) 49/10 t 2

>> ezplot(dys)

e plot(d s [0 3])

(c) 2009 Brian Funt, Simon Fraser University 393

ezplot(dys, [0 3])

Page 394: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

2

0

1)sin(

)cos(

gttvd

tvdx

−=

=

θ

θ

syms v0 t theta g

0 2)sin( gttvd y = θ

>> dx=v0*t*cos(theta)dx =v0*t*cos(theta)

>> dy=v0*t*sin(theta) -0.5*g*t^2dy =v0*t*sin(theta)-1/2*g*t^2

>> dys=subs(dy,{v0 theta g},{20 pi/4 9.8})dys =10*t*2^(1/2)-49/10*t^210 t 2 (1/2) 49/10 t 2

>> ezplot(dys)

e plot(d s [0 3])

(c) 2009 Brian Funt, Simon Fraser University 394

ezplot(dys, [0 3])

Page 395: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

2

0

1)sin(

)cos(

gttvd

tvdx

−=

=

θ

θ

When will the ball hit the ground?

syms v0 t theta g

0 2)sin( gttvd y = θ

In other words, when is dys = 0?

>> dx=v0*t*cos(theta)dx =v0*t*cos(theta)

> solve(dys)

ans =0

>> dy=v0*t*sin(theta) -0.5*g*t^2dy =v0*t*sin(theta)-1/2*g*t^2

0(100*2^(1/2))/49

>> double(ans)

>> dys=subs(dy,{v0 theta g},{20 pi/4 9.8})dys =10*t*2^(1/2)-49/10*t^2

ans =0

2.886210 t 2 (1/2) 49/10 t 2

Equations from last slide

2.8862

(c) 2009 Brian Funt, Simon Fraser University 395

Page 396: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

To Try (we didn’t do this one in class)

Find how long will the golf ball be in the ‘air’ on Mars where the acceleration ofFind how long will the golf ball be in the air on Mars where the acceleration of gravity is 3.7 m/s2 when it’s hit at an angle of 30 degrees with an initial velocity of 50 m/s2

My answer is 13.5135 seconds on Mars. Compare that to what it would be on Earth.

(c) 2009 Brian Funt, Simon Fraser University 396

Page 397: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 33 Fall 2009

Previous lecture

S b li M th C tiSymbolic Math Computing

Equation solvingEquation solving

subs

(c) 2009 Brian Funt, Simon Fraser University 397

Page 398: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Golf Ball Range

0 )cos(tvd = θ v0 Initial Velocity

20

0

21)sin(

)cos(

gttvd

tvd

y

x

−= θ

θ v0 Initial Velocityg gravityt timetheta initial angle from horizontal

How far will the ball go?

(c) 2009 Brian Funt, Simon Fraser University 398

Page 399: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

General Case Strategy for Best Angle

(1) Solve y equation for the time t until the ball hits the ground when y=0.

(2) Substitute t into the equation for x to get an equation for the(2) Substitute t into the equation for x to get an equation for the range (i.e, the distance travelled until hitting the ground).

(3) The range equation will be a function of the angle theta

(4) We want to maximize range function, so(1) Differentiate the range equation(2) Solve for it equal to zero(2) Solve for it equal to zero

(c) 2009 Brian Funt, Simon Fraser University 399

Page 400: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

2

0

1)sin(

)cos(

gttvd

tvdx

−=

=

θ

θ

syms v0 t theta g

0 2)sin( gttvd y = θ

>> dx=v0*t*cos(theta)dx =v0*t*cos(theta)

>> dy=v0*t*sin(theta) -0.5*g*t^2dy =v0*t*sin(theta)-1/2*g*t^2

General equations from before but without subs

(c) 2009 Brian Funt, Simon Fraser University 400

Page 401: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

2

0

1)sin(

)cos(

gttvd

tvdx

−=

=

θ

θSolve for t from the dy equation.Thi i h b ll hit d

syms v0 t theta gtf=solve(dy,t)

0 2)sin( gttvd y = θ This is when ball hits ground.

dy=0

>> dx=v0*t*cos(theta)dx =v0*t*cos(theta)

tf =0

2*v0*sin(theta)/g>> dy=v0*t*sin(theta) -0.5*g*t^2dy =v0*t*sin(theta)-1/2*g*t^2

( ) g

(c) 2009 Brian Funt, Simon Fraser University 401

Page 402: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

2

0

1)sin(

)cos(

gttvd

tvdx

−=

=

θ

θ

syms v0 t theta gtf=solve(dy,t)

0 2)sin( gttvd y = θ

>> dx=v0*t*cos(theta)dx =v0*t*cos(theta)

tf =0

2*v0*sin(theta)/g>> dy=v0*t*sin(theta) -0.5*g*t^2dy =v0*t*sin(theta)-1/2*g*t^2

( ) g

>> range=subs(dx,t,tf(2))range =2*v0^2*sin(theta)/g*cos(theta)2*v0^2*sin(theta)/g*cos(theta)

S b tit ti t i t th d tiSubstituting t into the dx equation gives us the distance the ball travelled (its range).

(c) 2009 Brian Funt, Simon Fraser University 402

Page 403: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Range as a function of theta

range =2*v0^2*sin(theta)/g*cos(theta)2 v0 2 sin(theta)/g cos(theta)

>> ezplot(subs(range,{v0, g}, {10, 9.8}), [0 pi/2])

(c) 2009 Brian Funt, Simon Fraser University 403

Page 404: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

What’s the Angle with Max Range?

Calculus problem: Find where first derivative is zeroCalculus problem: Find where first derivative is zero.

>> dr=diff(range)dr = Take Deriviative Differentiate rangedr 4*v0*sin(theta)/g*cos(theta)

Take Deriviative Differentiate range

(c) 2009 Brian Funt, Simon Fraser University 404

Page 405: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

What’s the Angle with Max Range?

Calculus problem: Find where first derivative is zeroCalculus problem: Find where first derivative is zero.

>> dr=diff(range)dr =dr 4*v0*sin(theta)/g*cos(theta)

>> solve(dr,theta)ans =1/2*pi

0

Solve for where deriviative is zero

(c) 2009 Brian Funt, Simon Fraser University 405

Page 406: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

What’s the Angle with Max Range?

Calculus problem: Find where first derivative is zeroCalculus problem: Find where first derivative is zero.

>> dr=diff(range)dr =dr 4*v0*sin(theta)/g*cos(theta)

>> solve(dr,theta) This is the wrong answer. Why?ans =1/2*pi

0

This is the wrong answer. Why?

(c) 2009 Brian Funt, Simon Fraser University 406

Page 407: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

diff defaults to variable closest to ‘x’>> diff(range)ans =4*v0*sin(theta)/g*cos(theta)4 v0 sin(theta)/g cos(theta)

>> diff(range,g)ans =2* 0^2* i ( h )/ ^2* ( h )-2*v0^2*sin(theta)/g^2*cos(theta)

>> diff(range,v0)ans =ans 4*v0*sin(theta)/g*cos(theta)

>> diff(range, theta)ans =2*v0^2*cos(theta)^2/g-2*v0^2*sin(theta)^2/g

(c) 2009 Brian Funt, Simon Fraser University 407

Page 408: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Solve also chooses a default variable

>> dr=diff(range theta)>> dr=diff(range,theta)dr =2*v0^2*cos(theta)^2/g-2*v0^2*sin(theta)^2/g

>> solve(dr)ans =0

00

>> solve(dr, theta)ans = Recommend always

-1/4*pi1/4*pi

Recommend always specifying variable for solve or diff

(c) 2009 Brian Funt, Simon Fraser University 408

Page 409: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Second Derivatives

range =

2*v0^2*sin(theta)/g*cos(theta)

Third argument to diff specfies nth

>> diff(range,theta,2)

ans =

derivative

-8*v0^2*sin(theta)/g*cos(theta)

(c) 2009 Brian Funt, Simon Fraser University 409

Page 410: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Partial Derivatives

>> syms x y2

y y>> f=2*x^2+3*y

f =2*x^2+3*y

yxyxf 32),( 2 +=

2*x^2+3*y

>> diff(f,x)

ans =4*x

>> diff(f y)3),(

=∂

∂y

yxf>> diff(f,y)ans =3

y

(c) 2009 Brian Funt, Simon Fraser University 410

Page 411: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Symbolic Plotting with ezsurf

ezsurf('exp(-(X^2 + Y^2))', [-2 2])ezsurf('exp(-(X^2 + Y^2))')

( p( ( )) , [ ])

(c) 2009 Brian Funt, Simon Fraser University 411

Page 412: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Partial Derivative of Gaussian

syms X Y>> gauss = sym(exp(-(X^2 + Y^2)))gauss =gauss =exp(-X^2-Y^2)

>> gaussX=diff(gauss, X)gaussX =-2*X*exp(-X^2-Y^2)

>> ezsurf(gaussX) ezsurf(gaussX)

(c) 2009 Brian Funt, Simon Fraser University 412

Page 413: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Passing symbolic expressions

%plotDf(symbolic function of one variable) creates a 3D surface p ( y _ _ _ _ )%plot of the first derivative of the function.%Main point of this is as an example of the fact that symbolic expressions%can be passed as parameters to functionsfunction plotDf(fn var)function plotDf(fn,var)ezsurf(diff(fn,var))

plotDf('exp(-(X^2 + Y^2))', 'x')

(c) 2009 Brian Funt, Simon Fraser University 413

Page 414: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Limits>> subs(sinc x 1)>> subs(sinc,x,1)ans =

0.6366

>> subs(sinc,x,0)Warning: Divide by zero.> In sym.subs at 127

ans =NaN

>> limit(sinc,x,0)ans =1

> syms x>> sinc = sym(sin(pi/2*x)/(pi/2*x))

>> limit(sinc,x,1)ans =2/pi

sinc =2*sin(1/2*pi*x)/pi/xezplot(sinc)

(c) 2009 Brian Funt, Simon Fraser University 414

2/pi

Page 415: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Integration

%Indefinite integrali t( i ( ) l ( ))

%Definite integrali t( i ( ) l ( ) 0 i)>> a=int(sin(x)+log(x))

a =

-cos(x)+x*log(x)-x

>> a=int(sin(x)+log(x),0,pi)a =2-pi+pi*log(pi)

( ) g( )>> double(a)

ans =2 45472.4547

(c) 2009 Brian Funt, Simon Fraser University 415

Page 416: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Definite Integration (again)

>> a=int(x*log(x) x 3 4)>> a=int(x log(x),x,3,4)a =16*log(2)-7/4-9/2*log(3)

>> double(a)ans =

4.3966

(c) 2009 Brian Funt, Simon Fraser University 416

Page 417: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Definite Integration (again)

∫4

∫=3

log xxa

>> a=int(x*log(x))>> a int(x*log(x) x 3 4) >> a=int(x*log(x))a =1/2*x^2*log(x)-1/4*x^2

>> a=int(x*log(x),x,3,4)a =16*log(2)-7/4-9/2*log(3)

>> subs(a,x,4) - subs(a,x,3)ans =

4.3966

>> double(a)ans =

4.3966

(c) 2009 Brian Funt, Simon Fraser University 417

Page 418: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Symbolic bounds of integration

>> syms p q>> a=int(x*log(x),x,p,q)

a =

∫q

1/2*q^2*log(q)-1/4*q^2-1/2*p^2*log(p)+1/4*p^2

>> b ( { } {3 4})

∫=p

xxa log

>> subs(a,{p q}, {3 4})

ans =

4.3966

(c) 2009 Brian Funt, Simon Fraser University 418

Page 419: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Labeling a Cylindrical Tank’s Volume

hy

dy

L w

∫==hwdyLALV

0Where should the li b f 20 40lines be for 20, 40, 60 thousand litres if L=8m and R=3m? Problem is from Matlab An Introduction with

Applications, by Amos Gilat

(c) 2009 Brian Funt, Simon Fraser University 419

Applications, by Amos Gilat

Page 420: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Calculating w

2⎞⎛

R

22)(2

RyRw=−+⎟

⎠⎞

⎜⎝⎛

RR - y

syms R y w L;w=solve((w/2)^2+(R-y)^2-R^2,w)

w/2w/2 w =2*(2*R*y-y^2)^(1/2)

-2*(2*R*y-y^2)^(1/2)( y y ) ( )

(c) 2009 Brian Funt, Simon Fraser University 420

Page 421: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Integrating for Volume

%let ig be the integrandi L* (1)>> ig=L*w(1)

ig =2*L*(2*R*y-y^2)^(1/2) ∫==

hwdyLALV

0

%Integrate for the volume as function%of height h>> v=int(ig,y,0,h)v =

L*(2*R*h-h^2)^(1/2)*h-L*(2*R*h-h^2)^(1/2)*R-L*R^2*atan((-h+R)/(2*R*h-h^2)^(1/2))-) ( ) ( ))1/2*i*L*R^2*log(i*R^(1/2))+1/2*i*L*R^2*log(-i*R^(1/2))

(c) 2009 Brian Funt, Simon Fraser University 421

Page 422: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Integrating for Volume

%let ig be the integrandi L* (1)

% Substitute in for length and radius>> v83=subs(v,{L R}, {8 3})

83>> ig=L*w(1)ig =2*L*(2*R*y-y^2)^(1/2)

v83 =8*(6*h-h^2)^(1/2)*h-24*(6*h-h^2)^(1/2)-72*atan((-h+3)/(6*h-h^2)^(1/2))-36*i*log(i*3^(1/2))+36*i*log(-i*3^(1/2))

%Integrate for the volume as function%of height h>> v=int(ig,y,0,h)

g( ( )) g( ( ))

%Solve for h, the height of the marker% for a volume of 20,000 litres>> solve(v83 20 h)v =

L*(2*R*h-h^2)^(1/2)*h-L*(2*R*h-h^2)^(1/2)*R-L*R^2*atan((-h+R)/(2*R*h-h^2)^(1/2))-

>> solve(v83-20,h)ans =.86245198985783601248732522490585

) ( ) ( ))1/2*i*L*R^2*log(i*R^(1/2))+1/2*i*L*R^2*log(-i*R^(1/2))

%Solve h again, but for 40,000 litres>> solve(v83-40,h)ans =1 3972414699718311678967923729135

(c) 2009 Brian Funt, Simon Fraser University 422

1.3972414699718311678967923729135

Page 423: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Lecture 35

Last timeLast timesymbolic integration using intindefinite and definite integrationindefinite and definite integrationusing symbolic bounds of the integrationsolving for the heights on a tank for specificsolving for the heights on a tank for specific volumes

(c) 2009 Brian Funt, Simon Fraser University 423

Page 424: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

“Improper” Integrals (of one type)>> syms x>> %Example of improper integral [1 infinity]>> f=sym(1/x^2)f =1/x^2

>> int(f) int(f)ans =-1/x

%Fi it b d%Finite bounds>> int(f,1,2)ans =1/2%Can we take bound out to infinity?>> int(f,1,Inf)

ans =1

(c) 2009 Brian Funt, Simon Fraser University 424

1

Page 425: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Differential Equations

Say we know something about a function’s derivative.

dy

Can we then figure out the function?

Simple case ydty=Simple case

If it were xdtdy

= we could just integrate.

(c) 2009 Brian Funt, Simon Fraser University 425

Page 426: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Differential Equations

Say we know something about a function’s derivative.

dy

Can we then figure out the function?

Simple case ydty=Simple case

Mi ht b th tt

t

ede=Might remember that e

dt=

(c) 2009 Brian Funt, Simon Fraser University 426

Page 427: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Differential Equations

Say we know a function’s derivative.

dy

Can we then figure out the function?

Simple case ydty=Simple case

Mi ht b th tt

t

ede=Might remember that e

dt=

So tey = is one solutionSo ey = is one solution

And so is tcey = for any constant c

(c) 2009 Brian Funt, Simon Fraser University 427

Page 428: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Matlab dsolve

ydtdy

=

>> dsolve('Dy=y')

ans =dt

C1*exp(t)

To pin down the constant C1 we need a boundary condition

It’s like us having a line of slope 3. We’d have y = 3x + bg y

To find b, we need a boundary condition that tells us some value of y(x)

y=dsolve('Dy=y' 'y(1)=2') ( )y=dsolve('Dy=y','y(1)=2')y =2/exp(1)*exp(t)

>> subs(y,'t',1)ans =

2

(c) 2009 Brian Funt, Simon Fraser University 428

Page 429: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Another differential equation example

ydy 2= What function y(t) has as its derivative 2y/t ?

tdt= What function y(t) has as its derivative 2y/t ?

>> dsolve('Dy=2*y/t')>> dsolve( Dy=2 y/t )ans =

C1*t^2

Makes sense since derivative of t2 is 2t

and 2t = 2 t2/t

%With boundary condition of y(3)=10%With boundary condition of y(3) 10>> dsolve('Dy=2*y/t', 'y(3)=10')ans =10/9*t^2

(c) 2009 Brian Funt, Simon Fraser University 429

Page 430: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Other ways to look at the equation

ydy 2=

tdt=

02=−

dtdy

ty

02

=−dtdyty

(c) 2009 Brian Funt, Simon Fraser University 430

Page 431: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Medication in Body

The amount of medication M in the body depends on rate of consumption and rate of injection into the body.

Rate of consumption proportional to amount M

Problem is from Matlab An Introduction with Applications, by Amos Gilat

(c) 2009 Brian Funt, Simon Fraser University 431

Page 432: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Medication in Body

The amount of medication M in the body depends on rate of consumption and rate of injection into the body.

Rate of consumption proportional to amount M

So we have:

pkMdt

dM+−=

dt

Constant of proportionality R t f i j tiConstant of proportionality Rate of injection

(c) 2009 Brian Funt, Simon Fraser University 432

Page 433: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Determining k Given Half-life

Suppose half life of medication is 3 hours

dM

Suppose half life of medication is 3 hours

Assume no medication added so p=0

kMdt

dM−=

At t 0 h t ti MAt t=0 we have a concentration M0

>> Mt=dsolve('DM = -k*M','M(0)=M0')kteMtM −)(

Mt =M0*exp(-k*t)

eMtM = 0)(

(c) 2009 Brian Funt, Simon Fraser University 433

Page 434: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Given half-life of 3 hours solve for k

>> Mt=dsolve('DM = -k*M' 'M(0)=M0')>> Mt=dsolve( DM = -k M , M(0)=M0 )

Mt =M0*exp(-k*t)

kteMtM −= 0)(

30

0)3( keMMM −==>> ks=solve('M0/2=M0*exp(-3*k)',k)

02)3( eMM

ks =1/3*log(2)

d bl (k )Concentration halves in 3 hours double(ks)ans =

0.2310

(c) 2009 Brian Funt, Simon Fraser University 434

Page 435: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Suppose patient given 50mg/hour, find concentration

pkMdt

dM+−= p = 50 and k = 0.2310

M(0) = 0 (patient has no drug to start)M(0) = 0 (patient has no drug to start)

>> syms p >> t=dsolve('DM = -k*M + p','M(0)=0')t =p/k-p/k*exp(-k*t)

>> ts=subs(t {p k} {50 ks})>> ts=subs(t,{p k},{50 ks})

ts =150/log(2)-150/log(2)*exp(-1/3*log(2)*t)

(c) 2009 Brian Funt, Simon Fraser University 435

Page 436: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Plot of concentration versus hours

>> ezplot(ts [0 24])>> ezplot(ts,[0 24])

(c) 2009 Brian Funt, Simon Fraser University 436

Page 437: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Writing to a File

Basically this is NOT covered in the textBasically this is NOT covered in the textTopics

Opening a fileOpening a filefopen

File identifierFile identifierfprintf with file identifier specified

(c) 2009 Brian Funt, Simon Fraser University 437

Page 438: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Opening a File for Writing Text

>> %Write a file of x and e^x>> x = 0: 1:1; Open the file for writing text.>> x 0:.1:1;>> y = [x; exp(x)];>> fid = fopen('exp.txt', 'wt');

p g“wt” indicates write and text

>> fprintf(fid, '%6.2f %12.8f\n', y);>> fclose(fid) fopen returns a file identifier.

It’s just a number Pass thatans =

0

It s just a number. Pass that file identifier number to fprintf

(c) 2009 Brian Funt, Simon Fraser University 438

Page 439: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

Many Options for File Reading and Writing

We don’t need to worry about them hereyShould be aware that they exist though

fscanfformatted reading similar to fprint

textreadreading textreading text

loadloading Matlab data

Other functions like imreadxlsread and xlswrite for Excel Spreadsheetsread AVI movie files etcread AVI movie files, etc.

(c) 2009 Brian Funt, Simon Fraser University 439

Page 440: CMPT 102 Introduction toCMPT 102 Introduction to …binay/102/Funt-LectureNotes/Funt-Lec_Cumulative-AL… · CMPT 102 in Matlab Matlab: You’ll like it! Matlab is very widely used

CMPT 102 Final Exam Instructions

Time: Sunday December 13, 2009 3:30-6:30pm (but please arrive early) Place: The large CSIL room (Applied Science Building 9838) NOTE that this is NOT the location listed in the exam schedule.

The exam will consist of two parts: one closed-book, the other using Matlab. The closed book part will be done first and will last 15 minutes. Only pen and pencil will be allowed. The second part will be 2 hours and 20 minutes and will include Matlab programming on the CSIL computers.

During the second part of the exam, you will be allowed access to (1) your course textbook, (2) Matlab and Matlab's help facility (as long as the computers work properly), (3) two double-sided, letter-sized sheets of whatever notes you like, (4) a file containing the complete lecture slides from the semester I'll mail out a copy soon(4) a file containing the complete lecture slides from the semester. I ll mail out a copy soon.

Cell phones, calculators, iPods, etc. will not be allowed. Bring a regular watch.

There's always the possibility that because of a technical problem the computer system will become il bl If 'll ti ith th b t t d d d il i hi hunavailable. If so, we'll continue with the exam, but as a standard paper-and-pencil exam in which

you would write your programs without access to Matlab.

Please try to arrive at CSIL by 3:15pm at the latest so that there will be time for you to get your temporary computer account. You will not be using your regular computer account so your files will

(c) 2009 Brian Funt, Simon Fraser University 440

p y p g y g p ynot be available to you.