rhodes university...contents i the matlab computationalenvironment iii 1 introduction 1 1.1 about...

162
RHODES UNIVERSITY DEPARTMENT OF MATHEMATICS AM 2.2 N UMERICAL M ETHODS WITH MATLAB Mike Burton 2009

Upload: others

Post on 06-Sep-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

RHODES UNIVERSITY

DEPARTMENT OF MATHEMATICS

AM 2.2

NUMERICAL METHODS WITH MATLAB

Mike Burton

2009

Page 2: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Contents

I The MATLAB Computational Environment iii

1 Introduction 1

1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

1.2 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

1.3 Arithmetic Calculations with MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

1.4 Matrix Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

2 MATLAB Scripts 39

2.1 Simple Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

2.2 A Note on Recursively Defined Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 48

2.3 Solutions and Lessons from Exercise 2.2.1 . . . . . . . . . . . . . . . . . . . . . . . . . 54

2.4 Making a Help File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

2.5 Data Import and export . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

3 Matrix Operators 66

3.1 Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

3.2 Logical Matrices for Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

4 Graphical Output 79

4.1 Two-Dimensional Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

4.1.1 Plotting Matrices Versus Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . 80

4.1.2 Plotting a Scalar Versus a Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

4.1.3 Plotting a Vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

4.1.4 Linestyles and Colours . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

4.1.5 Plotting Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

4.1.6 Superimposing Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

4.1.7 Plotting Closed Figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

4.1.8 Subplots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

4.1.9 Axis Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89

4.2 Curves in 3-D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

4.3 Surfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93

4.4 Contour Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

4.5 The Gradient Vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96

4.6 Saving Figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98

5 Flow Control 104

5.1 If-Constructs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104

5.2 For-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106

5.3 Decision Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108

5.4 While-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110

5.5 Switch-Case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112

i

Page 3: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

6 Functions 123

6.1 Function m-files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123

6.2 Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125

6.3 Inline Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127

6.4 Evaluating Functions with FEVAL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128

6.5 Variable Numbers of Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131

6.6 Subfunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133

6.7 Functions With No Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133

6.8 Self–Referential Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135

6.9 Pseudocode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138

6.10 The Mandelbrot Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146

6.11 The Julia Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150

6.12 Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151

6.13 Sound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154

II Numerical Methods 156

7 Solution of Equations 158

7.1 Non–Linear Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158

7.2 Using Inline Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169

7.3 Systems of Non-Linear Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170

8 Systems of Linear Equations 176

8.1 The General Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176

8.2 The Inverse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176

8.3 The Determinant of a Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177

8.4 The Backslash Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178

8.5 The Rank of a Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178

8.6 Reduction to Reduced Row-Echelon Form . . . . . . . . . . . . . . . . . . . . . . . . . . 179

9 Differential Equations 188

9.1 Professional Integrators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189

9.2 Systems of Differential Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196

9.3 Higher Order Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205

10 Optimisation 222

10.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222

10.2 One–Dimensional Optimisation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223

10.3 General Optimisation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229

10.4 Regression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231

10.5 Fitting Polynomials to Data Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233

10.6 The R2-Statistic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234

10.7 Non-linear Regression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241

11 Projects 246

ii

Page 4: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Part I

The MATLAB Computational

Environment

iii

Page 5: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

Real–world processes which can be expressed in some mathematical form generate mathematical prob-

lems whose solutions do not have an explicit mathematical solution. Such is often the case, for example,

with a problem whose solution is represented by the solution of an equation, system of equations, differ-

ential equation or system of differential equations. In many cases, the best we can do is find a numerical

approximation to the solution. This in turn is often found by means of some algorithm which generates suc-

cessive approximations to the solution. The study of these algorithms is called numerical methods. Before

computers, these approximate solutions were computed by hand and this was a lengthy and tedious pro-

cess. With the advent of computers these algorithms could be expressed as computer programs which run

at speeds many orders of magnitude greater than hand calculations. Output from these programs enhances

understanding of the numerical procedure and of the original problem.

The computational environment that we will use in this course is MATLAB and, in the first part of this

course, we come to grips with this powerful tool. In the second part of this course we employ MATLAB to

run programs which implement algorithms to solve certain selected numerical problems.

There is a third–year course, which is the natural sequel to this course, in which we investigate further

numerical procedures. Of course, MATLAB is used here to implement the algorithms.

The mathematical representation of real–world processes is called mathematical modelling. There is a

second–year course on this and a sequel in third–year. These courses also use the MATLAB system.

In honours there is a course on artificial neural networks. These are computer programs which learn

from data and are used to simulate complex processes and to perform pattern recognition. Here again,

MATLAB is the computational environment used for writing and deploying the neural networks.

So the MATLAB environment gives us a tool which is used in many of the courses in modern applied

mathematics. It is a vast system and we will have to be quite selective. We just cover what is needed for

our purposes, leaving the many other features to be discovered at a later time, when the need arises.

iv

Page 6: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Chapter 1

Introduction

1.1 About MATLAB

MATLAB is a high-performance language for technical computing. It integrates computation, visualization,

and programming in an easy-to-use environment where problems and solutions are expressed in familiar

mathematical notation. Typical uses include:

� Mathematics and computation

� Algorithm development

� Modelling, simulation, and prototyping

� Data analysis, exploration, and visualization

� Scientific and engineering graphics

� Application development, including graphical user interface building

MATLAB is an interactive system whose basic data element is an array. Some programming languages

require the user to declare what the nature of variables used. But MATLAB assumes that each variable

is a multidimensional complex-valued array. Multidimensional? Well, a vector is a 1-dimensional array

having form 1 � n or n� 1. The usual matrix encountered in mathematics is a 2-dimensional array, having

form m � n. If we have a stack of 2-dimensional matrices with one matrix to a page, then the pages

form another dimension and the entire stack forms a 3-dimensional array, which we could call a book. A

shelf of books is a 4-dimensional array and so on. This allows you to solve many technical computing

problems, especially those with matrix and vector formulations, in a fraction of the time it would take to

write a program in a scalar non-interactive language such as C or Fortran. The name MATLAB stands for

matrix laboratory. MATLAB was originally written to provide easy access to matrix software developed

by the LINPACK and EISPACK projects. Today, MATLAB uses software developed by the LAPACK

and ARPACK projects, which together represent the state-of-the-art in software for matrix computation.

MATLAB has evolved over a period of years with input from many users. In university environments,

it is the standard instructional tool for introductory and advanced courses in mathematics, engineering,

and science. In industry, MATLAB is the tool of choice for high-productivity research, development, and

analysis. MATLAB features a family of application-specific solutions called toolboxes. Very important to

most users of MATLAB, toolboxes allow you to learn and apply specialized technology. Toolboxes are

comprehensive collections of MATLAB functions (M-files) that extend the MATLAB environment to solve

particular classes of problems. Areas in which toolboxes are available include signal processing, control

systems, neural networks, fuzzy logic, wavelets, simulation, and many others.

The MATLAB system consists of five main parts:

1

Page 7: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

� Development Environment. This is the set of tools and facilities that help you use MATLAB functions

and files. Many of these tools are graphical user interfaces. It includes the MATLAB desktop and

Command Window, a command history, and browsers for viewing help, the workspace, files, and the

search path.

� The MATLAB Mathematical Function Library. This is a vast collection of computational algorithms

ranging from elementary functions like sum, sine, cosine, and complex arithmetic, to more sophisti-

cated functions like matrix inverse, matrix eigenvalues, Bessel functions, and fast Fourier transforms.

� The MATLAB Language. This is a high-level matrix/array language with control flow statements,

functions, data structures, input/output, and object-oriented programming features. It allows both

“programming in the small” to rapidly create quick and dirty throw-away programs, and “program-

ming in the large” to create complete large and complex application programs.

� Handle Graphics. This is the MATLAB graphics system. It includes high-level commands for two-

dimensional and three-dimensional data visualization, image processing, animation, and presentation

graphics. It also includes low-level commands that allow you to fully customize the appearance of

graphics as well as to build complete graphical user interfaces on your MATLAB applications.

� The MATLAB Application Program Interface (API). This is a library that allows you to write C and

Fortran programs that interact with MATLAB. It include facilities for calling routines from MATLAB

(dynamic linking), calling MATLAB as a computational engine, and for reading and writing MAT-

files.

MATLAB has a number of advantages over traditional languages:

� It is a high level language which allows easy coding.

� Variables and structures require very little attention and they can be declared on the fly.

� There is an interactive interface which allows experimentation while programming.

� There is a debugging window which facilitates the writing and debugging of programs.

� It supports object-oriented programming.

� High quality graphics facilities are available.

� MATLAB scripts are portable across a range of platforms.

� Specialised toolboxes can be added to the system.

� The MATLAB compiler can be used to link to compiled Fortran or C code.

These features make MATLAB a powerful tool for teaching, problem solving and research. It is widely

used in industry and in universities and is becoming an industrial standard.

We will be using MATLAB as a computational environment for mathematical experimentation. We will

encounter various real-world problems which we can express mathematically. Many of these problems will

not have a neat, closed-form mathematical solution and we will have to resort to numerical methods to solve

the problems. In many cases we will need to write a script (a program or function) to come to grips with

the problem. Some of these problems can be investigated by computer simulation - we simulate a physical

system on the computer.

2

Page 8: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

1.2 Getting Started

Launch MATLAB from the start button and the workspace window appears.

It may not look exactly like this since it varies with the computer on which it is installed. The view tab

at the top allows you to choose what is to be viewed in the second (left-hand) pane of the workspace. It is

probably best to get rid of it (click the close pane: X button at the top right) until it is needed.

You will find that MATLAB is extensively documented and any technical detail that you need can be

found here or by means of help at the command line, which we will discuss shortly. Theoretically, you could

page through the Help section and emerge with the necessary skills to use MATLAB as a computational

tool or a programming environment. However, it is my opinion that real learning only takes place through

application. We are therefore going to discover the MATLAB environment by means of problems. A

problem will be posed an then we will solve the problem using MATLAB and, in this way, we will discover

the basic features of MATLAB as we go. This will provide a basic skeleton of MATLAB skills which you

can flesh out as the need arises. The printable version allows you to print out pretty full documentation.

The command prompt:

>>

waits for commands to typed in and then executed by entering. Try

>> help

and a list of the help topics appears.

>> help

HELP topics:

matlab\general - General purpose commands.

matlab\ops - Operators and special characters.

matlab\lang - Programming language constructs.

matlab\elmat - Elementary matrices and matrix manipulation.

matlab\elfun - Elementary math functions.

matlab\specfun - Specialized math functions.

matlab\matfun - Matrix functions - numerical linear algebra.

and many more

If you pick one of these topics, say, elfun, then typing

>> help elfun

3

Page 9: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

produces the documentation for that topic. Try:

>> help help

Try:

>> help +

>> help diary

>> help lookfor

The Help facility provides some cute demos which you can watch by clicking on HelpnDemos or typing

>> demo

Full documentation at Rhodes University can be found at http://matlab.ru.ac.za/.

Run the Desktop Environment demo now. You will only be able to make an informed opinion about what

to view when you have worked with MATLAB for a while and so we are going to start by using MATLAB

as a computational device. Each time you encounter a new MATLAB command, view the documentation

on it.

Some MATLAB-related Books

[1] A. Kharab and R. B. Guenther, An Introduction to Numerical Methods – a MATLAB Approach,

Chapman Hall.

This book is prescribed for this course. It is well–written and has an excellent set of exercises. It will

be referred to throughout the course and you must have a copy since extra reading and projects will

be assigned from this book. In 2009 it will be prescribed for Numerical Analysis AM 3.1 – the big

brother to this course.

[2] Hahn, Brian D, Essential MATLAB for scientists and engineers, Third edition, Pearson Education.

This book was prescribed for this course in 2007. It is, in my opinion, the best introduction to

MATLAB and it is also the cheapest. It is available from UPB. By the way, Brian Hahn was an

applied mathematician at UCT. He has written many successful books on scientific computing. Sadly,

he was killed recently.

[3] Quarteroni, A. and Saleri, F., Scientific Computing with MATLAB and Octave, 2 nd ed, Springer.

This is also an excellent book and is prescribed for the third year course: Numerical Methods (AM

3.1) in 2008.

4

Page 10: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

[4] Chapman, Stephen J, MATLAB Programming for Engineers, Brookes/Cole.

This book was prescribed for the course in 2001 and there are a few copies still available at UPB.

[5] Higham D J & Higham N J, MATLAB Guide, SIAM.

A great book with well-chosen examples but no exercises.

[6] Redfern D & Campbell C, The MATLAB 5 Handbook, Springer.

This book contains detailed documentation for MATLAB functions and commands. Although this is

for the earlier version of MATLAB, most of the documentation still applies.

[7] Chen K, Giblin P & Irving A, Mathematical Explorations with MATLAB, Cambridge UP.

There are many interesting examples and exercises in this book.

[8] Van Loan, C, Introduction to Scientific Computing, Prentice Hall.

A very nice but brief introduction to MATLAB is followed by applications of MATLAB to numerical

analysis.

[9] Marchand P, Graphics and GUIs with MATLAB, CRC.

The full Monty on graphics and GUIs. The wireheads and computer geeks will love this one.

[10] Hunt, Lipsman & Rosenberg, A Guide to MATLAB for Beginners and Experienced Users, Cam-

bridge UP

Worth a look.

Some General References on Numerical Methods

If you visit the website:

www.mathworks.com

you will find, under Products, references to many books on MATLAB and its applications.

So, with MATLAB fired up and ready to go, we start learning to use this amazing computing envi-

ronment. We start by using MATLAB as a calculating device and then we learn to write programs with

MATLAB.

1.3 Arithmetic Calculations with MATLAB

At the command prompt, type in (and then press enter):

v = 3+5

v =

8

MATLAB has created a variable, v, and assigned the double precision number 8 to the variable: v. Theequals sign here is not the familiar equivalence relation used in mathematics. If you type

v = 10

then you are commanding MATLAB to assign the number 10 to the variable v. Check your variables by:

>> whos

Name Size Bytes Class

v 1x1 8 double array

MATLAB also has

5

Page 11: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> who

which just lists the variables in play. The other arithmetic operations are illustrated by:

>> 3-5

ans =

-2

Since no variable was specified, MATLAB has created its own: ans.

>> m=3*5

m =

15

>> 3/5

ans =

0.6000

>> p=3ˆ5

p =

243

Variables consist of a letter, followed by any number of digits or underscores. MATLAB uses only thefirst 31 characters of a variable’s name and ignores the rest.

>> v1234567891234567890123456789012345=2

v123456789123456789012345678901 =

2

illustrates the point. MATLAB is case sensitive, so V and v are different variable names. To clear thevariables:

>> clear

and now the are no variables in the workspace.If you type

>> x = 34

x =

34

>> X = ’34’

X =

34

Here the double precision number, 34, has been assigned to the variable, x and the character array, orstring, 34 has been assigned to the variable X. To see the difference, type:

>> whos

Name Size Bytes Class

X 1x2 4 char array

x 1x1 8 double array

Grand total is 3 elements using 12 bytes

More about strings later, for now let us get used to this process of assigning values to variables by using

MATLAB as a huge calculator to solve the problem: An amount of R1234 is deposited in an account which

bears 13% interest, evaluated at each year-end. Find the value of the account after 4 years.Here we go.

>> clc

clears the command window for a fresh start and

>> clear

6

Page 12: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

clears all variables (>>help clear).

We now define variables: balance, year, interest, rate. The variable rate will remain fixed

but the others will be initiated and then successively changed. We initiate the variables:

>> balance=1234

balance =

1234

>> year=1

year =

1

>> rate=.13

rate =

0.1300

>> interest=rate*balance

interest =

160.4200

MATLAB is revealing the value of the variable: interest, correct to 4 decimal places. This is theusual format, which is called short. A more convenient format for this problem is:

>> format bank

To see other options:

>> help format

FORMAT Set output format.

All computations in MATLAB are done in double precision.

FORMAT may be used to switch between different output

display formats as follows:

FORMAT Default. Same as SHORT.

FORMAT SHORT Scaled fixed point format with 5 digits.

FORMAT LONG Scaled fixed point format with 15 digits.

FORMAT SHORT E Floating point format with 5 digits.

FORMAT LONG E Floating point format with 15 digits.

FORMAT SHORT G Best of fixed or floating point format with 5 digits.

FORMAT LONG G Best of fixed or floating point format with 15 digits.

FORMAT HEX Hexadecimal format.

FORMAT + The symbols +, - and blank are printed

for positive, negative and zero elements.

Imaginary parts are ignored.

FORMAT BANK Fixed format for dollars and cents.

FORMAT RAT Approximation by ratio of small integers.

Spacing:

FORMAT COMPACT Suppress extra line-feeds.

FORMAT LOOSE Puts the extra line-feeds back in.

Now:

>> interest

interest =

160.42

We replace the variable, balance by the new balance:

>> balance = balance + interest

balance =

1394.42

7

Page 13: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

It is important to understand exactly what this means. The variable, balancewas storing the value 1234

and we have replaced that by the new value 1394.42, which is the old balance plus the interest. Computer

scientists sometimes use the notation

x x C y

to stress the fact that the variable x is being replaced by x C y. We will use the equals sign, D, instead of

the replacement arrow sign, . But bear in mind what it means. In this context, it is not the old familiar

equivalence relation from mathematics.The variable, balance now stores the balance at the end of year 1. We update the value stored in the

variable, year:

>> year=year+1

year =

2.00

We compute the interest for the next year and update the values in the variables interest, balance:

>> interest=rate*balance

interest =

181.27

>> balance=balance + interest

balance =

1575.69

For year 3 and beyond we continue the process. By the way, you can use the smart up-arrow " to findprevious commands. Type

>> y

and then use the up-arrow " to find year and then type:

>> year=year+1

year =

3.00

Do the same for the other variables:

>> interest=rate*balance

interest =

204.84

>> balance=balance+interest

balance =

1780.53

>> year=year+1

year =

4.00

>> interest=rate*balance

interest =

231.47

>> balance=balance+interest

balance =

2012.00

This is the balance after 4 years, which is confirmed by:

>> 1.13ˆ4*1234

ans =

2012.00

8

Page 14: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

For practice, suppose we start with R1500 at 15% annual interest and make fixed deposits of R1200 ateach year-end. Find the balance after 4 years. Let’s use simpler variable names this time:

>> y=1

y =

1.00

>> r=.15

r =

0.15

>> b=1500

b =

1500.00

>> i=b*r

i =

225.00

>> d=1200

d =

1200.00

>> b=b+i+d

b =

2925.00

>> y=y+1

y =

2.00

>> i=b*r

i =

438.75

>> b=b+i+d

b =

4563.75

Continue to obtain:

b =

8615.56

at the end of year 4.

1.3.1 Exercise

[1] Which of the following are valid names for MATLAB variables?

(a) my_name

(b) My_name

(c) my-name

(d) M32

(e) m-34

(f) _32M

(g) M_34

(h) D$

[2] An amount of R10 000 is deposited into an account which bears interest at the rate of 12% per year.

Each subsequent year an additional deposit of R1000 is deposited into the account. Find the balance

after 5 years

9

Page 15: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

[3] A population of 2000 slave workers lives in a radioactive wasteland. The birth rate is 3% per year

but the death rate is 5% per year. The government therefore deposits 100 people per year in the land.

Find the size of the population after 5 years.

[4] Complex numbers are entered in the natural way in the form

a+i*b

or

complex(a,b)

For example

>> a=3;

>> b=4;

Note that the semicolon at the end of a line causes MATLAB to suppress displaying the result. If youdo not want MATLAB to echo a typed command, end the line with a semicolon.

>> z=a+i*b

z =

3.0000 + 4.0000i

>> w=complex(a,b)

w =

3.0000 + 4.0000i

The functions real and imag produce the real and imaginary parts of a complex number.

Initiate variables, c and z. Let z start off as c and then successively replace z by z2 C c. In other

words, we are going to generate the sequence:

c; c2 C c; .c2 C c/2 C c; ..c2 C c/2 C c/2 C c; � � �

For example

>>format long

>> c=.2+.3*i;

>> z=c;

>> z=zˆ2+c

z =

0.15000000000000 + 0.42000000000000i

Repeat this a number of times:

>> z=zˆ2+c

z =

0.04610000000000 + 0.42600000000000i

>> z=zˆ2+c

z =

0.02064921000000 + 0.33927720000000i

>> z=zˆ2+c

z =

0.08531737143378 + 0.31401161230202i

>> z=zˆ2+c

z =

0.10867576120785 + 0.35358129072259i

>> z=zˆ2+c

z =

0.08679069192506 + 0.37685143183626i

10

Page 16: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

Is it possible that the sequence of complex numbers so generated converges, or remains bounded?Let us iterate 200 times as follows:

>> for k=1:200

z=zˆ2+c;

end

This is called a for-loop or a deterministic-loop since a process is repeated for a pre-determinednumber of iterations. After this, the value of z is seen to be:

>> z

z =

0.07920424995319 + 0.35646747854111i

If we now iterate further:

>> z=zˆ2+c

z =

0.07920424995319 + 0.35646747854111i

>> z=zˆ2+c

z =

0.07920424995319 + 0.35646747854111i

>> z=zˆ2+c

z =

0.07920424995319 + 0.35646747854111i

we see that the sequence seems to be converging. At any rate the sequence is bounded. Try this out

for z D 0:1C i0:7 and you will see that the sequence diverges - the last element is NaN +iNaN. Try

this out for various c and you will see that sometimes the sequence is bounded and sometimes it is

not. Furthermore, the set of c for which the sequence converges is not at all obvious. This is what it

looks like.

−2 −1.5 −1 −0.5 0 0.5

−1

−0.8

−0.6

−0.4

−0.2

0

0.2

0.4

0.6

0.8

1

This set is known as the Mandelbrot Set and it has a strange beauty and many curious properties. It

is self-similar in the sense that, as you peer deeper and deeper into it, copies of the whole set appear

as subsets. Peer into these subsets and there is an infinite sequence of copies of the whole. This type

of set is called a fractal. We will generate this set later.

11

Page 17: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

[5] Recall that Newton’s Method of solving f .x/ D 0 (finding a root of f .x/) involves making an initial

guess, x and then adding a correction h given by:

h D ! f .x/

f 0.x/I

The new estimate of the root is then given by x C h. This process is repeated and a sequence

is generated which, under favourable circumstances, converges to the root. Let us try this out by

evaluatingp

2 by finding the root of f .x/ D 2 ! x2. We start with the guess x D 1.

>> x=1;

>> h=-(2-xˆ2)/(-2*x)

h =

0.50000000000000

>> x=x+h

x =

1.50000000000000

>> h=-(2-xˆ2)/(-2*x)

h =

-0.08333333333333

>> x=x+h

x =

1.41666666666667

>> h=-(2-xˆ2)/(-2*x)

h =

-0.00245098039216

>> x=x+h

x =

1.41421568627451

>> h=-(2-xˆ2)/(-2*x)

h =

-2.123899819940621e-006

>> x=x+h

x =

1.41421356237469

The sequence is converging rapidly to the root. Check by

>> sqrt(2)

ans =

1.41421356237310

>> error=abs(ans-x)

error =

1.594724352571575e-012

>>

Use the same procedure to find3p

10.

[6] Recall the Euclidean Algorthm for finding the greatest common divisor (gcd) of two numbers, a; b,

with a � b, is as follows.

Divide b into a and call the remainder c. This is produced by the function rem. If c D 0 thengcd.a; b/ D b. Otherwise replace a by b, replace b by c, recalculate c and repeat until c D 0, atwhich point the gcd is b. For example

>> a=168;

>> b=32;

12

Page 18: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> c=rem(a,b)

c =

8

>> a=b

a =

32

>> b=c

b =

8

>> c=rem(a,b)

c =

0

>>

So gcd.168; 32/ D 8, which can be confirmed by

> gcd(168,32)

ans =

8

Find the gcd of various pairs of numbers using the Euclidean Algorithm. Verify with gcd.

1.4 Matrix Algebra

Matrix Operations and Functions

Matrices are entered row by row, with spaces, or commas, separating the elements in a row and semi-colonsseparating the rows. So, for example:

>> A=[ 1 3 5; 2, 4, 8]

A =

1 3 5

2 4 8

defines a variable, A as the matrix above. The matrix operations of scalar multiplication, addition,subtraction and transpose are performed in the natural way using: �;C;!;0. For example

>> B=2*A

B =

2 6 10

4 8 16

>> C=A+B

C =

3 9 15

6 12 24

C1=C+1

C1 =

4 10 16

7 13 25

(MATLAB does the most reasonable thing and adds 1 to each entry.)

>> D=A-B

D =

-1 -3 -5

-2 -4 -8

13

Page 19: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> E=D’

E =

-1 -2

-3 -4

-5 -8

E is the transpose. The operator: � is also used to denote matrix multiplication:

>> x=[ 1 2; 3 4]

x =

1 2

3 4

>> y=[5 6 7; 8 9 1]

y =

5 6 7

8 9 1

>> z=x*y

z =

21 24 9

47 54 25

Of course, the matrices must be compatible. Try:

>> C*B

??? Error using ==> *

Inner matrix dimensions must agree.

For square matrices we have the exponentiation operator : O .>> M=[ 4 5; 6 7]

M =

4 5

6 7

>> N=Mˆ3

N =

514 615

738 883

Pointwise operations are denoted in the natural way by: � O and �� and so on. For example

>> M=[ 1 2; 3 4]

M =

1 2

3 4

>> N=M.ˆ2

N =

1 4

9 16

forms a new matrix by squaring each element. So the matrix N is the pointwise square of the matrix M .

>> P=M.*N

P =

1 8

27 64

forms the pointwise product of the matrices. Similarly:

>> P./M

ans =

1 4

9 16

14

Page 20: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

forms the pointwise quotient of the matrices. Type

>> help

for a list of the operators. MATLAB’s arithmetic operators obey the usual precedence rules. In order of

precedence:

[1] ^

[2] �; =

[3] C;!

Parentheses can always be used to overrule precedence and/or provide clarity or avoid ambiguity. Forexample

>> a=2ˆ3+2*4

a =

16

>> b=(2ˆ(3+2))*4

b =

128

>> c=2ˆ(3+2)*4

c =

128

>> d=2ˆ((3+2)*4)

d =

1048576

Errors and floating point arithmetic

When we apply mathematics, we quite often have to use approximations of real numbers. Consider, for

example, the problem of computing the volume of a cone with height h D 10 cm and base diameter d D 2

cm. The formula which applies is

V D 1

3�

d2

4h:

First we note that � is an irrational number which has infinitely many digits after the decimal point,

� D 3:1415926::: Of course we cannot do any exact computation with this number since we do not know

all of � ’s digits. So we may approximate � by 3:14. But even then our result would be V D 10:4666666::::

and we will also approximate this for further computations to 10.47, say.

So the problem of approximating numbers is quite central. (It is even more fundamental: whenever we

make a measurement, we may not hope that our measurement is exact. Neither the scales are so in general

nor our ability to compare a scale to a quantity. Only in the case of counting objects there is a certain chance

to get exact results.)

One way of approximating is chopping. We decide on the number of digits after the decimal point and

simply cut the rest off. If we wish e.g. to approximate � to n digits by chopping, we get the following table

n 0 1 2 3 4 5 ...

approx(� ) 3 3.1 3.14 3.141 3.1415 3.14159 ...

Another way of approximation is rounding. Here we search for the closest real number with exactly n

digits after the decimal point. If x D :::a3a2a1:d1d2d3:::dndnC1::: then we add 5�10 nC1 to x and chopp.

For the number � we get the following table:

15

Page 21: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

n 0 1 2 3 4 5 ...

approx(� ) 3 3.1 3.14 3.142 3.1416 3.14159 ...

For practical implementation of chopping and rounding, most computer languages allow chopping or

rounding to the nearest integer. In MATLAB the functions fix and round do this job. Try help fix

and help round to see how they work. With such functions, we can chopp or round a real number x to

n digits as follows.

xapprox x � 10ˆn

xapprox f ix.xapprox/ (or round.xapprox/)

xapprox xapprox � 10ˆ.!n/

As a practical example we round � D 3:1415926::: to 3 digits. This is achieved by first multiplying by

103, then rounding and finally dividing by 103. You can find � in MATLAB entering pi. We proceed as

follows.

>>format long

>>x = pi

>>xa = x*10ˆ3

>>xa=round(xa)

>.xa=xa/10ˆ3

The result of this algorithm is xa = 3.14200000000000

Of course, by rounding and chopping we introduce errors in our calculations.

Let x be a real number and let x� be an approximation of x. Then

Ex.x�/ D jx ! x�j is called the absolute error of x� with respect to xI

Rx.x�/ D jx ! x�jjxj is called the relative error of x� with respect to x.

(In the latter case we assume x 6D 0.)

1.4.1 Example

[1] If x D 3:14159 and x� D 3:14 then Ex.x�/ D 0:00159 and Rx.x�/ D 0:00506:::, i.e. the relative

error is about 0.5%

[2] If x D 0:001 and x� D 0:002 then Ex.x�/ D 0:001 and Rx.x�/ D 1, i.e. the relative error is 100%

[3] If x D 99995 and x� D 100000 then Ex.x�/ D 5 and Rx.x�/ D 0:00005, i.e. the relative error is

0.005%

We see from the above examples that the absolute error is, without further information, no valuable

error measure. The relative error behaves much better, especially if jxj > 1.

1.4.2 Exercise

Assume that your computer has an ideal (which means exact) exponential function ex. Show by considering

exC�x ! ex � �x ex that a small relative error x� D x.1C �/ may result in an enormous relative error of

the result.

Let now ˇ be an integer, ˇ � 2. Then any real number x 2 IR has a unique representation in the form

x D ˙:d1d2d3::: � ˇe

We call d1d2d3::: the mantissa, ˇ the base and e the exponent. The digits di satisfy 0 � di � ˇ ! 1 for

all i D 1; 2; 3; ::: and moreover we want d1 � 1 (which is sometimes called then normalized).

16

Page 22: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

We are most familiar with the case ˇ D 10 – the decimal system. But the more general case poses no

theoretical difficulty. x D ˙:d1d2d3::: � ˇe is interpreted as

x D .d1 � ˇ 1 C d2 � ˇ 2 C d3 � ˇ 3 C :::/ � ˇe:

In the decimal system ˇ D 10 the number � will be represented as

� D C:31415926:::: � 101:

The number x D !0:00125 has as representation

x D !:125 � 10 2:

How does a computer represent real numbers? The representation is quite similar, but we may use only

finitely many digits and the possible range for the exponent is restricted. A floating point number system

.ˇ; t; L; U / is defined by a base ˇ, a mantissa length t and a (finite) exponent range ŒL; U �. A (normalized)

floating point number x has thus the form

x D ˙:d1d2d3:::dt � ˇe

with the exponent e satisfying L � e � U and mantissa d1d2:::dt . For the digits di it shall also hold

0 � di � ˇ ! 1 and d1 � 1. Moreover we define 0 D C:0000:::0 � ˇ0.

It is clear that every floating point number is a real number, but conversely there are more real numbers

than there are floating point numbers.

The format which most resembles this long e. Try:

>> format long e

>> p=pi

p =

3.141592653589793e+000

>> x=pˆ20

x =

8.769956796082693e+009

>> y=xˆ100

y =

Inf

>> z=yˆ2

z =

Inf

>> w=123.7*sin(1.7*p)

w =

-1.000754022041810e+002

>> c=1/x

c =

1.140256472468226e-010

Consider as an example the floating point number system .ˇ; t; L; U / D .10; 2;!1; 2/. There are 90

positive normalized mantissas

:10; :11; :12; :::::; :98; :99

and four possible exponents !1; 0; 1; 2. Thus there are 2 � 90 � 4 C 1 D 721 normalized floating point

numbers in this system, i.e. the set of floating point numbers is finite! The smallest positive floating point

number is :01 � 10 1 D 0:001 and the largest is C:99 � 102 D 99. Moreover the spaces between two

consecutive floating point numbers differ. We can use MATLAB to see this. Define

>>v = (10:99)*10ˆ(-2)

17

Page 23: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

i.e. v D .0:10; 0:11; :::; 0:99/ and consider

>>v1 = v*10ˆ(-1)

>>v2 = v*10ˆ0

>>v3 = v*10ˆ1

>>v4 = v*10ˆ2

We will find that in Œ0:01; 0:099� the spacing is 0.001, in Œ0:1; 0:99� the spacing is 0.01, in Œ1; 9:9� the

spacing is 0.1 and finally that in Œ10; 99� the spacing is 1.

If x is a real number, then we denote f l.x/ the nearest floating point number representing x on the

computer. f l.x/ is either found by chopping the digits dtC1dtC2::: from x or by rounding x to t digits.

Both is only possible if x is in the range of the floating point numbers. Real number outside this range

cannot be represented.

As floating point numbers are not equally spaced, the error in representing real numbers by floating

point numbers is not uniform. But the relative error is always small.

1.4.3 Lemma

For a system of floating point numbers .ˇ; t; L; U / let the real number x satisfy ˇL < x < ˇU . Then

jx ! f l.x/jjxj � 1

2ˇ1 t

Proof: We assume that x is positive and has the base ˇ representation

x D C:d1d2:::dt dtC1::: � ˇe

with d1 � 1. We assume further that dtC1 < ˇ=2, so that we need not round but only chopp. Then

f l.x/ D C:d1d2:::dt � ˇe

and therefore

x ! f l.x/ D C:dtC1dtC2::: � ˇe t

which is � ˇe t=2 as dtC1 < ˇ=2. As moreover, as a consequence of 1 � d1, x � ˇe 1 we find finally

x ! f l.x/

x� 1

2� ˇe t

ˇe 1D 1

2ˇ1 t

Another way to put this is:

f l.x/ D x.1C �/ with j�j � 1

2ˇ1 t :

The quantity eps D ˇ1 t=2 is called machine precision. It is an upper bound of the relative error of f l.x/

with respect to x and depends only on the base ˇ and the mantissa length t . Note that for ˇ D 2 we get

eps D 2 1 �21 t D 2 t . You can use the MATLAB command eps to obtain the machine precision of your

system.

Before we define now an idealized arithmetic for floating point numbers, we remark that in general the

product of two floating point numbers is not a floating point number. If e.g. the mantissa length t D 2 and

we have x D C:99 � 101; y D C:99 � 101 then x � y D C:9801 � 102, i.e. we would need four digits in

the mantissa. Also the resulting exponent could leave the exponent range. In this case a so-called overflow

error would occur, with different effects depending on the system. Usually however the operation is aborted

and an error message is output. (You can create such an overflow easily entering in MATLAB e.g. x = 2

and then, using smart recall, repeatedly x = x*x.)

We define for floating point numbers x; y the following operations:

x ˚ y D f l.x C y/

x y D f l.x ! y/

x ˇ y D f l.x � y/

x ˛ y D f l.x=y/

18

Page 24: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

provided that the results of the exact operations lie in the range of the floating point numbers. In this model

we compute the exact result and round it to the nearest floating point number. Let us, for an example,

consider the floating point number system .ˇ; t; L; U / D .10; 3;!9;C9/. Then we get for x D :123 �102; y D :527 � 101 the sum

x ˚ y D f l.12:3C 5:27/ D f l.17:57/ D f l.:1757 � 102/ D :176 � 102 D 17:6

As an illustration of the severe influences of floating point arithmetic on multiplication we evaluate .x !1/2 D .x ! 2/x C 1 at x D 1:04 in two ways. We find first

x 1 D f l.1:04 ! 1/ D C:4 � 10 1

.x 1/ˇ .x 1/ D f l.0:04 � 0:04/ D f l.0:0016/ D C:16 � 10 2

This is the exact result. If we evaluate the second form then we get

x 2 D f l.1:04 ! 2/ D f l.!0:96/ D !:96 � 100

.x 2/ˇ x D f l.!0:96 � 1:04/ D f l.!0:9984/ D !:998 � 100

..x 2/ˇ x/˚ 1 D f l.!0:998C 1/ D f l.0:002/ D :2 � 10 2

which has a relative error of 25% !

1.4.4 Exercise

[1] Evaluate x2!2xC1 at x D 1:04 in the floating point number system .ˇ; t; L; U /D .10; 3;!9;C9/.

[2] Prove x ˚ y D y ˚ x and x ˇ y D y ˇ x.

[3] Show in the floating point system .ˇ; t; L; U / D .10; 3;!9;C9/

� by considering x D C:801 � 101; y D C:125 � 101; z D C:808 � 102 that in general

.x ˇ y/ ˇ z 6D x ˇ .y ˇ z/

� by considering x D C:113 � 103; y D !:111 � 103; z D C:751 � 101 that in general

.x ˚ y/ ˚ z 6D x ˚ .y ˚ z/

� by considering x D C:200 � 103; y D !:600 � 102; z D C:603 � 101 that in general

.x ˚ y/ ˇ z 6D .x ˇ y/ ˚ .x ˇ z/

� by considering x D C:100 � 10 6; y D C:100 � 106; z D C:100 � 106 that during the

calculation of xˇ.yˇz/ an overflow error occurs but not during the calculation of .xˇy/ˇz.

[4] Show that the equation aC x D a may have many solutions x in floating point numbers.

[5] Evaluate with MATLAB the polynomial .x ! 1/6 D x6 ! 6x5 C 15x4 ! 20x3 C 15x2 ! 6x C 1 in

two ways near the zero in x D 1. To analyse the relative error of the second with respect to the first

enter the following:

>>delta = 0.005;

>>x = linspace(1-delta,1+delta,100);

>>px = x.ˆ6 - 6*x.ˆ5 + 15*x.ˆ4 - 20*x.ˆ3 + 15*x.ˆ2 - 6*x +1;

>>qx = (x-1).ˆ6;

semilogy(x,abs(px-qx)./abs(qx));

Use help linspace and help semilogy to find out, how these functions work. Try also

delta = 0.001, delta=0.003 etc.

[6] (Loss of significance) Suppose we have a floating point number system .ˇ; t; L; U / D .10; 10;!9;C9/

and we perform the computation

19

Page 25: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>>x = 0.6666666667*10ˆ(-1)

>>y = sin(x)

>>z = x-y}

What is the result?

(Answer: use MATLAB. You will get y = 0.06661729492672, which has a floating point rep-

resentation in our system of f l.y/ D 0:6661729492�10 1. Thus f l.x/!f l.y/ D 0:0004937175�10 1, which gives the floating point result 0:4937175000 � 10 4. The last three zeros of this result

are spurious, i.e. are not significant. The computer just supplies them.)

� Calculate the result of the subtraction 37:593621!37:584216 in the above floating point number

system. How many insignificant digits are in the result?

� Evaluate the function f .x/ Dp

x2 C 1 ! 1 at x D 1=300 in the above floating point number

system. How many insignificant digits has the result?

� Evaluate the function f .x/ D x2=.p

x2 C 1C 1/ (which is mathematically equivalent to the

function f .x/ in (b)!) at x D 1=300/ in the above floating point number system. How many

insignificant digits has now the result? The moral of this: avoid, whenever possible, the sub-

traction of almost equal numbers.

[7] The point of the last exercise is that numbers are represented in the computer by a finite system which

approximates the real numbers. Different numbers can have the same representation. Foe example

x =

1.000000000000000e+089

>> y=10ˆ89+1

y =

1.000000000000000e+089

Find other examples. Computations can generate errors which can become so large that the compu-

tation becomes meaningless. For example, we know that

.1C "/ ! .1 ! "/

"D 2

for any ". However, try this:

>> for n=1:100

e=1/10ˆn;

f(n)=(1+e-(1-e))/e;

f=f(:);

end

The computer soon gets it horribly wrong, yet we on the outside of the system can see what the

answer should be.

[8] Read Section 1.3: (Taylor Series) in Kharab for a good summary of this very important theorem.

[9] Read Sections 2.1 to 2.3 (Foating point arithmetic) in Kharab.

The computations that MATLAB performs are in double precision floating point arithmetic, so eachdouble data type number is encoded by a 64-bit word. The unit roundoff is approximately ı D 2 53 �1:11 � 10 16. Therefore the elementary arithmetic operations are performed to an accuracy of about 16significant decimal digits. The function eps returns the distance, ", from 1 to the next floating point number:

20

Page 26: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> eps

ans =

2.2204e-016

This is twice the unit roundoff, in other words, " D 2 � ı.The function realmax returns the largest positive number that MATLAB recognises:

>> realmax

ans =

1.7977e+308

If a computation produces a number larger than realmax then the value inf is returned. Similarly,-inf is returned if the computation produces a number smaller than -realmax. For example

>> r=realmax

r =

1.7977e+308

>> s=2*r

s =

Inf

>> t=-3*r

t =

-Inf

If a computation produces an undefined quantity then NaN is returned. For example

>> a=0/0

Warning: Divide by zero.

a =

NaN

>> b=inf/inf

b =

NaN

>> c=inf+inf

c =

Inf

Quite reasonably, if NaN is generated then all subsequent computations involving NaN return NaN. Forexample

>> a=2*0/0

Warning: Divide by zero.

a =

NaN

>> b= a+1

b =

NaN

MATLAB has many built-in functions and these all operate on matrices. For example

>> a=[ 2 pi pi/2; 3 4 -pi/4]

a =

2.0000 3.1416 1.5708

3.0000 4.0000 -0.7854

>> b=sin(a)

b =

0.9093 0.0000 1.0000

0.1411 -0.7568 -0.7071

>>help elfun produces:

21

Page 27: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

Elementary Math Functions

Trigonometric.

sin - Sine.

sinh - Hyperbolic sine.

asin - Inverse sine.

asinh - Inverse hyperbolic sine.

cos - Cosine.

cosh - Hyperbolic cosine.

acos - Inverse cosine.

acosh - Inverse hyperbolic cosine.

tan - Tangent.

tanh - Hyperbolic tangent.

atan - Inverse tangent.

atan2 - Four quadrant inverse tangent.

atanh - Inverse hyperbolic tangent.

sec - Secant.

sech - Hyperbolic secant.

asec - Inverse secant.

asech - Inverse hyperbolic secant.

csc - Cosecant.

csch - Hyperbolic cosecant.

acsc - Inverse cosecant.

acsch - Inverse hyperbolic cosecant.

cot - Cotangent.

coth - Hyperbolic cotangent.

acot - Inverse cotangent.

acoth - Inverse hyperbolic cotangent.

Exponential.

exp - Exponential.

log - Natural logarithm.

log10 - Common (base 10) logarithm.

log2 - Base 2 logarithm and dissect floating point number.

pow2 - Base 2 power and scale floating point number.

sqrt - Square root.

nextpow2 - Next higher power of 2.

Complex.

abs - Absolute value.

angle - Phase angle.

complex - Construct complex data from real and imaginary parts.

conj - Complex conjugate.

imag - Complex imaginary part.

real - Complex real part.

unwrap - Unwrap phase angle.

isreal - True for real array.

cplxpair - Sort numbers into complex conjugate pairs.

Rounding and remainder.

fix - Round towards zero.

floor - Round towards minus infinity.

ceil - Round towards plus infinity.

round - Round towards nearest integer.

mod - Modulus (signed remainder after division).

rem - Remainder after division.

sign - Signum.

22

Page 28: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

For a complete list of available functions, go to the MATLAB Help Window (Finding Functions and

Properties, MATLAB Functions Listed by Category - browse MATLAB functions by category) and find:

All the standard mathematical functions, and many more, are there.The arithmetic functions: floor, ceil, fix, round, sign, re, abs, mod are very useful. To

illustrate how these functions work, form the matrix m:

m =

1.2000 2.5000 3.6000 3.1416 7.0000

-1.2000 -2.5000 -3.6000 -3.1416 -7.0000

>> mf=fix(m)

mf =

1 2 3 3 7

-1 -2 -3 -3 -7

So fix round towards zero.

>> mr=round(m)

mr =

1 3 4 3 7

-1 -3 -4 -3 -7

So round rounds (up or down) towards the nearest integer.

>> mfl=floor(m)

mfl =

1 2 3 3 7

-2 -3 -4 -4 -7

So floor rounds towards!1.

>> mc=ceil(m)

mc =

2 3 4 4 7

-1 -2 -3 -3 -7

So ceil rounds towardsC1.

Generating Lists

If you have the stomach for it, enter:

>> help colon

23

Page 29: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

to find out about the colon operator. It is a handy device for entering lists. Try:

m=3:2:11

and you get a list, starting with 3, with elements increasing by 2 each time until the last element is reached.

>> m=3:2:11

m =

3 5 7 9 11

Actually, if the last element can not be attained, MATLAB does the most reasonable thing.Specifically, if d > 0 then

a:d:b =[a, a+d, ..., max{k: k-a is divisible by d}]

Try:

>> n=3:2:10

n =

3 5 7 9

Try

>> 5:-.5:3.2

ans =

5.0000 4.5000 4.0000 3.5000

The default increment is 1, so

>> x=3:7

x =

3 4 5 6 7

without having to specify the increment.The function: linspace, also produces lists with ease. Enter

>> linspace(0,1,5)

ans =

0 0.2500 0.5000 0.7500 1.0000

So linspace(a,b,n) produces a list with n elements starting with a and ending with b. Try:

>>linspace(0,1,11)

>>linspace(1,0,11)

>>linspace(0,1,10)

>>linspace(0,10,11)

Generating Matrices

Some special matrices are easily constructed using eye, ones, zeros as follows.

>> I=eye(3)

I =

1 0 0

0 1 0

0 0 1

constructs the 3 � 3 identity matrix.

>> Z=zeros(3,6)

Z =

0 0 0 0 0 0

0 0 0 0 0 0

0 0 0 0 0 0

24

Page 30: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

constructs a 3 � 6 matrix of zeros.

>> W=ones(3,5)

W =

1 1 1 1 1

1 1 1 1 1

1 1 1 1 1

constructs a 3 � 5 matrix of ones.

>> D=diag([1 2 3])

D =

1 0 0

0 2 0

0 0 3

constructs a diagonal matrix with specified diagonal elements.

>> DS=diag([1 2 3],1)

DS =

0 1 0 0

0 0 2 0

0 0 0 3

0 0 0 0

constructs a matrix with specified elements 1 up from the main diagonal. Consult the help on: eye, ones,

zeros, diag.The function: size returns the size of a matrix. For example

>> A=diag([2 2 2],3)

A =

0 0 0 2 0 0

0 0 0 0 2 0

0 0 0 0 0 2

0 0 0 0 0 0

0 0 0 0 0 0

0 0 0 0 0 0

>> s=size(A)

s =

6 6

since A is a 6 � 6 matrix. Look up

>>help size.

While you are at it, look up

>>help length

to see the documentation on the function which returns the length of a vector or the length of the largestdimension of a matrix. Try:

>> d=ones(size(A))

d =

1 1 1 1 1 1

1 1 1 1 1 1

1 1 1 1 1 1

1 1 1 1 1 1

1 1 1 1 1 1

1 1 1 1 1 1

25

Page 31: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

Generating Random Matrices

The MATLAB function rand produces pseudo-random matrices. Look up

>> help rand

Its usage is illustrated by the following examples.

>> r=rand(3)

r =

0.9501 0.4860 0.4565

0.2311 0.8913 0.0185

0.6068 0.7621 0.8214

is a 3 � 3 matrix of random numbers which are uniformly distributed in the interval Œ0; 1/. More generally,

rand(m,n) is an m � n matrix of numbers unifromly distributed in the interval Œ0; 1/.

For example:

>> s=rand(2,3)

s =

0.4447 0.7919 0.7382

0.6154 0.9218 0.1763

>> h=100*rand(2,4)

h =

40.5706 91.6904 89.3650 35.2868

93.5470 41.0270 5.7891 81.3166

>> f=floor(100*rand(2,5))

f =

0 20 60 19 74

13 19 27 1 44

>> x=fix(100*rand(2,5))

x =

93 41 52 67 1

46 84 20 83 68

>> u=-.5+rand(2,5)

u =

-0.1205 0.0028 -0.0711 -0.3103 0.1822

0.3318 0.2095 -0.1954 -0.3066 -0.1972

In u, the numbers are distributed in the interval Œ!:5; :5/. To generate a 2� 6 matrix whose elements arerandomly distributed in the interval Œ!1; 1/:

>> m=2*(-.5+rand(3,6))

m =

0.0833 -0.2433 0.1871 0.6433 0.3205 -0.3176

-0.6983 0.7200 -0.0069 0.2898 -0.3161 0.0682

0.3958 0.7073 0.7995 0.6359 -0.4205 0.4542

We will discuss pseudo-random numbers in some detail later. For the moment, suffice it to say that the

numbers are generated by a function. So they are not random at all. However the values of the function

wander all over the place and so they seem to vary randomly. Later, we will make our own random number

generator as well as write a program that generates true random numbers.MATLAB generates random permutations using the function randperm and it generates all permuta-

tions of the numbers [m:n] with the function perm. Try

>> randperm(5)

ans =

2 4 3 5 1

26

Page 32: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> perms(2:4)

ans =

4 3 2

4 2 3

3 4 2

3 2 4

2 3 4

2 4 3

Each successive application of randperm(n) produces a different random permutation of 1 � � �n.

Addressing Parts of a Matrix

If A is an m � n matrix, i; j are positive integers with i � m; j � n and I � Œ1 W m�; J � Œ1 W n� then:

� A.i; j / is the element in row i and column j ;

� A.W; j / is the column j ;

� A.i; W/ is the row i ;

� A.I; J / is the submatrix with elements from rows I and columns J ;

� A.W/ lists, as a single column, all the elements of A, columnwise.

For example:

>> A=floor(10*rand(5,8))

A =

0 2 0 4 8 5 1 6

3 1 7 8 0 7 6 3

8 6 4 5 6 4 3 8

0 2 9 2 3 3 5 8

1 1 4 6 8 1 1 5

>> A(2,4)

ans =

8

>> A(:, 2)

ans =

2

1

6

2

1

>> A(3,:)

ans =

8 6 4 5 6 4 3 8

>> A([2 3 4],[4 6])

ans =

8 7

5 4

2 3

Let

27

Page 33: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> M=[1 2 3; 4 5 6]

M =

1 2 3

4 5 6

>> L=M(:)

L =

1

4

2

5

3

6

As a general rule, MATLAB operates columnwise, down column 1, then down column 2 and so on to

the last column.

This is seen in other MATLAB functions such as max and min.Type

>> help max

MAX Largest component.

For vectors, MAX(X) is the largest element in X.So:

>> x=round(10*rand(1,7))

x =

7 6 8 10 5 9 2

>> m=max(x)

m =

10

For matrices, MAX(X) is a row vector containing the maximum from each column.For example, let

>> A=round(100*rand(4,7))

A =

98 74 20 47 42 23 64

27 14 30 6 52 58 21

25 1 66 99 33 76 38

88 89 28 58 43 53 78

>> m=max(A)

m =

98 89 66 99 52 76 78

MATLAB has searched down successive columns for the maximum in each column and listed eachmaximum element in a row vector. Also:

>> [v i]=max(A)

v =

98 89 66 99 52 76 78

i =

1 4 3 3 2 3 4

lists the maximum in each column as well as the index in the column where the maximum occurs.If we wanted the maximum element in the whole of the matrix A we need to find the maximum in the

list m:

>> maxA=max(m)

maxA =

99

28

Page 34: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

Alternatively:

>> MA=max(A(:))

MA =

99

does the same thing.

See also MIN, MEDIAN, MEAN, SORT.

Products and Sums

Let

>> A=round(10*rand(4,6))

A =

7 6 9 2 2 2

7 1 3 8 0 8

7 5 3 9 1 2

5 7 9 2 6 2

Now the prod function acts like this:

>> p=prod(A)

p =

1715 210 729 288 0 64

is a vector which lists, in typical MATLAB fashion, the products of the elements in each column. If thematrix is just a vector then it forms the product of the elements.

>> A=round(10*rand(1,6))

A =

10 4 3 3 4 4

>> p=prod(A)

p =

5760

The sum function also acts columnwise:

>> A=round(10*rand(4,6))

A =

6 9 9 7 8 7

1 9 2 9 4 3

0 3 6 0 9 2

5 2 10 1 7 2

>> s=sum(A)

s =

12 23 27 17 28 14

Here s is a list of the sums of the columns of A. If the matrix is a vector then the sum of the elements isreturned.

>> A=round(10*rand(1,6))

A =

2 4 9 5 8 5

>> s=sum(A)

s =

33

The functions: cumsum and cumprod produce the cumulative sum and cumulative product of vectors.As always, type >>help cumsum and >> help cumprod to read the documentation on these functions. Tosee how they work:

29

Page 35: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> M=round(10*rand(1,5))

M =

10 6 6 3 8

>> cs1=cumsum(M)

cs1 =

10 16 22 25 33

It forms the cumulative sum of the vector M . Now try a matrix.

>> M=round(10*rand(4,5))

M =

3 2 9 8 8

3 9 10 4 6

2 5 3 4 0

1 3 1 4 4

>> cs2=cumsum(M)

cs2 =

3 2 9 8 8

6 11 19 12 14

8 16 22 16 14

9 19 23 20 18

It forms cumulative sums down the columns of the matrix.Experiment with cumprod similarly. MATLAB also has function dot which produces the dot product

and the function cross, which produces the cross product of vectors. Try them out:

>> x=[-1 2 3 4];

>> y=[2 -1 pi .2];

>> d=dot(x,y)

d =

6.2248

>> x=[-1 2 3];

>> y=[2 -1 pi ];

>> c=cross(x,y)

c =

9.2832 9.1416 -3.0000

>>

Other useful functions are:

unique, diff, setdiff, union, intersect, ismember, setxor.

Consult the help files on each of these and experiment with their usage. For example, let

x=[1 2 3 4 5 5] and y=[3:8] and form diff(x), unique(x), setdiff(x,y), union(x,y), in-

tersect(x,y), ismember(x,y), setxor(x,y).

Augmenting Matrices

Let

>> M=[3 6; 7 9]

M =

3 6

7 9

Suppose that we want to replace the variable M by a new matrix with the old M in the first two rowsand 2 �M in the next two rows.

>> M=[M;2*M]

M =

30

Page 36: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

3 6

7 9

6 12

14 18

does the trick.Similarly, let:

>> A=[ 5 7; 4 6]

A =

5 7

4 6

To form a matrix, B with A in the first two columns and A in the next two columns:

>> B=[A A]

B =

5 7 5 7

4 6 4 6

Let:

>> B=[B;3*B]

B =

5 7 5 7

4 6 4 6

15 21 15 21

12 18 12 18

The matrix B has been augmented by 3 � B in the next two rows. The command

>>E=[]

assigns the empty matrix to the variable E. This is actually useful, as we shall see. When some successive

computation is being performed we can harvest the first result into the empty matrix and keep augmenting

the matrix by successive results.

As an application, suppose a population starts at 1000 and increases by 5% per year and is culled by 10

individuals each year-end. Suppose we want to keep a record of the populations at year-end.Here is one way of proceeding. Initiate a matrix to hold the year and year-end population.

>> v=[]

v =

[]

Initially we have:

>> y=0

y =

0

>> p=1000

p =

1000

Put these into v:

>> v=[v;y p]

v =

0 1000

Calculate the new values:

31

Page 37: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> p=1.05*p-10

p =

1040

>> y=y+1

y =

1

Augment v:

>> v=[v;y p]

v =

0 1000

1 1040

Carry on like this, using smart recall:

>> y=y+1

y =

2

>> p=1.05*p-10

p =

1082

>> v=[v;y p]

v =

0 1000

1 1040

2 1082

>> y=y+1

y =

3

>> p=1.05*p-10

p =

1.1261e+003

>> v=[v;y p]

v =

1.0e+003 *

0 1.0000

0.0010 1.0400

0.0020 1.0820

0.0030 1.1261

MATLAB has automatically switched to exponential format since the numbers are getting large.

Reshaping and Replicating Matrices

The reshape function changes the dimensions of a matrix. To see this in action, let:

>> A=round(100*rand(4,8))

A =

68 6 30 97 50 96 27 21

46 60 87 99 21 73 44 84

57 5 2 79 64 41 93 63

79 42 77 44 32 74 68 13

Now reshape the matrix to produce another matrix, this time of size 8 � 4, with the same elements.

>> R=reshape(A,8,4)

32

Page 38: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

R =

68 30 50 27

46 87 21 44

57 2 64 93

79 77 32 68

6 97 96 21

60 99 73 84

5 79 41 63

42 44 74 13

MATLAB has poured the 32 elements of A, columnwise (as usual for MATLAB operations) into the

matrix R. Of course, for this to be possible, if size(A)=[m n] and size(R)=[m’ n’] then we must have

m*n=m’*n’.Let:

>> B=round(100*rand(2,3))

B =

21 63 58

61 37 45

To replicate B 3 � 4 times:

>> C=repmat(B,3,4)

C =

21 63 58 21 63 58 21 63 58 21 63 58

61 37 45 61 37 45 61 37 45 61 37 45

21 63 58 21 63 58 21 63 58 21 63 58

61 37 45 61 37 45 61 37 45 61 37 45

21 63 58 21 63 58 21 63 58 21 63 58

61 37 45 61 37 45 61 37 45 61 37 45

which is the block matrix:

B B B B

B B B B

B B B B

The sort function also operates columnwise:

>> A=round(10*rand(5,6))

A =

5 6 8 7 7 1

9 7 4 5 10 7

3 4 4 8 8 4

7 4 6 5 7 1

4 7 6 2 5 6

>> Sa=sort(A)

Sa =

3 4 4 2 5 1

4 4 4 5 7 1

5 6 6 5 7 4

7 7 6 7 8 6

9 7 8 8 10 7

The columns of the matrix have been sorted in ascending order. We sort in descending order using thetrick:

>> Sd=-sort(-A)

Sd =

33

Page 39: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

9 7 8 8 10 7

7 7 6 7 8 6

5 6 6 5 7 4

4 4 4 5 7 1

3 4 4 2 5 1

Look up the functions: flipud , fliplr, rot90.Let

>>A=[3 4 5; 6 7 8]

and try out

>>flipud(A)

>>fliplr(A)

>>rot90(A)

The Kronecker product, kron.A; B/ of two matrices A and B is defined by

kron.A; B/.i; j / D A.i; j /B:

So if size.A/ D Œm1; n1� and size.B/ D Œm2; n2� then size.kron.A; B// D Œm1m2; n1n2�. For example

>> A=[1 2; 3 4]

A =

1 2

3 4

>> B=[3 4 5; 6 7 8]

B =

3 4 5

6 7 8

>> k=kron(A,B)

k =

3 4 5 6 8 10

6 7 8 12 14 16

9 12 15 12 16 20

18 21 24 24 28 32

Roughly speaking kron.A; B/ forms copies of B multiplied by the components of A. Can you see how

to use the Kronecker product, kron to replace the use of the function repmat?

Higher-dimensional Arrays

So far, we have worked with two-dimensional arrays, which have a row dimension and a column dimension.

So ordinary matrices are 2-dimensional arrays. We define a book of matrices by defining each page to be a

(2-dimensional) matrix. The page dimension is the third parameter. If for each k , Mk is a (2-dimensional)

matrix then

M.W; W; k/ DMk

defines a 3-dimensional array, M , whose k th page is Mk . For example

>> M=[1+i 1;2 1-i];

>> N=[2-i 3; 4+i 5];

>> B(:,:,1)=M;

>> B(:,:,2)=N;

So the book, B, is a 3-dimensional complex-valued array whose first page is M and whose second pageis N . To see the pages of B:

34

Page 40: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> B

B(:,:,1) =

1.0000 + 1.0000i 1.0000

2.0000 1.0000 - 1.0000i

B(:,:,2) =

2.0000 - 1.0000i 3.0000

4.0000 + 1.0000i 5.0000

In general, MATLAB assumes that all variables are higher dimensional complex-valued arrays.

A book can be one of many on a shelf. For example, let us define a shelf, S whose first book is B and

whose second book is 2 �B.

>> S(:,:,:,1)=B;

>> S(:,:,:,2)=2*B;

To see the shelf:

>> S

S(:,:,1,1) =

1.0000 + 1.0000i 1.0000

2.0000 1.0000 - 1.0000i

S(:,:,2,1) =

2.0000 - 1.0000i 3.0000

4.0000 + 1.0000i 5.0000

S(:,:,1,2) =

2.0000 + 2.0000i 2.0000

4.0000 2.0000 - 2.0000i

S(:,:,2,2) =

4.0000 - 2.0000i 6.0000

8.0000 + 2.0000i 10.0000

1.4.5 Exercise

[1] Let

a D�

1 2 3 4

5 6 7 8

; b D�

1 3 5 7�

:

Wrtite the MATLAB commands which produce the matrices:

A D

2

4

1 2 3 4

5 6 7 8

1 3 5 7

3

5 ; B D

2

6

6

4

1 2 3 4

5 6 7 8

1 3 5 7

1 4 9 16

3

7

7

5

; C D

2

6

6

4

2 3 4 5

6 7 8 9

0 2 4 6

2 5 10 17

3

7

7

5

[2] Suppose that we intend to generate a vector v of length n whose k th element, vk , is defined by some

function, say vk D k2. This can be done by creating each element vk “on the fly” even though the

variable v does not exist. Try this with:

>>clear

Now there are no variables in the workspace. With the loop:

for k=1:5

v(k)=kˆ2;

end

v

35

Page 41: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

MATLAB creates one and automatically adds in the components as they come. This is computation-

ally less efficient than defining v first with

v=zeros(1,n)

and then adjusting the components with the above loop. For small programs, this loss of efficiency isnot a problem and creating variables on the fly makes life easy. MATLAB allows us to often avoidthe use of loops with vectorised commands. For example

v=[1:5].ˆ2

does the same job as the above loop.

(a) Use linspace and the colon operator to produce the vectors:

Œ!1;!:8;!:6; � � � ; 1�

Œ10; 8; 6; � � � ; 0�

Œ3; 3:3; 3:6; � � � ; 4:8�

Œ!�;!� C �

10; � � � ; ��

(b) Use a loop to produce the vectors of length 10:

Œ1; 8; 27; � � � ; 1000�IŒ!1; 1;!1; � � � ; 1�I�

1;1

2; � � � ; 1

10

I

Œ1;p

2; � � � ;p

10�I

(c) Produce the above vectors using vectorised commands.

[3] Write the MATLAB commands which produce

(a) a column of values of sin x for integers ranging from 1 to 100;

(b) a 10 � 6 matrix of random integers n with 0 � n � 100;

(c) a 2 � 4 matrix of random integers n with 50 � n � 100;

(d) a 3 � 3 matrix of random integers n with !10 � n � 10;

(e) a 5 � 7 matrix of random integers n with !10 � n � 100.

[4] Use MATLAB to compute

(a) 3C 5C � � � C 2013;

(b) 35!;

(c) 2 � 4 � � � � � 20;

(d) 25 C 210 C � � � C 250;

(e) 1C 12C 1

4C � � � C 1

1024

[5] Let

M D

2

4

3 5 7 9 11

2 4 6 8 10

7 5 9 3 11

3

5 :

Produce a matrix whose elements are

36

Page 42: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

� the log of the squares of the elements of M ;

� the cosines of the reciprocals of the elements of M ;

� the square root of the reciprocals of the elements of M .

[6] Let

N D�

1 0

!1 1

:

Repeatedly replace N by N 2 and deduce the value of N k for any k .

Now try this with

N D

2

4

1 0 0

!1 1 0

1 0 1

3

5 :

[7] Let

>> x=[2 1 3 1 7 3 4];

>> y=[2 5 4 8 9 2 5];

Supply the MATLAB functions which produces the following:

x1 =

1 1 2 3 3 4 7

x2 =

7 4 3 3 2 1 1

x3 =

1 2 3 4 7

y1 =

2 4 5 8 9

U =

1 2 3 4 5 7 8 9

I =

2 4

D =

1 3 7

[8] Let

>> A=[ 2 1 3 1 4 6 5; 4 6 8 1 2 4 7; 0 3 1 0 4 7 3]

A =

2 1 3 1 4 6 5

4 6 8 1 2 4 7

0 3 1 0 4 7 3

Supply the MATLAB functions which produce:

A1 =

2 1 3 1 4 6 5

6 7 11 2 6 10 12

6 10 12 2 10 17 15

A2 =

2 1 3 1 4 6 5

8 6 24 1 8 24 35

0 18 24 0 32 168 105

37

Page 43: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

[9] Let R be the rotation matrix:�

cos � ! sin �

sin � cos �

:

Choose � D �3

say, and produce a multidimensional array, M , with 8 pages whose k th page contains

Rk 1.

38

Page 44: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Chapter 2

MATLAB Scripts

2.1 Simple Scripts

We saw how MATLAB could be used as a calculator. Previously executed commands were recovered using

smart recall and a sequence of operations could be performed. This is OK for a short sequence of commands

but when many calculations are required we write a program. A MATLAB program is a text file, called

a script file or an m-file, with file extension: .m, which contains the commands that are to be executed.

These can be composed in any text editor and saved in ASCII format. MATLAB comes with a very useful

program composer and debugging facility which automatically indents at the appropriate places and warns

of syntax errors as you type. Let us use the following example to illustrate the process.

2.1.1 Example

Write a program which prompts for a positive integer, n and computes n!.

First decide on a name for this program. MATLAB has many hundreds of its own m-files and functions

and it is important to assign a name which differs from these. If we want to use the name: factorial.m

we must check that this name is not already taken. To do this type

>> help factorial

FACTORIAL Factorial function.

FACTORIAL(N) is the product of all the integers from 1 to N, i.e. prod(1:N).

Since double precision numbers only have about 15 digits, the answer is only

accurate for N <= 21. For larger N, the answer will have the right magnitude,

and is accurate for the first 15 digits.

See also PROD.

To see the path to this function, use which:

>> which factorial

C:\MATLAB6p1\toolbox\matlab\specfun\factorial.m

To see all scripts withthis name use which factoral - all. So this function already exists and itone of the special functions. No matter, let’s make our own and call it fact1.m. Check:

>>help fact1

fact1.m not found.

We can proceed. Open the debugging window using the file button at the top left of the command

window. Click this and then click: new and then m-file.

39

Page 45: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

This sequence of windows operations is usually described in the form: filennewnm-file Alterna-tively, in the command window, type:

>>edit

and the debugging window appears.

Create a folder: L:nmfiles. Save this empty file right away as fact1.m in your folder

L:nmfiles . This is achieved using filenSave As in the debugging window. So save the file as

L:nmfilesnfact1.mThe first line of any program should contain comments which supply the name and usage of the program.

Any text in the body of the debugging window appearing after a % character is not read. So the % characterallows us to write comments to the user. So the first lines of our program should be something like:

%fact1.m

%Usage: Solicits n and then computes and displays n!

%

The program is going to, ask the user for a positive integer, n, compute n! and then display the answer.We obtain the input, n, from the user with a line of form:

n = input(’n = ’);

Type:

>>help input

INPUT Prompt for user input.

R = INPUT(’How many apples’) gives the user the prompt in the text string and

then waits for input from the keyboard. The input can be any MATLAB expression,

which is evaluated, using the variables in the current workspace, and the result

returned in R. If the user presses the return key without entering anything,

INPUT returns an empty matrix.

R = INPUT(’What is your name’,’s’) gives the prompt in the text string and waits

for character string input. The typed input is not evaluated; the characters are

simply returned as a MATLAB string.

The text string for the prompt may contain one or more ’\n’. The ’\n’ means skip

to the beginning of the next line. This allows the prompt string to span several

lines. To output just a ’\’ use ’\\’.

See also KEYBOARD.

40

Page 46: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

One method of computing n! is to form a temporary variable, p, say, which starts off as 1 and is thensuccessively multiplied by the numbers: 1 W n. We achieve this with a for-loop, which repeats calculationsfor a variable which ranges through a specified vector.

>>help for

FOR Repeat statements a specific number of times.

The general form of a FOR statement is:

FOR variable = expr, statement, ..., statement END

The columns of the expression are stored one at a time in the variable and

then the following statements, up to the END, are executed. The expression is

often of the form X:Y, in which case its columns are simply scalars.

Some examples (assume N has already been assigned a value).

FOR I = 1:N,

FOR J = 1:N,

A(I,J) = 1/(I+J-1);

END

END

FOR S = 1.0: -0.1: 0.0, END steps S with increments of -0.1

FOR E = EYE(N), ... END sets E to the unit N-vectors.

Long loops are more memory efficient when the colon expression appears in

the FOR statement since the index vector is never created.

The BREAK statement can be used to terminate the loop prematurely.

See also IF, WHILE, SWITCH, BREAK, END.

Here is a program that does this:

%fact1.m

%usage: solicits n and displays n!

%

n=input(’n = ’);

p=1;

for k=1:n

p=p*k;

end

p

We have got the program to display the resulting product in the crudest possible way by simply includingthe line:

p

Save the program and then add its location to the MATLAB search path. This is achieved with

>>addpath L:\mfiles

Check that this has been done by typing

>>path

and the MATLAB search path is displayed and L:nmfiles should be there.At the command window type:

>>fact1

n = 2

41

Page 47: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

p =

2

>> fact1

n = 3

p =

6

>> fact1

n = 4

p =

24

>> fact1

n = 5

p =

120

Yes! Our program is working. As proud as we may be, this program has many faults. To see some ofthem type:

>>fact1

n = 3.45

p =

6

>> fact1

n = -3

p =

1

>> fact1

n = [3 4; 5 6]

p =

6

The program finds 3.45! to be 6. The reason is easy to discover. We set the variable, p, to be 1 andthen formed, p D p � 1; p D p � 2; p D p � 3 until we reached n. Iterations of a command are performedas a variable, k , in this case, varies through a specified vector (Œ1 W n� in this case). If n is not an integer,MATLAB stops the iteration when floor(n) is reached. To see how the programs iterates through theloop, type

>> edit fact1

The program appears. Go to the line

p=1;

and set a breakpoint there using the button with a red dot. A red dot appears at the beginning of this line.

Now go back to the command window and run fact1.m again. The program stops when it reaches the

breakpoint. Now click the Single-Step button and watch the program perform the iterations. As it does so,

you can see the values of a variable by positioning the mouse pointer over it (without pressing a mouse

button). The value appears in a yellow box. When you have finished, click the button for continue, which

allows the program to finish its iterations. Now click the Clear All Breakpoints button.

42

Page 48: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

Another handy method of investigating a script in operation is to use the keyboard command. When

this command is inserted in a script, the execution of the script is suspended and control is returned to the

keyboard. You can then, in the command window, type in the names of variables to see them and perform

calculations with them. When you have finished, type return and the script resumes.

Our program also happily supplies the factorial of a negative number and of a matrix. We really should

prevent the user from entering any value but a positive integer and so we shall, a little later.Continuing with the critical appraisal of our very first program, it must be said that just outputting the

answer without comment is a bit crude. We get it to display, using the disp function. Something like:

disp(’The answer is:’)

disp(p)

will produce:

>> fact1

n = 5

The answer is:

120

when then program is run.If you really want to control how the output is presented, use the fprintf function. This prints format-

ted data to file and the usual usage is:

fprintf(’format string \n’,out)

Out is a matrix of values to be displayed or printed to a file. The format string is a string which

determines how the output is to be displayed. Within the format statement, values from the output matrix,

out, are inserted at places indicated by a % character. The nn character forces a skip to a new line.See

>> help fprintf

To see how fprintf works, go to the command window. Type:

>> out=[2 ; 3.14];

>> fprintf(’The value of pi to %d places is %f \n’,out)

The value of pi to 2 places is 3.140000

Here %d and %f are place holders in the format string where values from the output matrix, out, are to

appear.The character %d specifies that a digit (integer) is to be placed there. The character

43

Page 49: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

%d display value as an integer

%e display value in exponential format

%f display value in floating point format

%g display value in general format: %f or %e, whichever is shorter.

\n skip to a new line after printing

\t set a tab

Suppose that we have written a program that has calculated the values of � , correct to k places, fork D 0 W 5. The output values are stored in a matrix: out

>> out=[ 0 1 2 3 4 5; 3 3.1 3.14 3.142 3.1416 3.14159]

out =

0 1.0000 2.0000 3.0000 4.0000 5.0000

3.0000 3.1000 3.1400 3.1420 3.1416 3.1416

Columnwise Functions

MATLAB will read down column 1, printing the values that it encounters in the places specified by %

characters, in the format specified. Then it will skip to a new line (if nn is included) and read down

column 2, doing the same thing. It repeats this for each column. We could say that this function operates

columnwise.Type

>> fprintf(’The value of pi to %d places is %f \n’,out)

and you get:

The value of pi to 0 places is 3.000000

The value of pi to 1 places is 3.100000

The value of pi to 2 places is 3.140000

The value of pi to 3 places is 3.142000

The value of pi to 4 places is 3.141600

The value of pi to 5 places is 3.141590

Printing Specifications

We can also specify the total number of characters occupied at each place and the number of decimal placesdisplayed. This done by:

%(width).(places)f

For example:

>>fprintf(’The value of pi to %5.0f places is %20.10f \n’,out)

The value of pi to 0 places is 3.0000000000

The value of pi to 1 places is 3.1000000000

The value of pi to 2 places is 3.1400000000

The value of pi to 3 places is 3.1420000000

The value of pi to 4 places is 3.1416000000

The value of pi to 5 places is 3.1415900000

>> fprintf(’The value of pi to %4.0f places is %20.10f \n’,out)

The value of pi to 0 places is 3.0000000000

The value of pi to 1 places is 3.1000000000

The value of pi to 2 places is 3.1400000000

The value of pi to 3 places is 3.1420000000

44

Page 50: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

The value of pi to 4 places is 3.1416000000

The value of pi to 5 places is 3.1415900000

>> fprintf(’The value of pi to %3.0f places is %20.10f \n’,out)

The value of pi to 0 places is 3.0000000000

The value of pi to 1 places is 3.1000000000

The value of pi to 2 places is 3.1400000000

The value of pi to 3 places is 3.1420000000

The value of pi to 4 places is 3.1416000000

The value of pi to 5 places is 3.1415900000

Experiment with various values in (width).(places). If the width that we specify is too small forthe number, MATLAB does the most reasonable thing and expands the space allocated to accommodate:

>>fprintf(’The value of pi to %3.0f places is %3.10f \n’,out)

The value of pi to 0 places is 3.0000000000

The value of pi to 1 places is 3.1000000000

The value of pi to 2 places is 3.1400000000

The value of pi to 3 places is 3.1420000000

The value of pi to 4 places is 3.1416000000

The value of pi to 5 places is 3.1415900000

The default format is right-justified. Left-justification is specified using:

%-(width).(places)f

For example

>>fprintf(’The value of pi to %-5.0f places is %-3.10f \n’,out)

The value of pi to 0 places is 3.0000000000

The value of pi to 1 places is 3.1000000000

The value of pi to 2 places is 3.1400000000

The value of pi to 3 places is 3.1420000000

The value of pi to 4 places is 3.1416000000

The value of pi to 5 places is 3.1415900000

See what happens when the nn character is omitted. Type:

>> fprintf(’The value of pi to %-5.0f places is %-3.10f’,out)

and see what happens.

Back to our program. Let’s use our new-found knowledge to display the output in a dignified way.

%fact1.m

%usage: solicits n and displays n!

%

n=input(’n = ’);

p=1;

for k=1:n

p=p*k;

end

out=[n;p];

fprintf(’The value of %d! is %d \n’,out)

Save this with cntrl+S and then use alt+tab until the MATLAB command window icon is displayed.Run the program again and you get:

45

Page 51: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> fact1

n = 7

The value of 7! is 5040

>> fact1

n = 20

The value of 20! is 2.432902e+018

>> fact1

n = 100

The value of 100! is 9.332622e+157

>> fact1

n = 120

The value of 120! is 6.689503e+198

>> fact1

n = 200

The value of 200! is Inf

Since 200! is greater than realmax, we have overflow and the value is given as inf.The program algorithm itself can be improved to make use of MATLAB’s ability to use vectorised

commands. Here is a typical MATLAB approach to the problem:

%fact.m

%usage: solicits n and displays n!

%

n=input(’n = ’);

p=prod(1:n);

out=[n;p];

fprintf(’The value of %d! is %d.\n’,out)

You could even compress this to

n=input(’n = ’);

fprintf(’The value of %d! is %d.\n’,n,prod(1:n))

It is clear that fact.m is simpler in structure than the others. The vectorised MATLAB programming

language is much easier to use than conventional programming languages and the need for loops is cut down

dramatically. When writing MATLAB programs, you should make use of this powerful facility to vectorise

statements. It is good programming practice to add comments to a program as you write it. This is for your

own benefit at a later stage or for some other user who wants to understand or modify your program. We

did not do this in our little factorial programs since they were our first and they were very short. However,

from now on, we will be disciplined and annotate all programs. It is also usual to include the name of the

programmer in the file.

2.1.2 Example

Write a program, called ciy, that prompts for an initial deposit, d , annual interest rate, i , and number, n, of

years and then computes the final value, v, after n years with interest accruing at the end of each year.

%ciy.m

%Mike Burton 2004

echo on

%computes the final value after n years, interest accruing at year-end

%prompts for: d=initial deposit; i=yearly percentage interest; n=number of years;

%displays the value after n years

%

echo off

disp(’________________________________________’)

46

Page 52: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

d=input(’initial deposit = ’);

i=input(’yearly percentage interest = ’);

n=input(’number of years = ’);

%set the value v to the initial deposit

v=d;

%set r as the growth rate

r=i/100;

%compute the year-end values recursively

for k=1:n

v=(1+r)*v;

end

%print

out=[n;v];

fprintf(’final value after %1.0f years = %-10.2f\n’,out)

Note the cheap way, employing:

echo on

echo off

of getting the information about the program to display to the user.

Here is the dialogue when the program is run:

initial deposit = 1000

yearly percentage interest = 12

number of years = 5

final value after 5 years = 1762.34

2.1.3 Example

Modify the above program to display the initial deposit and the values at each year end.

Here we use the device of first initiating a vector, v, of the right length to contain the values. We then

compute successive values of v(k).

%ciyall.m

%Mike Burton 2004

%computes the final value after n years, interest accruing at year-end

%prompts for input:

%d=input(’initial deposit = ’);

%i=input(’yearly percentage interest = ’);

%n=input(’number of years = ’);

%displays the value after n years

%

d=input(’initial deposit = ’);

i=input(’yearly percentage interest = ’);

n=input(’number of years = ’);

%initiate a vector whose elements are the year-end values

%and initial deposit

v=zeros(1,n+1);

%set first value

v(1)=d;

47

Page 53: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

%set r as the growth rate

r=i/100;

%compute the year-end values recursively

for k=2:n+1

v(k)=(1+r)*v(k-1);

end

%y=list of years

y=[0:n];

%print: MATLAB prints down the columns of the matrix named: out

out=[y; v];

fprintf(’value at year %-4.0f is %-8.2f\n’,out)

Running the program:

>> ciyall

initial deposit = 1000

yearly percentage interest = 12

number of years = 5

value at year 0 is 1000.00

value at year 1 is 1120.00

value at year 2 is 1254.40

value at year 3 is 1404.93

value at year 4 is 1573.52

value at year 5 is 1762.34

2.2 A Note on Recursively Defined Functions

We will often need to form a list of values of indeterminate length and there are a number of ways of doing

this. Say, for example, we want to generate the Famous Fibonacci sequence, f , whose first two terms are

1; 1 and subsequent terms are obtained from the rule :

f .n/ D f .n ! 1/C f .n ! 2/:

This is a linear recurrence relation with constant coefficients and it is possible to find a closed-form

solution. However, for most recurrence relations, a closed-form solution is difficult or even impossible to

obtain. If we are interested in finding the values of the function rather than an expression for the function

itself, we can use the computer to generate them.In the command window, let

>> f=[1 1 ]

f =

1 1

Here is how we generate the new value from the old ones using f(end) :

Method 1

>> fnew=f(end)+f(end-1)

fnew =

2

Now augment the list f:

48

Page 54: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> f=[f fnew]

f =

1 1 2

Repeat this procedure:

>> fnew=f(end)+f(end-1)

fnew =

3

>> f=[f fnew]

f =

1 1 2 3

>> fnew=f(end)+f(end-1)

fnew =

5

>> f=[f fnew]

f =

1 1 2 3 5

Method 2

Again, to start off, let

>> f=[1 1]

f =

1 1

Set the index in the sequence:

>> k=3

k =

3

Generate the next term of the sequence:

>> f(k)=f(k-1)+f(k-2)

f =

1 1 2

Note that the sequence has automatically been lengthened to accommodate the extra term. Increase the

index and generate the next term:

>> k=k+1

k =

4

>> f(k)=f(k-1)+f(k-2)

f =

1 1 2 3

Repeat this procedure:

>> k=k+1

k =

5

>> f(k)=f(k-1)+f(k-2)

f =

1 1 2 3 5

49

Page 55: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

Method 3

We can use a for-loop to generate the terms.

>> f=[1 1];

>> for k=3:6

f(k)=f(k-1)+f(k-2);

end

>> f

f =

1 1 2 3 5 8

Vectorisation

Suppose that we want to write a script which prompts for a natural number, n, and then computes

Sn Dn

X

kD1

1

k

Those with some programming experience might immediately think in terms of making a loop whichsuccessively adds the next term to a partial sum. Something like:

%sum1

n=input(’n= ’)

s=1;

for k=2:n

s=s+1/k;

end

format rat

s

This:

� creates the variable, s

� sets s to 1 with

s D 1

� successively replaces s by s C 1k

by

s D s C 1

k

as k varies from 2 to n.

� crudely displays the final value of s.

This does the job but there is a better way:

� Form the vector v=[1:n],

� take the pointwise reciprocal of v

� and the find the sum.

%sum1

n=input(’n= ’)

v=[1:n];

v=1./v;

s=sum(v)

format rat

s

50

Page 56: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

Let us call this technique, which uses the full power of MATLAB’s matrix handling capabilities, vec-

torisation.In fact we can shorten the above script to

%sum1

n=input(’n= ’)

s=sum(1./[1:n)

format rat

s

Of course, we check it to see that it is performing the right task

n =

3

s =

11/6

Then, when we are satisfied, we use fprintf to display the sum. Note also that we have resisted the

temptation to call the scipt sum since this is the name of a MATLAB function.

2.2.1 Exercise

[1] Write a program, called temp.m which prompts for the temperature, c, in Celsius, converts it to

Fahrenheit, f , using the formula:c

5D f ! 32

9:

and displays the result. Typical output is:

20 degrees Celsius is 68 degrees Fahrenheit

[2] Modify the program, calling it vtemp.m, to accept a list of input temperatures and then display theconversions. Typical input and output are: input:

>> vtemp

Enter a list temperatures in Celsius = [ -10 23 45 67]

output:

-10.00 degrees Celsius is 14.00 degrees Fahrenheit

23.00 degrees Celsius is 73.40 degrees Fahrenheit

45.00 degrees Celsius is 113.00 degrees Fahrenheit

67.00 degrees Celsius is 152.60 degrees Fahrenheit

Think about how you can ensure that the (row or column) vector input by the user is always converted

to a row vector. Make sure that the columns of your output are straight - without kinks.

[3] Write a program, called cidep.m which prompts for:

� an initial deposit, d ;

� a fixed deposit, yd , at the end of each year except the last;

� an annual interest rate, I ;

� the number, n, of years

and then computes the final value, v, of the account if the sequence of deposits accumulates compoundinterest for the specified number of years. There is a formula for this, but use a for-loop instead.Typical input and output is: input:

51

Page 57: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> cidep

initial deposit = 1000

year end deposit = 100

yearly percentage interest = 10

number of years = 5

output:

final value after 5 years = 2121.02

[4] Modify the last program, calling it cidepall.m, to display the initial and year-end values.

[5] Write a program, called ser1.m, which asks for a positive integer, n, and then computes:

nX

kD1

k2:

[6] Write a program, called ser2.m, which asks for a positive integer, n, and then computes:

nX

kD1

.!1/k 1 1

k:

Does this series converge?

[7] Write a program, called ser3.m, which asks for a positive integer, n, and then computes:

nX

kD1

1

k2:

Does this series converge?

[8] The resistance, R, in a circuit with two resistors: R1 and R2 in parallel is obtained from:

1

RD 1

R1

C 1

R2

:

Write a program, called resist.m which prompts for a vector input ŒR1; R2� and displays the total

resistance R.

[9] The number e is given by:

e D1

X

kD0

1

k!:

Write a program, called ser4.m which prompts for a number n and then forms the .n C 1/th partial

sum:

Sn Dn

X

kD0

1

k!:

52

Page 58: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

[10] An initial deposit is made into an account which earns compound interest, which is evaluated monthly.

Write a program, called ci1.m, which prompts for the initial deposit, the interest rate and the in-

vestment period and then displays the value of the account and each month-end as well as at each

year-end. Typical input and output are:

input:

>> ci1

For an initial deposit, I, and interest compounded on a monthly basis,

the amounts at the end of each year are displayed.

____________________________________________

number of years =2

annual percentage interest rate = 10

output:

initial deposit = 1000

month: 0 value: 1000.00

month: 1 value: 1008.33

month: 2 value: 1016.74

month: 3 value: 1025.21

month: 4 value: 1033.75

month: 5 value: 1042.37

month: 6 value: 1051.05

month: 7 value: 1059.81

month: 8 value: 1068.64

month: 9 value: 1077.55

month: 10 value: 1086.53

month: 11 value: 1095.58

month: 12 value: 1104.71

month: 13 value: 1113.92

month: 14 value: 1123.20

month: 15 value: 1132.56

month: 16 value: 1142.00

month: 17 value: 1151.52

month: 18 value: 1161.11

month: 19 value: 1170.79

month: 20 value: 1180.54

month: 21 value: 1190.38

month: 22 value: 1200.30

month: 23 value: 1210.31

month: 24 value: 1220.39

_______________________________________________________

year: 0 value: 1000.00

year: 1 value: 1104.71

year: 2 value: 1220.39

________________________________________________________

The value after 2 years is 1220.39

The solutions to this exercise contain a number of important lessons. Do not look at a solution before

you have finished. When you have finished these there is another exercise, which is to be submitted.

53

Page 59: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

2.3 Solutions and Lessons from Exercise 2.2.1

%temp.m

%converts temperature from Celsius to Fahrenheit

%

c = input(’Enter a temperature in Celsius = ’);

c=c(:)’;

%calculate temperature in Fahrenheit

f = (9*c)/5 + 32;

out=[c;f];

fprintf(’%3.2f degrees Celsius is %3.2f degrees Fahrenheit\n’,out)

Note that MATLAB works with vectors and matrices as easily as with numbers. If the input, c, is a

matrix then the output, f, will be a matrix of the same size. The line

c=c(:)’;

ensures that c becomes a row. We want a row because the printing matrix, out, must have c in the first row

and f in the second.

%cidep.m

%Mike Burton 2005

%computes compound interest with regular deposits:

%prompts for input:

%d=input(’initial deposit = ’);

%yd=input(’year end deposit = ’);

%i=input(’yearly percentage interest = ’);

%n=input(’number of years = ’);

%displays the value after n years (No last deposit).

%

d=input(’initial deposit = ’);

yd=input(’year end deposit = ’);

i=input(’yearly percentage interest = ’);

n=input(’number of years = ’);

%set the value v to the initial deposit

v=d;

%set r as the growth rate

r=i/100;

%compute the values recursively

for k=1:n

v=(1+r)*v+yd;

end

%no last deposit

v=v-yd;

%print

out=[n;v];

fprintf(’final value after %1.0f years = %-10.2f\n’,out)

54

Page 60: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

%cidepall.m

%Mike Burton 2005

%See cidep.m

%promts for input:

%d=input(’initial deposit = ’);

%yd=input(’year end deposit = ’);

%i=input(’yearly percentage interest = ’);

%n=input(’number of years = ’);

%displays the year-end value for n years

%

d=input(’initial deposit = ’);

yd=input(’year end deposit = ’);

i=input(’yearly percentage interest = ’);

n=input(’number of years = ’);

v=zeros(1,n+1);

%set the value v to the initial deposit

v(1)=d;

%set r as the growth rate

r=i/100;

%compute the values recursively

for k=2:n+1

v(k)=(1+r)*v(k-1)+yd;

end

%no last deposit

v(end)=v(end)-yd;

%print

y=0:n;

out=[y;v];

fprintf(’final value after \t%-3.0f years = %-10.2f\n’,out)

Note the difference in between cidep and cidepall. In the first, the value, v, is modified a number

of times to produce the final value. In the second, v is initiated as a vector of appropriate length and the

values, v(k), are computed. Note the useful trick: v(end) which is the last value of v. We did not really

need this here, but is very handy in cases where the length of v cannot be predetermined.

echo on

%ser1

%computes: 1+2ˆ2+...nˆ2 for given n

%

echo off

n=input(’n = ’);

s=sum([1:n].ˆ2);

fprintf(’The sum of %1.0f terms is %-1.0f\n’,n,s)

A number of little lessons here. Observe the way of using

echo on

echo off

of displaying the purpose of the program to the user.

55

Page 61: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

Be Wise, Vectorise!

Take careful note of the very efficient way of finding the sum of the series with vectorised operations. Note

that we did not bother to make a print matrix, out, here. We simply put the two values to be printed where

the out matrix usually goes. It is better to have a fixed procedure, so I recommend that you form the matrix,

out, and use:

fprintf(’message with place-holders \n’, out)

You could contract your program even further to have only the input line and the print line, doing the

calculation in the fprintf function itself. For example

%ser1: compact version

n=input(’n = ’);

fprintf(’The sum of %1.0f terms is %-1.0f\n’,n,sum([1:n].ˆ2))

%ser2

%computes 1-1/2+1/3+...+(-1)ˆn*1/n

%

disp(’computes 1-1/2+1/3+...+(-1)ˆn*1/n ’);

n=input(’n = ’);

%vector of signs

v=(-1).ˆ[0:n-1];

s=sum(v.*1./[1:n]);

out=[n,s];

fprintf(’The sum of %d terms is %g \n’,out)

We check it out:

>> ser2

computes 1-1/2+1/3+...+(-1)ˆn*1/n

n = 1

The sum of 1 terms is 1

>> ser2

computes 1-1/2+1/3+...+(-1)ˆn*1/n

n = 2

The sum of 2 terms is 0.5

>> ser2

computes 1-1/2+1/3+...+(-1)ˆn*1/n

n = 3

The sum of 3 terms is 0.833333

>> ser2

computes 1-1/2+1/3+...+(-1)ˆn*1/n

n = 1000

The sum of 1000 terms is 0.692647

>>

%ser3

%computes 1+1/2ˆ2+1/3ˆ2+...+1/nˆ2

%

disp(’computes 1+1/2ˆ2+1/3ˆ2+...+1/nˆ2 ’);

n=input(’n = ’);

s=sum(1./[1:n].ˆ2);

out=[n,s];

fprintf(’The sum of %d terms is %g \n’,out)

56

Page 62: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

By simply modifying ser2, this program took ten seconds to write. It is important that you realise that

although

1C 1

2C 1

3C � � �

diverges as n increases, but

1C 1

22C 1

32C � � �

converges. Try it out:

>> ser3

computes 1+1/2ˆ2+1/3ˆ2+...+1/nˆ2

n = 10

The sum of 10 terms is 1.549767731167

>> ser3

computes 1+1/2ˆ2+1/3ˆ2+...+1/nˆ2

n = 100

The sum of 100 terms is 1.634983900185

>> ser3

computes 1+1/2ˆ2+1/3ˆ2+...+1/nˆ2

n = 1000

The sum of 1000 terms is 1.643934566682

>> ser3

computes 1+1/2ˆ2+1/3ˆ2+...+1/nˆ2

n = 10000

The sum of 10000 terms is 1.644834071848

%resist

%computes R from 1/R = 1/R1 +1/R2

%

disp(’computes R from 1/R = 1/R1 +1/R2’);

v=input(’[R1 R2] = ’);

R=1/(1/v(1) +1/v(2));

fprintf(’R is %4.4f \n’,R)

Dead easy! Here is one way of dealing with ser4.

%ser4

%computes 1 + 1/1 +1/2! +1/3! + ... +1/n! for increasing n

%

disp(’computes 1 + 1/1 +1/2! +1/3! + ... +1/n! for increasing n’);

n=input(’n = ’);

s=sum(1./[1 cumprod(1:n)]);

out=[n;s];

fprintf(’The sum to %-5.0f terms is %-1.14f \n’,out)

Here is a case where it looks as though we could not avoid using a loop. However cumprod comes to

the rescue.

A Common Error: Badly Chosen Variable Names

It is temping to use the variable name: sum instead of s, in programs which compute a sum. If you do, the

program leaves the variable sum behind in the workspace. Then when you try to use the MATLAB function

sum, you get an error message. For example

57

Page 63: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>>sum =7

>> x=1:5

x =

1 2 3 4 5

>> sum(x)

??? Index exceeds matrix dimensions.

This is because sum is now a vector and you are attempting to address the x th element, which makes no

sense.The same thing happens if you make a syntax error and write, for example,

fprintf=(’The value after %d years is %10.2f\n’,years,value)

Until you clear the variable fprintf the function with that name is unavailable and MATLAB will give

the same error message as above.

Pausing

Suppose we wanted the program to compute the nth partial sum of a series for various increasing n and

display each partial sum briefly. To do this we use the pause command within a loop. For example

%ser4a

%computes 1 + 1/1 +1/2! +1/3! + ... +1/n! for increasing n

%

disp(’computes 1 + 1/1 +1/2! +1/3! + ... +1/n! for increasing n’);

n=input(’n = ’);

s=1;

fprintf(’The sum of %-5.0f terms is %-1.14f \n’,1,1)

for k=1:n

s=sum(1./[1 cumprod(1:k)]);

out=[k+1;s];

fprintf(’The sum to %-5.0f terms is %-1.14f \n’,out)

pause(1)

end

You can also insert the lines

disp(’Strike any key to continue’)

pause

in a program to pause the execution of the program until there is some response from the user.

You can also make use of the keyboard command, which returns control to the keyboard so that vari-

ables may be investigated. When you have finished, type return for control to return to the script.

58

Page 64: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

%ci1.m

%computes compound interest, evaluated monthly

%lists monthly values and yearly values

%

format bank

clear

disp(’For an initial deposit, I, and interest compounded on a monthly basis,’)

disp(’the amounts at the end of each year are displayed.’)

disp(’____________________________________________’)

n=input(’number of years =’);

a=input(’annual percentage interest rate = ’);

I=input(’initial deposit = ’);

t=[0:12*n]’;

v=zeros(12*n+1,1);

v(1)=I;

for k=[2:n*12+1];

v(k)=v(k-1)*(1+(a/1200));

end

y=[1:12:12*n+1]’; %years among the months

yi=[1:length(y)]’; %year index

yv=zeros(length(y),1); %year values

for i=yi

yv(i)=v(12*(i-1)+1);

end

out=[t v]’;

fprintf(’month:%3.0f\t value:%10.2f\n’,out)

fprintf(’\n’)

disp(’_________________________________________________________’)

fprintf(’\n’)

aout=[(yi-1) yv]’;

fprintf(’year:%3.0f\t value:%10.2f\n’,aout)

fprintf(’\n’)

disp(’_________________________________________________________’)

fprintf(’\n’)

fprintf(’The value after %1.0f years is %-10.2f\n’,n,v(end))

59

Page 65: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

2.4 Making a Help File

Now that you have written a few programs it is a good idea to keep track of them with a Help file. Whenyou type >>help elfun, for example, MATLAB searches for the file called contents.m in the folderC:nMATLAB6p1ntoolboxnmatlabnelfun. If you make a file called contents.m in the folder L:nmfilesthen typing >>help mfiles will bring up the contents of this file. Each line must begin with a commentsymbol %. Here is an example of the first few lines of the help file: contents.m

%%%%%%%%%%%%%

%mfiles

%%%%%%%%%%%%%%

%amort.m

%Computes the monthly payments for a given deposit, interest and period

%

%annuity1.m

%computes compound interest, evaluated monthly, fixed deposits

%

%fact1.m

%Usage: solicits n and then computes and displays n!

%crude first program

%

If you type >>help mfiles then these comments, which are just the comment lines pasted in from

each program, are displayed.

%%%%%%%%%%%%

mfiles

%%%%%%%%%%%%%

amort.m

computes the monthly payments for a given deposit, interest and period

annuity1.m

computes compound interest, evaluated monthly, fixed deposits

fact1.m

Usage: solicits n and then computes and displays n!

crude first program

2.5 Data Import and export

At this stage, you need to know something about handling data. Later we can will see how to get programs

to automatically import data files, and then save data to indexed files. For now, let us be content with being

able to get a data set from an Excel sheet or a text file.

Importing from excel

Suppose that we have a data set in the form of a matrix in an Excel sheet. Select the matrix and save it to a

file on the MATLAB path. Say:

L\mfiles\datafile.xls

60

Page 66: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

This file is loaded in MATLAB by the function xlsread which reads excel files.

>> xlsread(’datafile’)

ans =

1 1

2 4

3 9

MATLAB has assigned the variable ans to the matrix, which you may now rename. Alternatively:

>> M=xlsread(’datafile’)

M =

1 1

2 4

3 9

assigns the matrix to the variable M. We could be more specific and use the path instead of just the file name:

M=xlsread(’L:\mfiles\datafile.xls’)

Alternatively, the matrix can be copied in Excel, or any other application and pasted into Notepad, or

any other text editor. Save it in Notepad as a text file, say:

L:\mfiles\datafile.txt

This file is then imported into MATLAB using the function: load or the function importdata. For exam-

ple

>> load datafile.txt

>> M=datafile

M =

1 1

2 4

3 9

Or:

>> importdata(’datafile.txt’)

ans =

1 1

2 4

3 9

61

Page 67: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

Again, the full path can be cited to avoid confusion. You can also import the matrix manually by:

� copying the highlighted matrix in Excel,

� forming an empty matrix, [ ], in MATLAB,

� dropping the data matrix into the matrix brackets.

Saving variables is achieved with the function save. Its usage is straightforward. Type

>> help save, >> help load, >>help importdata.

For example, suppose the following marks are achieved by five third-year mathematics students at

Rhodes University.

Course Marks

student Course Record Exam

1 50 60

2 45 67

3 68 78

4 78 65

5 55 53

Our task is to compute the final mark (F ), which is obtained from the Course Record (C )and exam

mark (E) by the formula:

F D 30C C 70E

100:

We import the matrix:

M D

2

6

6

6

6

4

1 50 60

2 45 67

3 68 78

4 78 65

5 55 53

3

7

7

7

7

5

into MATLAB as above and call it M .

>> M

M =

1 50 60

2 45 67

3 68 78

4 78 65

5 55 53

We compute the final mark:

>> F=.3*M(:,2)+.7*M(:,3)

F =

57.0000

60.4000

75.0000

68.9000

53.6000

Let’s round the marks to the nearest integer and augment the matrix to have the final mark in the last column:

62

Page 68: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> F=round(F)

F =

57

60

75

69

54

>> MF=[M F]

M =

1 50 60 57

2 45 67 60

3 68 78 75

4 78 65 69

5 55 53 54

We save the matrix using:

>> save L:\mfiles\coursemarks.mat MF M F

This saves the variables: M, F, MF as a MAT-file. Check:

>> clear

>> load coursemarks.mat

>> whos

Name Size Bytes Class

F 5x1 40 double array

M 5x3 120 double array

MF 5x4 160 double array

Grand total is 40 elements using 320 bytes

If the final-mark matrix, MF is needed as an ASCII file use:

>> save L:\mfiles\finalmarks.txt MF -ascii

The function wk1write exports data as a Lotus 123 worksheet which can be opened in Excel. For

example:

>> wk1write(’c:\data\mfiles\finalmarks.xls’,MF)

does the job. Type >> help iofun for further details.

2.5.1 Exercise

[1] Write a program, called ser5.m which prompts for m and computes

1 ! 1

2C 1

3! 1

4C � � � C .!1/n 1 1

n

for n D 1 W m.

Get the program to pause and display the partial sums. Note that this alternating series converges,

whereas the Harmonic series diverges.

63

Page 69: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

[2] See if you can prove that1

2!C 2

3!C 3

4!C � � � D 1:

Write a script, called ser5a which prompts for n and then computes

1

2!C 2

3!C 3

4!C � � � C n ! 1

n!:

[3] Consider the sequence whose terms are:

1C 1

2; 1C 1

2C 12

; 1C 1

2C 1

2C 12

; � � �

Write a program, called cfrac.m, which asks for the number, n, of terms and displays the terms of

the sequence up to the nth term. The sequence converges to a well-known number, can you spot it?

[4] A sequence .x1; x2; � � � ; / is generated from an initial number s > 0 by

x1 D s

x2 D 1C 1

2C s

:::

xn D 1C 1

2C xn 1

Write a script called cfrac2 which asks for n and then displays the terms up to the nth term. Can you

find the limit of the sequence?

[5] Write a program, called annuity1.m, which computes the final value, at the end of n years, of an

annuity which consists of an initial deposit and 12n monthly deposits. For example

input:

>> annuity1

Computes the value after n years of an annuity with an initial deposit

The total number of deposits is 12*n.

The annuity is reaped at the beginning of month 12*n+1.

number of years = 3

initial deposit= 1000

percentage interest rate per year= 12

deposit per month= 100

output:

month beginning: 1 value: 1000.00

month beginning: 2 value: 1110.00

month beginning: 3 value: 1221.10

etc

month beginning: 36 value: 5582.63

month beginning: 37 value: 5638.46

The final value after 3 years is 5638.46

[6] Write a program, called testmarks1.m, which accepts a list of test marks and produces the average,

minimum, maximum and standard deviation of the list. Type

64

Page 70: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>>lookfor standard

and you will see the function std available for you. Generate a list of test marks in Excel and

get the list into MATLAB. Alternatively, the file testmarks1.xls is available on the Mathematics

Department website under LINKS.

For example

>> L

L =

Columns 1 through 21

63 38 55 28 52 94 50 30 50 52 64 42 55 50 52 72 34 50 70 45 34

Columns 22 through 41

34 42 57 50 41 67 37 50 28 55 54 78 58 51 53 56 50 65 16 74

>> testmarks1

list of marks = L

min=16.00 max=94.00 average=51.12 std dev =15.09

[7] The text file: testmarks2.txt is available on the website. This contains the records of first year

students. The course record, C , is the average of the two tests and the final mark, F , is obtained from

C and the exam mark, E by the formula:

F D C C 4E

5:

Write a program, testmarks2.m that loads the text file, verifies the course record and produces the

final mark. The top line of the file is text:

Test1 Test 2 CR Exam

and this will have to be pruned off to make a text file with only numerical data.

65

Page 71: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Chapter 3

Matrix Operators

3.1 Relational Operators

We need some facility which enables us to query whether a matrix has certain properties. MATLAB has the

Relational Operators which produce logical 0, 1-matrices. These are :

Relational Operators

DD equal to

�D not equal to

< less than

<D less than or equal too

> greater than

>D greater than or equal to

To see the entire list of MATLAB operators, type:

>> help ops

If M is a matrix, � a relational operator and t is a (test) value then

M�t returns a matrix, R whose size is the size of M and such that:

R.i; j / D 1 if M.i; j /�t is true;

R.i; j / D 0 if M.i; j /�t is false.

For example, let

A =

-23 45 2 0 6 89

99 12 -34 -3 9 1

76 -6 84 2 16 74

then:

>> A==0

produces

ans =

0 0 0 1 0 0

0 0 0 0 0 0

0 0 0 0 0 0

66

Page 72: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

Here, the logical matrix ans has a 1 wherever the matrix A has a 0 and ans has zeros elsewhere. In other

wordsans.i; j / D 1 wherever A.i; j / D 0

ans.i; j / D 0 elsewhere

We could elect to give the logical matrix a name. For example

>> L=A>0

L =

0 1 1 0 1 1

1 1 0 0 1 1

1 0 1 1 1 1

We may use brackets to make things look more readable:

>> L=(A˜=2)

ans =

1 1 0 1 1 1

1 1 1 1 1 1

1 1 1 0 1 1

MATLAB has the following logical operators.

Logical Operators

& and

j or

� not

xor exclusive or

any any

all all

These can be used in conjunction with the relational operators. For example

>> A

A =

-23 45 2 0 6 89

99 12 -34 -3 9 1

76 -6 84 2 16 74

>> A>0 & A<50

ans =

0 1 1 0 1 0

0 1 0 0 1 1

0 0 0 1 1 0

>> A>-20 | A==20

ans =

0 1 1 1 1 1

1 1 0 1 1 1

1 1 1 1 1 1

67

Page 73: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> ˜(A>-20|A==20)

ans =

1 0 0 0 0 0

0 0 1 0 0 0

0 0 0 0 0 0

The operators: all and any again conform to the MATLAB principle of working columnwise. Type

>> help all

>> help any

Let’s try them out:

>> A

A =

-23 45 2 0 6 89

99 12 -34 -3 9 1

76 -6 84 2 16 74

>> all(A>0)

ans =

0 0 0 0 1 1

MATLAB has worked down each column and checked whether all of the elements, x, in the column

satisfy the condition x > 0, returning a 1 if this is true and 0 otherwise. Similarly:

>> any(A>2)

ans =

1 1 1 0 1 1

returns a f0; 1g-vector which has a 1 if any element, x, in the corresponding column satisfies the condition

x > 2.

>> any(A(:,2)>2)

ans =

1

since the second column of A does have an element which is greater than 2.

>> any(A(:,2)>99)

ans =

0

Nope! There is no element in the second column greater than 99.

MATLAB functions operate down the columns by default, but you can get them to operate down the

rows too. For example, if M is a matrix then the first dimension is the row dimension and the second

dimension is the column dimension. That is:

� going down a column is going down through the rows and that is summing along the first dimension.

� going along a row is going along through the columns and that is summing along the second dimen-

sion.

So

sum(M,1) means summing down each column of M (passing through the rows)

and

sum(M,2) means summing along each row of M (passing through the columns)

The other functions, such as any, all and so on, have the same feature. For example, let:

68

Page 74: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> M=round(10*rand(5,7))

M =

4 8 5 2 7 5 7

8 0 7 7 4 9 3

5 7 4 3 9 8 3

2 4 3 5 9 6 3

7 8 2 2 6 8 5

To sum along each row:

>> sum(M,2)

ans =

38

38

39

32

38

To find out which rows have a 3:

>> any(M==3,2)

ans =

0

1

1

1

0

To find the columns which have all positive entries:

>> all(M>0,1)

ans =

1 0 1 1 1 1 1

A binary matrix can represent properties. Each row could be an object and each column a property

which the object may or may not have. For example,

>> M=round(rand(5,7))

M =

1 1 1 1 0 1 1

0 1 1 0 0 0 0

1 0 1 0 1 0 1

1 1 1 1 0 0 0

0 1 0 1 0 1 0

Here are five objects with seven properties and the matrix is an incidence matrix between objects and properties. To

find the objects which have all of the first four properties:

>> all(M(:,1:4),2)

ans =

1

0

0

1

0

69

Page 75: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

To find which of the properties is possessed by all of the first four objects:

>> all(M(1:4,:),1)

ans =

0 0 1 0 0 0 0

3.2 Logical Matrices for Indexing

Let us set the stage by recalling the matrix A:

>> A

A =

-23 45 2 0 6 89

99 12 -34 -3 9 1

76 -6 84 2 16 74

Let us extract a submatrix from A consisting of the elements in rows 1:2 and columns 2:5:

>> A(1:2,2:5)

ans =

45 2 0 6

12 -34 -3 9

Now try:

>> A(0:2,1:3)

and we get the frustrated reply:

??? Index into matrix is negative or zero.

This is because there is no row zero. So 0 cannot be used as an index. However, a logical matrix can be

used as an index:

A =

-23 45 2 0 6 89

99 12 -34 -3 9 1

76 -6 84 2 16 74

Let

>> I=A>10

I =

0 1 0 0 0 1

1 1 0 0 0 0

1 0 1 0 1 1

Now:

>> T=A(I)

T =

99

76

45

12

84

16

89

74

70

Page 76: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

is a column vector of the elements encountered in a columnwise search of A corresponding to where the

(logical) index matrix I is 1. Beware: the 0s and 1s in a logical matrix are not the same as numerical 0s and

1s. To see this, let:

>> x=linspace(-1,1,5)

x =

-1.0000 -0.5000 0 0.5000 1.0000

>> i=[0 0 1 1 1]

i =

0 0 1 1 1

>> x(i)

??? Index into matrix is negative or zero.

See release notes on changes to logical indices.

Again, MATLAB is complaining about zero indices. But:

>> j=x>=0

j =

0 0 1 1 1

>> x(j)

ans =

0 0.5000 1.0000

MATLAB is happy with this because j is a logical matrix - one whose entries signify yes/no to some

enquiry and are created by the logical operators. We can convert an ordinary f0; 1g-matrix to a logical

matrix with the command: logical. For example

>> i=logical(i)

i =

0 0 1 1 1

>> x(i)

ans =

0 0.5000 1.0000

Type

>> help logical

The find command finds the linear index in the matrix, relative to a columnwise search down successive

columns, of elements satisfying some condition. Let us recover our matrix A:

A =

-23 45 2 0 6 89

99 12 -34 -3 9 1

76 -6 84 2 16 74

Now let us find the index of those elements which are greater than 20.

>> find(A>20)

ans =

2

3

4

9

16

18

71

Page 77: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

If we want the actual elements:

>> A(find(A>20))

ans =

99

76

45

84

89

74

does the job. If the subscripts in the matrix are required rather than the linear index then we have: ind2sub.

Type

>>help ind2sub:

IND2SUB Multiple subscripts from linear index. IND2SUB is used to determine

the equivalent subscript values corresponding to a given single index into

an array.

[I,J] = IND2SUB(SIZ,IND) returns the arrays I and J containing the equivalent

row and column subscripts corresponding to the index matrix IND for a matrix

of size SIZ.

For matrices, [I,J] = IND2SUB(SIZE(A),FIND(A>5)) returns the same values as

[I,J] = FIND(A>5).

[I1,I2,I3,...,In] = IND2SUB(SIZ,IND) returns N subscript arrays I1,I2,..,

In containing the equivalent N-D array subscripts equivalent to IND for an

array of size SIZ.

See also SUB2IND, FIND.

Try:

>> [r c]=ind2sub(size(A), find(A>20))

r =

2

3

1

3

1

3

c =

1

1

2

3

6

6

So the condition is satisfied at subscripts: .2; 1/; .3; 1/; � � � .We will use the following idea a lot. If A is a matrix and C is some condition then:

A.C / is a list of those elements of A which satisfy the condition C:

72

Page 78: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

For example

>> A

A =

-23 45 2 0 6 89

99 12 -34 -3 9 1

76 -6 84 2 16 74

>> B=A(A>30)

B =

99

76

45

84

89

74

x =

-1.0000 -0.5000 0 0.5000 1.0000

>> y=x(x<0)

y =

-1.0000 -0.5000

Again, MATLAB does the most reasonable thing. If A is a matrix then A.C / is a column vector. If A is a

row or column then A.C / is a row or column respectively.

A word of caution when using the == operator. Be aware that any computer produces roundoff errors.

To illustrate:

>> a=0

a =

0

>> b=sin(pi)

b =

1.2246e-016

>> a==b

ans =

0

Since b has been computed correct to 16 decimal places, b is close to, but not equal to 0. We will need to

identify places where a variable, y, say, becomes 0. Setting y==0 does not suffice. Try:

>> x=[-pi:pi/4:pi]

x =

-3.1416 -2.3562 -1.5708 -0.7854 0 0.7854 1.5708 2.3562 3.1416

>> y=sin(x)

y =

-0.0000 -0.7071 -1.0000 -0.7071 0 0.7071 1.0000 0.7071 0.0000

We humans know that y has zeros at !�; 0; � and it looks as though MATLAB knows it too. However, let

us try to identify the zeros with:

>> z=(y==0)

z =

0 0 0 0 1 0 0 0 0

and we see that MATLAB has identified only one zero due to its roundoff errors. We would rather have to

find those values which are “close to 0” by:

73

Page 79: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> zc=abs(y)<10e-15

zc =

1 0 0 0 1 0 0 0 1

>> zc=abs(y)<eps

zc =

1 0 0 0 1 0 0 0 1

The number eps is the distance from 1 to the next floating point number and is twice the unit roundoff.

>help eps. But don’t get too close:

>> zc=abs(y)<10e-17

zc =

0 0 0 0 1 0 0 0 0

and a zero has been missed.

As an application let us generate a vector, v, which has repeated values. Our task is to find a systematic

way of extracting the distinct values into a vector dv. MATLAB has the function unique which does this

but it is instructive to find our own procedure.

>> v=round(10*rand(1,14))

v =

7 8 0 7 4 8 5 7 4 3 2 2 7 3

Start dv as the empty matrix.

>> dv=[]

dv =

[]

Augment dv by adding the first element of v.

>> dv=[dv v(1)]

dv =

7

Redefine v as the vector whose elements are not equal to v.1/

v=v(v˜=v(1))

v =

8 0 4 8 5 4 3 2 2 3

Just note how easy this is to do with MATLAB. Augment dv as before, using smart recall.

>> dv=[dv v(1)]

dv =

7 8

Redefine v

>> v=v(v˜=v(1))

v =

0 4 5 4 3 2 2 3

Repeat the process until v is empty.

74

Page 80: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> dv=[dv v(1)]

dv =

7 8 0

>> v=v(v˜=v(1))

v =

4 5 4 3 2 2 3

>> dv=[dv v(1)]

dv =

7 8 0 4

>> v=v(v˜=v(1))

v =

5 3 2 2 3

>> dv=[dv v(1)]

dv =

7 8 0 4 5

>> v=v(v˜=v(1))

v =

3 2 2 3

>> dv=[dv v(1)]

dv =

7 8 0 4 5 3

>> v=v(v˜=v(1))

v =

2 2

>> dv=[dv v(1)]

dv =

7 8 0 4 5 3 2

>> v=v(v˜=v(1))

v =

[]

and the procedure is complete.

Type

>> help elmat

to see a list of elementary matrix manipulation tools. In particular, the function isequal is useful.

>> help isequal

ISEQUAL True if arrays are numerically equal.

ISEQUAL(A,B) is 1 if the two arrays are the same size and contain the

same values, and 0 otherwise.

ISEQUAL(A,B,C,...) is 1 if all the input arguments are numerically equal.

ISEQUAL recursively compares the contents of cell arrays and structures.

If all the elements of a cell array or structure are numerically equal,

ISEQUAL will return 1.

See also EQ.

For example:

>> a=[1 2; 3 4]

a =

1 2

3 4

75

Page 81: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> b=[1 2 ; 3 4]

b =

1 2

3 4

>> c=[ 1 2; 3 5]

c =

1 2

3 5

>> isequal(a,b)

ans =

1

>> isequal(a,c)

ans =

0

>> isequal(a,b,c)

ans =

0

>> isequal(a,b,a)

ans =

1

The function ismember is also useful. Look up its usage with the help facility. To see it in action,

suppose we have a matrix, M :

>> M=[ 1 2 3; 4 5 6; 7 8 9]

M =

1 2 3

4 5 6

7 8 9

Let x D 3:

>> x=3;

Is x a member of M ?

>> ismember(M,x)

ans =

0 0 1

0 0 0

0 0 0

So ismember(M,x) produces a logical matrix which answers the question. Try

>> v=[4 5 6];

>> ismember(M,v)

ans =

0 0 0

1 1 1

0 0 0

Now the 1s appear where the members of the vector v are members of the matrix M .

>> ismember(M,v,’rows’)

ans =

0

1

0

76

Page 82: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

Now the row of M which matches the vector v is identified.

Type >>help ops to see the complete list of operators. We will need the function unique, later.

3.2.1 Exercise

[1] Generate a 5 � 6 matrix, m, of numbers between !100 and 100.

Execute the MATLAB commands which extract into a list:

(a) the elements, y, of m which satisfy: !50 < y < 50;

(b) the elements, y, of m which satisfy: y > 90 or y < !90;

(c) the elements whose absolute value is less than 10.

[2] Let x D Œ!1;!0:99; � � � ; 0:99; 1� and let y be the vector whose elements are the square of the ele-

ments of x. Execute the MATLAB commands which produce a list, t , whose values are the values of

y which are greater than 0:1.

[3] The table below indicates whether the objects listed do (1) or do not (0) have certain properties.

object property 1 property 2 property 3 property 4 property 5 property 6

1 1 0 1 1 0 0

2 1 1 1 0 0 0

3 0 1 0 1 0 1

4 0 0 1 1 1 0

5 0 0 0 1 1 1

6 1 1 0 1 1 0

7 0 0 0 1 0 0

Construct a 0; 1-matrix M and then produce the commands which identify

(a) an object with the properties 4:6

(b) an object without properties 1:3

(c) an object with the properties 4:6, but without properties 1:3;

(d) an object with at least properties 3:6;

(e) an object with less than three of the properties;

(f) an object with all of the properties;

(g) an object with none of the properties.

[4] The graph of the function

y D x2e x

looks like

77

Page 83: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

0 1 2 3 4 5 6 7 8 9 100

0.1

0.2

0.3

0.4

0.5

0.6

0.7

x

y

y=x2e−x

This could represent, for example, the concentration of a substance in the blood, after a pill has been

taken, as a function of time. Let x=[0:.01:10]; and compute the corresponding y. Then

find

(a) the maximum concentration

(b) the time when the concentration drops once more to the level 0.3.

[5] The graph of y D tan x has vertical asymptotes at x D ˙�2. If we wanted to plot

the graph then we would have to decide on a maximum value for jyj. Say this is

10. We then plot only fy W jyj � 10g.Start with

x=linspace(-pi/2,pi/2,501);

y=tan(x);

Write the MATLAB code to generate

fy W jyj � 10g and fx W jyj � 10g:

78

Page 84: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Chapter 4

Graphical Output

4.1 Two-Dimensional Plots

To obtain the graph of

y D f .x/ x 2 Œa; b�

we:

� form a vector x=linspace(a,b,n) for a suitable number n;

� form the vector y=f(x);

� use the MATLAB function plot in the form plot(x,y)

which forms n points:

..x.1/; y.1//; ..x.2/; y.2//; : : : ; .x.n/; y.n//

and joins them to produce a polygonal arc consisting of n! 1 straight line segments.

Try it out with the function

y D 100! x C 3p

100C x2:

>> x=linspace(-4,10,100);

>> y=100-x+3*sqrt(100+x.ˆ2);

>> plot(x,y)

The figure window appears:

−4 −2 0 2 4 6 8 10128

129

130

131

132

133

134

135

136

137

79

Page 85: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

Type

>>help plot

for the details. We will go through some of them now.

4.1.1 Plotting Matrices Versus Matrices

PLOT Linear plot.

PLOT(X,Y) plots vector Y versus vector X. If X or Y is a matrix,

then the vector is plotted versus the rows or columns of the matrix,

whichever line up.

So we can plot a matrix X versus a matrix Y .

>> x=[1:10]’;

>> y1=x.ˆ2;

>> y2=x.ˆ3;

>> X=[x x]

X =

1 1

2 2

3 3

4 4

5 5

6 6

7 7

8 8

9 9

10 10

>> Y=[y1 y2]

Y =

1 1

4 8

9 27

16 64

25 125

36 216

49 343

64 512

81 729

100 1000

>> close

>> plot(X,Y)

The columns of Y are plotted against the columns of X .

80

Page 86: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

1 2 3 4 5 6 7 8 9 100

100

200

300

400

500

600

700

800

900

1000

4.1.2 Plotting a Scalar Versus a Matrix

If X is a scalar and Y is a vector, length(Y) disconnected points are plotted.

To see this, try

>> t=4;

>> v=[2:.1:5];

>> close

>> plot(t,v)

and the points:

f.t; v.i// W i 2 Œ1 W length.v/gare plotted, forming a vertical set of points above t D 4.

>>close

>>plot(v,t)

produces a horizontal set of points.

4.1.3 Plotting a Vector

PLOT(Y) plots the columns of Y versus their index.

If Y is complex, PLOT(Y) is equivalent to PLOT(real(Y),imag(Y)).

In all other uses of PLOT, the imaginary part is ignored.

For example

>> x=[1:.1:3].ˆ2;

>> close

>> plot(x)

81

Page 87: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

0 5 10 15 20 251

2

3

4

5

6

7

8

9

4.1.4 Linestyles and Colours

Various line types, plot symbols and colors may be obtained with

PLOT(X,Y,S) where S is a character string made from one element

from any or all the following 3 columns:

b blue . point - solid

g green o circle : dotted

r red x x-mark -. dashdot

c cyan + plus -- dashed

m magenta * star

y yellow s square

k black d diamond

v triangle (down)

ˆ triangle (up)

< triangle (left)

> triangle (right)

p pentagram

h hexagram

For example, PLOT(X,Y,’c+:’) plots a cyan dotted line with a plus

at each data point; PLOT(X,Y,’bd’) plots blue diamond at each data

point but does not draw any line.

So the syntax is plot(x,y,choices), where choices is a string of the form

’colour, markerstyle, linestyle’

chosen from the list above (in any order). Any or all of the three choices may be left blank.For example , to produce a red curve (polygonal arc):

>> x=[0:.1:10];

>> y=x.ˆ2.*exp(-x);

>> close

>> plot(x,y,’r’)

82

Page 88: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

0 1 2 3 4 5 6 7 8 9 100

0.1

0.2

0.3

0.4

0.5

0.6

0.7

To produce a red curve with � as markers and no lines connecting the points:

>> close

>> plot(x,y,’*r’)

>> title(’markers only’)

The function title adds a title to the figure with the syntax: title(’figure name’).

0 1 2 3 4 5 6 7 8 9 100

0.1

0.2

0.3

0.4

0.5

0.6

0.7markers only

To produce a black curve with square markers and dotted linestyle:

>> close

>> plot(x,y,’ks:’)

The function title adds a title to the figure with the syntax: title(’figure name’).

4.1.5 Plotting Sequences

The function stem gives a graphical representation of a sequence.

>> help stem

STEM Discrete sequence or "stem" plot.

STEM(Y) plots the data sequence Y as stems from the x axis

83

Page 89: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

terminated with circles for the data value. If Y is a matrix then

each column is plotted as a separate series.

STEM(X,Y) plots the data sequence Y at the values specified

in X.

STEM(...,’filled’) produces a stem plot with filled markers.

STEM(...,’LINESPEC’) uses the linetype specified for the stems and

markers. See PLOT for possibilities.

STEM(AX,...) plots into axes with handle AX. Use GCA to get the

handle to the current axes or to create one if none exist.

H = STEM(...) returns a vector of stemseries handles in H, one handle

per column of data in Y.

See also plot, bar, stairs.

Reference page in Help browser

doc stem

For example:

>> x(1)=1;

>> x(2)=1;

>> for k=3:20

x(k)=1.2*x(k-1)-1.3*x(k-2);

end

>> stem(x)

0 2 4 6 8 10 12 14 16 18 20−10

−5

0

5

10

15

There are many more specialised plotting tools. To see them all, click on the Help button and go to

Functions, By Category, Graphics. Explore!

4.1.6 Superimposing Plots

To plot curves in the same system of axes, we use the syntax: plot(x,y1,x,y2,x,y2) or the hold

command. If the vectors are columns then plot(x,[y1 y2]) does the same thing.For example

84

Page 90: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> x=[0:.1:10]’;

>> y=x.*exp(-x);

>> z=x.ˆ2.*exp(-x);

>> close

>> plot(x,y,x,z)

0 1 2 3 4 5 6 7 8 9 100

0.1

0.2

0.3

0.4

0.5

0.6

0.7

Equivalently:

>> hold on

>> close

>> plot(x,y)

>> plot(x,z)

>> hold off

does the same thing.The functions xlabel, ylabel label the axes and the function legend adds a legend. For example

>> close

>> plot(x,y,x,z)

>> xlabel(’x=time’)

>> ylabel(’y,z=concentrations’)

>> legend(’substance 1’,’substance 2’)

0 1 2 3 4 5 6 7 8 9 100

0.1

0.2

0.3

0.4

0.5

0.6

0.7

x=time

y,z=concentrations

substance 1substance 2

The grid command produces a grid:

85

Page 91: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>>grid

and the grid is toggled on. Type this again and it is toggled off.

4.1.7 Plotting Closed Figures

To plot a closed figure, form lists of the x; y-values of the points and repeat the first point at the end of thelist. For example, to plot a square:

>> close

>> x=[0 1 1 0 0];

>> y=[0 0 1 1 0]

>> plot(x,y)

The figure that is produced is square but MATLAB has automatically decided on the length of the axes.The axis function allows us to control the length of the axes. The syntax is axis([xmin,xmax,ymin,ymax]).For example

>> axis([-1,2,-1,2])

−1 −0.5 0 0.5 1 1.5 2−1

−0.5

0

0.5

1

1.5

2

Alternatively,

xlim([xmin, xmax])

or

ylim([ymin, ymax])

sets the lengths independently. Type

>> help axis

for a full list of axis options. Experiment with these on your own, but two, namely axis equal and axissquare are worth mentioning now. We plot a circle by:

>> t=[0:.01:2*pi];

>> x=cos(t);

>> y=sin(t);

>> close

>> plot(x,y)

86

Page 92: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

−1 −0.8 −0.6 −0.4 −0.2 0 0.2 0.4 0.6 0.8 1−1

−0.8

−0.6

−0.4

−0.2

0

0.2

0.4

0.6

0.8

1

This does not look quite circular. Suppose that we set the axis lengths:

axis([-2,2,-1.5,1.5])

−2 −1.5 −1 −0.5 0 0.5 1 1.5 2−1.5

−1

−0.5

0

0.5

1

1.5

The command axis square forces the box to be square.

87

Page 93: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

−2 −1.5 −1 −0.5 0 0.5 1 1.5 2−1

−0.8

−0.6

−0.4

−0.2

0

0.2

0.4

0.6

0.8

1

The command axis equal forces the aspect ratio to be equal:

−2 −1.5 −1 −0.5 0 0.5 1 1.5 2

−1.5

−1

−0.5

0

0.5

1

1.5

In this figure, even though the axes are of different lengths, the curve is circular.

4.1.8 Subplots

We can partition the figure window into a m � n matrix of sub-windows using the syntax:

subplot(m,n,k)

which plots the k th figure window in the m � n matrix of figure windows. Try:

>> t=linspace(0,2*pi,501);

>> c1=cos(t);

>> s1=sin(t);

>> s2=sin(2*t);

>> s3=sin(3*t);

>> s4=sin(4*t);

>> figure

>> subplot(2,2,1)

88

Page 94: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> plot(c1,s1)

>> subplot(2,2,2)

>> plot(c1,s2)

>> subplot(2,2,3)

>> plot(c1,s3)

>> subplot(2,2,4)

>> plot(c1,s4)

and we get:

−1 −0.5 0 0.5 1−1

−0.5

0

0.5

1

−1 −0.5 0 0.5 1−1

−0.5

0

0.5

1

−1 −0.5 0 0.5 1−1

−0.5

0

0.5

1

−1 −0.5 0 0.5 1−1

−0.5

0

0.5

1

4.1.9 Axis Properties

When plotting, MATLAB makes up its own mind about the axis, fonts, linestyle and hundreds of otherthings. These can all be set if necessary. To see the current axis properites use the get function. Forexample

>> x=[-360:360];

>> y=sin(pi/180*x);

>> close

>> plot(x,y)

Let’s plot the x-axis as well:

>> hold on

>> plot(x,0)

89

Page 95: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

−400 −300 −200 −100 0 100 200 300 400−1

−0.8

−0.6

−0.4

−0.2

0

0.2

0.4

0.6

0.8

1

To get the current axis properties, type

>> get(gca)

ALim = [0 1]

ALimMode = auto

AmbientLightColor = [1 1 1]

.

.

.

UIContextMenu = []

UserData = []

Visible = on

A long list of axis properties is displayed. We can now set the xtick and fontsize by

>> set(gca,’xtick’,[-360:45:360])

>> set(gca,’fontsize’,[8])

−360 −315 −270 −225 −180 −135 −90 −45 0 45 90 135 180 225 270 315 360−1

−0.8

−0.6

−0.4

−0.2

0

0.2

0.4

0.6

0.8

1

Suppose that we want to identify those points for which y > :8. We do this as follows:

>> I=find(y>.8);

>> hold on

>> p=y(I);

>> xp=x(I);

>> plot(xp,p,’*’)

90

Page 96: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

The figure is now:

−360 −315 −270 −225 −180 −135 −90 −45 0 45 90 135 180 225 270 315 360−1

−0.8

−0.6

−0.4

−0.2

0

0.2

0.4

0.6

0.8

1

The plotting functions that are available are:

Plotting Functions

plot simple curve plot

loglog plot with log-scaled axes

semilogx plot with log-scaled x-axis

semilogy plot with log-scaled y-axis

plotyy x-y plot with y axis on left and right

fplot functional form of plot, specified by a string

ezplot easy to use plot function with

ezpolar easy to use form of polar plot

fill polygon fill

area filled area graph

bar bar graph

barh horizontal bar graph

hist cgistogram

pie pie chart

comet animated x-y plot

errorbar error bar plot

quiver vector field plot

scatter scatter plot

Consult the help files on these. We will use the hist function later when we deal with stochastic

processes.

4.2 Curves in 3-D

To plot a curve in 3-space we have the plot3 function.

>>help plot3

PLOT3 Plot lines and points in 3-D space.

PLOT3() is a three-dimensional analogue of PLOT().

PLOT3(x,y,z), where x, y and z are three vectors of the same length,

plots a line in 3-space through the points whose coordinates are the

91

Page 97: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

elements of x, y and z.

PLOT3(X,Y,Z), where X, Y and Z are three matrices of the same size,

plots several lines obtained from the columns of X, Y and Z.

Various line types, plot symbols and colors may be obtained with

PLOT3(X,Y,Z,s) where s is a 1, 2 or 3 character string made from

the characters listed under the PLOT function.

PLOT3(x1,y1,z1,s1,x2,y2,z2,s2,x3,y3,z3,s3,...) combines the plots

defined by the (x,y,z,s) fourtuples, where the x’s, y’s and z’s are

vectors or matrices and the s’s are strings.

Example: A helix:

>>t = 0:pi/50:10*pi;

>>plot3(sin(t),cos(t),t);

PLOT3 returns a column vector of handles to LINE objects, one handle

per line. The X,Y,Z triples, or X,Y,Z,S quads, can be followed by

parameter/value pairs to specify additional properties of the lines.

See also PLOT, LINE, AXIS, VIEW, MESH, SURF.

So let

>> t=linspace(0,6*pi,1001);

>> x=cos(t);

>> y=sin(t);

>> z=t;

>> plot3(x,y,z)

>> title(’helix’)

and the helix appears.

−1

−0.5

0

0.5

1

−1

−0.5

0

0.5

1

0

2

4

6

8

10

12

14

16

18

20

helix

Try the same thing with

>>comet3(x,y,z);

92

Page 98: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

4.3 Surfaces

To plot surfaces defined by

z D f .x; y/

we first need to establish a grid of points in the x; y plane. To see how this is done, consider the matrix ofcoordinates:

(2, 3) (3, 3) (4, 3)

(2, 4) (3, 4) (4, 4)

(2, 5) (3, 5) (4, 5)

(2, 6) (3, 6) (4, 6)

This can be expressed in terms of two matrices:

X = 2 3 4 Y= 3 3 3

2 3 4 4 4 4

2 3 4 5 5 5

2 3 4 6 6 6

Here, X is the matrix of x-values of points on the grid and Y is the matrix of y-values of points in thegrid. These two matrices are produced using the function meshgrid as follows.

>> x=[2 3 4];

>> y=[ 3 4 5 6];

>> [x y]=meshgrid(x,y)

x =

2 3 4

2 3 4

2 3 4

2 3 4

y =

3 3 3

4 4 4

5 5 5

6 6 6

If

z D x2 C y2

we plot the values of z using

>>z=x.ˆ2 +y.ˆ2

z =

13 18 25

20 25 32

29 34 41

40 45 52

Now the set of points .x; y; z/ for .x; y/ ranging through the points in the grid, are plotted with the

functions: mesh, surf, or surfl. The usage is illustrated by the following example. Let us plot the

surface defined by:

z D 1C cos.x2 C y2/:

Here we go. We define a meshgrid of points in the x; y plane, compute the corresponding z values andplot the points.

>> x=linspace(-2,2,201);

>> y=linspace(-2,2,201);

>> [x y]=meshgrid(x,y);

>> z=1+cos(x.ˆ2+y.ˆ2);

>> surfl(x,y,z)

93

Page 99: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

and here comes the rather interesting surface:

Type:

>>help surfl

>>help surf

>>help mesh

to see the documentation. There are many options available and a very nice one is shading interp as

well as colormap(pink)

The surface above was obtained by giving the function a rectangular domain. If the domain were

specified in polar coordinates with radius ranging from 0 to 4 and angle ranging from 0 to 2� say, the

corresponding Cartesian coordinates would have to be specified in order to plot the surface. MATLAB has

the function pol2cart which does the job. To see how it works:

>> r=[0:.1:4];

>> t=[0:pi/16:2*pi];

>> [T R]=meshgrid(t,r);

>> close all

>> plot(T,R,’.’)

>> xlabel(’T’)

>> ylabel(’R’)

>> [X Y]=pol2cart(T,R);

>> figure

>> plot(X,Y,’.’)

>> xlabel(’X’)

>> ylabel(’Y’)

0 1 2 3 4 5 6 70

0.5

1

1.5

2

2.5

3

3.5

4

T

R

−4 −3 −2 −1 0 1 2 3 4−4

−3

−2

−1

0

1

2

3

4

X

Y

94

Page 100: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

The rectangular coordinates of the points specified by their polar coordinates are computed by pol2cart.

The polar coordinates are on the left and the corresponding cartesian coordinates are on the right.Try this

>>theta=[0:pi/50:2*pi];

>> r=[0:.005:4];

>> [T, R]=meshgrid(theta, r);

>> [X, Y]=pol2cart(T, R);

>> Z=1+cos(X.ˆ2+Y.ˆ2);

>> close all

>> surfl(X,Y,Z)

4.4 Contour Maps

If the function >>contour(x,,y,z) is used instead of >>surfl(x,y,z) then the contour map is pro-duced. MATLAB makes up its own mind about the number of contours. The caommand contour(x,y,z,n)tells MATLAB to plot n contours. The function contourf(x,y,z,n) produces n contour lines which arefilled in. With x; y; z defined as above, try:

>> contour(x,y,z)

>> contour(x,y,z,50)

>> contourf(x,y,z)

>> contour(x,y,z,30)

Here is the filled contour map:

95

Page 101: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

−2 −1.5 −1 −0.5 0 0.5 1 1.5 2−2

−1.5

−1

−0.5

0

0.5

1

1.5

2

which looks better in full colour as you can see in the figure window.

Labels can be added to the contour levels with clabel. Consult the help files on contour, contourf,

clabel

Other 3-d plotting functions are:

3-d Plotting Functions

plot3 3-d curve plot

contour contour plot

contourf filled contour plot

contour3 3-d contour plot

mesh wireframe surface

meshc wireframe surface with contours

meshz wireframe surface with curtain

surf solid surface

surfc solid surface with contours

waterfall unidirectional wireframe

bar3 3-d bar graph

bar3h 3-d horizontal bar graph

pie3 3-d pie chart

fill3 polygon fill

comet3 3-d comet

scatter3 3-d scatter

stem3 3-d stem plot

4.5 The Gradient Vector

If z D f .x; y/ then the gradient of f , denoted, rf , is defined as

rf D"

@f@x

@f@y

#

Of course, rf is a function of x and y and we could write rf .x; y/ to emphasise this. For example,

if z D x2y C 2xy3 then

rf D�

2xy C 2y3

x2 C 6xy2

:

96

Page 102: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

If z D f .x1; � � � ; xn/ then

rf D

2

6

6

4

@f@x1

:::@f

@xn

3

7

7

5

A fundamental property of the gradient vector is that it is orthogonal to the contour lines at each point.The functions gradient and quiver assist us here.

GRADIENT Approximate gradient.

[FX,FY] = GRADIENT(F) returns the numerical gradient of the matrix F. FX corresponds

to dF/dx, the differences in the x (column) direction. FY corresponds to dF/dy, the

differences in the y (row) direction. The spacing between points in each direction

is assumed to be one. When F is a vector, DF = GRADIENT(F) is the 1-D gradient.

Type help gradient for the full monty. To see how it works, try the following:

>> x=[-2:2];y=x;

>> [x,y]=meshgrid(x,y)

x =

-2 -1 0 1 2

-2 -1 0 1 2

-2 -1 0 1 2

-2 -1 0 1 2

-2 -1 0 1 2

y =

-2 -2 -2 -2 -2

-1 -1 -1 -1 -1

0 0 0 0 0

1 1 1 1 1

2 2 2 2 2

>> z=x.ˆ2+3*y.ˆ2

z =

16 13 12 13 16

7 4 3 4 7

4 1 0 1 4

7 4 3 4 7

16 13 12 13 16

>> [px,py]=gradient(z)

px =

-3 -2 0 2 3

-3 -2 0 2 3

-3 -2 0 2 3

-3 -2 0 2 3

-3 -2 0 2 3

py =

-9 -9 -9 -9 -9

-6 -6 -6 -6 -6

0 0 0 0 0

6 6 6 6 6

9 9 9 9 9

So we see that px stores the differences between the columns of z and py stores the differences between

the rows. These are the discrete versions of the partial derivatives.If the spacing is not 1 then:

[FX,FY] = GRADIENT(F,H), where H is a scalar, uses H as the spacing between points

in each direction.

97

Page 103: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

[FX,FY] = GRADIENT(F,HX,HY), when F is 2-D, uses the spacing specified by HX and HY.

HX and HY can either be scalars to specify the spacing between coordinates or

vectors to specify the coordinates of the points. If HX and HY are vectors, their

length must match the corresponding dimension of F.

The quiver function places arrows at specified points in specified directions.

QUIVER Quiver plot.

QUIVER(X,Y,U,V) plots velocity vectors as arrows with components (u,v) at the points

(x,y). The matrices X,Y,U,V must all be the same size and contain corresponding position

and velocity components (X and Y can also be vectors to specify a uniform grid).

QUIVER automatically scales the arrows to fit within the grid.

Try this:

>> x=[-2:.1:2];y=x;

>> [x,y]=meshgrid(x,y);

>> z=sin(x)+cos(y);

>> x=[-pi:pi/10:pi];y=x;

>> [x,y]=meshgrid(x,y);

>> z=sin(x)+cos(y);

>> [px,py]=gradient(z,pi/10,pi/10);

>> contour(x,y,z)

>> hold on

>> quiver(x,y,px,py)

−3 −2 −1 0 1 2 3

−3

−2

−1

0

1

2

3

4.6 Saving Figures

If you want to save a figure to file use: print. Type >>help print for the details. A good default is tosave the image as a tiff file. This is achieved with

>>print -dtiff path

For example

98

Page 104: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>>print -dtiff L:\figurename.tif

Tiff images can be inserted into most word processing documents and they are not as bulky as bitmap

images. Encapsulated postscript (eps) is another good option. These files can be included into TEX docu-

ments.

4.6.1 Exercise

[1] Plot the graph of the function

y D 1

.x 1/2C 3

.x 2/2

over the interval Œ0; 3�. The default axis limits will be such that the graph has a very long y-axis. Thisis because of the singularites at x D 1; 2. To getter a better picture, use

ylim([0, 50]).

[2] Plot the graph of the epicycloid:

x D .aC b/ cos t b cos�a

bC 1

t

y D .aC b/ sin t b sin�a

bC 1

t

for t 2 Œ0; 10��. For a D 12; b D 5 the graph is:

−25 −20 −15 −10 −5 0 5 10 15 20 25−25

−20

−15

−10

−5

0

5

10

15

20

25

x

y

Epicycloid with a=12, b=5

Produce a figure with axes and title as above.

[3] Write a program, called ellipse.m which solicits numbers a and b from the user and then plots the

graph of the ellipse:

x2

a2C y2

b2D 1

[4] Write a program, called pentagon.m, which plots a pentagon. Modify the program, calling it

ngon.m, to prompt the user for a positive integer, n, and then plot an n-gon.

99

Page 105: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

−1.5 −1 −0.5 0 0.5 1 1.5−1.5

−1

−0.5

0

0.5

1

1.5

[5] Write a program, called dartboard.m which plots a circular dartboard on a square frame:

−1.5 −1 −0.5 0 0.5 1 1.5−1.5

−1

−0.5

0

0.5

1

1.5The Dart Board Before the Action

Now modify this program, calling it dartsthrow.m, to prompt for the number, n, of darts to throwand then simulate the throwing of n darts at the board. Do this by generating suitable x and ycoordinates: dx and dy using the random number generator. Plot the points using:

plot(dx,dy,’.’,’markersize’,1)

With 1000 darts you should get:

−1.5 −1 −0.5 0 0.5 1 1.5−1.5

−1

−0.5

0

0.5

1

1.5Dartsthrow

[6] Write a program, called graph1.m, which the graph of

y D 1 cos x

x2:

100

Page 106: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

You may get warnings of division by zero. To remove these, redefine your x vector by

x=x(x˜=0);

and then redefine your y values

y=y(x˜=0);

and try again.

[7] Write a program, called graph2.m, which plots the graph of

y D sin x

x

with no complaints about division by zero.

[8] Write a program : graph3.m that plots the graphs of

y D 10 sin t

z D 10 sin t C 5 sin t

w D 10 sin t C 5 sin t C sin 5t

in 3� 1 subplots.

[9] Write a program graph4.m that asks for a number, a, close to �2

and then plots the graph of y D tan xfor x D Œ a W :001 W a�. You will see that the graph looks strange because very large values of y areproduced. Remove these by inserting the lines:

y=y(abs(y)<10);

x=x(abs(y)<10);

This is a useful trick for getting sensible plots.

[10] Write a program graph5.m that plots the graph of

y D 1

1 x2

on a suitable axis. Be sure to avoid dividing by zero and to remove very large values of y.

[11] A projectile fired with initial speed u and angle of elevation ˛ on a flat plane has coordinates

x D .u cos ˛/t

y D .u sin ˛/t 1

2gt2

where g D 9:81ms 2 is the acceleration due to gravity.

Write a program, called projectile1.m, which prompts for u and ˛ (in degrees) and then plots the

trajectory using the comet facility (>>help comet).

The comet plot is a little finicky. If you want to see the trajectory along with a thicker line to representthe ground, you will need to run comet first and then plot the trajectory and the ground. For example:

101

Page 107: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

xf=x(end); %find the last value of the x coordinate of the projectile

Gx=[0 xf]; %x coordinates of the ground line

Gy=[0 0]; %y coordinates of the ground line

comet(x,y); %run the comet plot

hold on

plot(Gx,Gy,’linewidth’,3) %plot the ground

plot(x,y); %plot the trajectory

hold off

In the program, you will need to solve a quadratic equation to find the time of flight. Identify thehighest point with a marker and insert a suitable text message at that point. To insert a text messageat a point .r; s/ into a figure use:

text(r,s,’message’)

A limited number of TEX commands are available. For example:

TEX Commands

nalpha a

nbeta ˇ:::

:::

napprox �nge �nle �ninfty 1npm ˙nsurd

p

For example text(r, s, ’nleftarrow maximum point’) inserts an arrow and the message atthe point .r; s/ on the graph. You can also manually insert comments use gtext or the insert text boxon the figure window. To insert text containing data, such as the initial speed and angle, into the title,xlabel, ylabel or text box, we use the sprintf function. The syntax is the same as for fprintf butsprintf prints formatted data to string. So:

message=sprintf(’speed, u = %3.0f, angle, a = %2.0f degrees\n’,u,a);

text(xm,ym/2,message)

puts the input data into a text box at .xm; ym

2/ where .xm; ym/ is the maximum point.

Here is typical output

0 500 1000 1500 2000 2500 3000 3500 4000 4500 50000

100

200

300

400

500

600

700

← maximum pointProjectile Motion

speed, u = 234, angle, a = 32 degrees

x: distance

y: height

102

Page 108: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

[12] Plot the surfaces, corresponding contour maps and contour maps with gradient vectors illustrated by

the quiver function:

(a) z D x2

4 y2

9: a hyperbolic paraboloid.

(b) z D x2

4C y2

9: an elliptic paraboloid.

(c) z D 1

1C x2 C y2.

(d) z D e y cos x.

(e) z D cos x C 3 cos.3x C y/.

(f) z D ex2Cy2

10 sin.x2 C y2/.

(g) z D xy.x2 y2/

x2 C y2

[13] Write a program, called cycloid.m, which plots the graph of the cycloid:

x D Rt k sin t

y D R k cos t

This is the locus of a point at a distance k from the centre of a circle of radius R which rolls along

the horizontal track: x D 0. So let t 2 Œ0; n2�� for some suitable number, n, of revolutions.

0 20 40 60 80 100 120

−40

−30

−20

−10

0

10

20

30

40

50

Cycloid

R=5.00, k=8.00

y

103

Page 109: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Chapter 5

Flow Control

5.1 If-Constructs

An if-construct or a branching statement is placed in a program at a place where a decision is to be made.The decision is made on the basis of a control statement which is either true (logical value of 1) or false(logical value of 0). If the control statement is true then the control commands are executed, otherwise theprogram proceeds to the line immediately after the end statement. The simplest form is:

if control statement

control commands

end

For example, in our program fact1.m, an input, n, is requested from the user and then n! is computed.We require n to be an integer and not a vector or any higher-dimensional array. So we insert an if-constructwhich decides whether or not this is true. If it is not true we get the program to halt and return an errormessage. This is conveniently done with the error function:

>> help error

ERROR Display message and abort function.

ERROR(’MSG’) displays the text MSG and causes an error exit from an

M-file to the keyboard. If the string is empty, no action is taken.

See also WARNING, LASTERR, ERRORDLG, DISP, DBSTOP.

The input n must be non-negative, have length.n/ D 1 and it must have no fractional part. We call theprogram fact.m:

%fact.m

%Usage: solicits n and then computes and displays n!

%crude first program

%

n=input(’n = ’);

if (length(n)˜=1) | (fix(n) ˜= n) | (n < 0)

error(’N must be a positive integer’);

end

p = prod(1:n);

fprintf(’%d! = %d\n’,n,p)

104

Page 110: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

A more general form of the construction is called an elseif ladder and has the form:

if control statement 1

command block 1

elseif control statement 2

command block 2

elseif control statement 3

command block 3

else control statement m

command block m

end

Control statements 1 to m are tested for a truth value of 1, in that order. If a truth value of 1 is found then

the corresponding block of command statements are executed. Note that the last control statement starts

with else. If truth values of 0 are produced for all the control statements then the program skips to the line

immediately after the end statement. For example :

The income tax in a country is computed as follows. Let I denote the annual income to the nearest unit.

Then:

� For I � 10000, the tax rate is 10%;

� for 10000 < I � 20000, the tax is 1000C 15% of the income above 10000;

� for 20000 < I , the tax is 2500C 20% of the income above 20000.

We say that the basic rate is 10% with marginal rates of 15% and 20% at barriers 10000 and 20000.

Here is a program that computes the income tax.

%tax1.m

%prompts for income and calculates income tax

%

I=input(’Income (to the nearest unit) = ’);

%get the income to the nearest unit anyway

I=fix(I);

if I<= 10000

t=.1*I;

elseif I <= 20000

t=1000+.15*(I-10000);

else

t=2500+.2*(I-20000);

end

out=[I;t];

fprintf(’The tax on %6.0f is %4.2f \n’,out)

Note that at the elsif condition it is not necessary have 10000 < I � 20000. If the first condition,

I � 10000 is not true then MATLAB skips to the next and tests that for truth. If it is not true then we

already have 10000 < I from the first being false and we now also have I � 20000.

105

Page 111: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

5.2 For-Loops

If a command is to be executed for a predetermined number of times or for a variable which ranges througha fixed vector, we achieve this with a for-loop or deterministic-loop. The syntax is

for variable=expression

statements

end

Usually the expression is a vector and the statements are executed as the variable ranges through each

element of the vector.For example, to compute the final value after 20 years in an account which has an initial deposit of

10000, attracts 10% interest per year and receives a deposit of 1000 at the end of each year we use thefor-loop:

s=10000; %set the sum to 10000 at the start of year 1

for k=[1:20]

s=s+.1*s+1000; %the value at the end of year k

end

As k ranges through the vector Œ1 W 20�, the sum, s, is successively increased.

If interest is paid every six months, the interest is 5% per half–year. Suppose that the deposits are 500

per half–year, then:

s=10000;

for k=.5:.5:20

s=s+.05*k+500;%value at the end of each half-year

end

Now k ranges through the vector Œ:5 W :5 W 20�.To display some values of sin x:

>> for k=[0:pi/4:2*pi]

disp([k,sin(k)])

end

Multiple loops: loops within loops, can be nested. In the debugging window, MATLAB automaticallyindents the loops to improve readability. For example:

for j=1:5

for i=1:6

M(i,j)=1/(i+j);

end

end

constructs the 6 � 5 matrix, M , such that

M.i; j / D 1

i C j

Actually, MATLAB assumes that the expression is a matrix and that the variable ranges through the

columns of the matrix. Of course, if the expression is a vector then the columns are the elements. For

example, suppose 10000 is deposited into three accounts which earn 20% per year. In:

� account 1 interest is accumulated yearly and there is a withdrawal of 3000 per year;

� account 2 interest is accumulated every 2 years and there is a withdrawal of 4000 every 2 years;

� account 3 interest is accumulated every 3 years and there is a withdrawal of 5000 every 3 years.

106

Page 112: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

We write a script which allows a 3 � 1 vector K to range through an index matrix.

I=[1:10;1:2:20;1:3:30];%index set

ID=[10000;10000;10000];%initial deposits

H=[3000;4000;5000]; %withdrawals

V=ID; %initial values in the accounts

r=.2; %interest rate

VV=[V]; %stores the values

for K=I %K ranges through the matrix I

V=[(1+r);(1+r)ˆ2;(1+r)ˆ3].*V-H;

VV=[VV,V];

end

format bank

T=[[0;0;0],I]; %insert year 0

close all

plot(T,VV,’.’)

fprintf(’acc1: %-10.2f acc2: %-10.2f acc3: %-10.2f\n’,VV)

The break command is used to terminate the execution of a loop (help break). In this case, controlis passed to the first statement following the end of the loop. For example

>> S=[0;0];I=repmat([1:10],2,1);

>> for K=I

S=S+[1/K(1);1/K(2)ˆ2]

if any(S>2)

break

end

end

S =

1.00

1.00

S =

1.50

1.25

S =

1.83

1.36

S =

2.08

1.42

and the computations cease after the first instance of any(S>2).

The continue command causes the execution of a loop to skip the remaining statements in the loop

and go to the line immediately after the end of the loop. For example

107

Page 113: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> clear

>> for k=1:10

x(k)=sum([1:k].ˆ2);

if x(k)>100, continue, end

disp(x);

end

1

1 5

1 5 14

1 5 14 30

1 5 14 30 55

1 5 14 30 55 91

5.3 Decision Trees

Suppose that we set ourselves the task of writing a script which prompts for the coefficients of a quadratice

equation and then returns the roots. So wish to solve

ax2 C bx C c D 0:

Let us also allow for the case a D 0, in which case we have a linear equation. We make a decision tree to

represent the situation and help us to form the loops.

No Solutions x D cb x D b˙

pb2 4ac

2ax D b˙i

p4ac b2

2a

b D 0? b2 4ac � 0?

a D 0?

yes no yes no

yes no

The decisions that have to made are:

� a D 0?

� b D 0?

� If a ¤ 0 then is � D b2 4ac >D 0?

We form the ladder:

if a==0

block 1

else

block 2

end

108

Page 114: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

In the first part of the ladder: block 1 (the left–hand side of the tree) we have a D 0 and on the second:

block 2 (the right-hand side of the tree) we have a ¤ 0. Within the first part we deal with the question

b D 0? and in the second part we deal with the question � � 0?. The script looks like:

%quadratic.m

%Displays the roots of the quadratic equation

%

disp(’Displays the roots of the quadratic equation: a*xˆ2+b*x+c=0’)

coeffs=input(’enter the coefficients in the form [a b c] = ’);

a=coeffs(1);

b=coeffs(2);

c=coeffs(3);

if a==0

if b==0

error(’no solution unless c=0’)

else

x=-c/b;

fprintf(’The is one root: %5.6f\n’,x)

end

else

disc=bˆ2-4*a*c;

%complex roots

if disc<0

d=sqrt(-disc);

p=-b/(2*a);

q=d/(2*a);

fprintf(’roots are %10.6f plusminus i*%10.6f\n’,p,q)

%distinct real roots

elseif disc>0

d=sqrt(disc);

r1=(-b+d)/(2*a);

r2=(-b-d)/(2*a);

fprintf(’roots are %10.6f and %10.6f\n’,r1,r2)

%repeated real roots

else

r=-b/(2*a);

fprintf(’repeated root: %10.6f\n’,r)

end

end

5.3.1 Exercise

[1] A salesman gets a basic monthly salary of R5000 plus 5% of all sales revenue up to R100000 plus

7% of all sales revenue in excess of R100000. Write a program, called salary.m, which computes

his salary.

[2] Modify the tax1 program, calling it vtax.m, to receive as input: an 5-list of tax rates: basic and 4

marginal rates, a 4 list of tax barriers and the income. The program should then produce as output the

income tax.

[3] The tax system in a country is such that:

� If your age is � 65 then you pay 10% tax.

� If your age is < 65 and you are a foreigner then you pay 20% tax.

� If your age is < 65 and you are not a foreigner then:

109

Page 115: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

� If income, I < 50000 you pay 10% tax

� If 50000 � I < 100000 you pay 5000 +15% of the income above 50 000

� If 100000 � I you pay 5000+7500+ 20% of the income above 100 000

Make a decision tree and write a script, called ftax.m which accepts

� age

� foreigner or not

� income

and returns the tax payable.

5.4 While-Loops

A while-loop has the form

while expression

statements

end

The statements are executed while ever the expression is true. This is also called a non-deterministic

loop since the termination of the loop is not predetermined. The break command and the continue

command may also be used in while loops. For example, suppose we want to write a script to find the root,

accurate to four places, of

x2 10 D 0

using Newton’s Method. Suppose that we want the root accurate to three decimal places. We therefore stop

the iterations when the correction, h, is less than 0:0005. In other words, we continue the iterations while

h � 0:0005. The program therefore uses a while loop as follows.

%newton.m

%throw-away program to find the root xˆ2=10.

%illustrates the use of a while-loop

%

%first estimates

x=2;

h=1;

while abs(h)>.0005

h=-(xˆ2-10)/(2*x);

x=x+h;

end

fprintf(’the root of xˆ2-10=0, accurate to three places is %4.3f\n’,x)

To get a better idea of the iterative process we modify the above program to show the sequence which

converges to the root and the sequence error estimates.

110

Page 116: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

%newton2.m

%throw-away program to find the root xˆ2=10.

%illustrates the use of a while-loop and shows the results of each iteration

%

%iterations

n=0;

%first estimates

x=2;

h=1;

%number of places

p=5;

out=[n x h];

while abs(h)>5*10ˆ(-p-1)

h=-(xˆ2-10)/(2*x);

x=x+h;

n=n+1;

out=[out; n x h ];

end

out=out’;

disp(’Using Newton’’s method to find the root of xˆ2-10=0’);

fprintf(’iteration: %-3.0f x=%-15.12f h=%-10.12f \n’,out)

The output is:

Using Newton’s method to find the root of xˆ2-10=0

iteration: 0 x=2.000000000000 h=1.000000000000

iteration: 1 x=3.500000000000 h=1.500000000000

iteration: 2 x=3.178571428571 h=-0.321428571429

iteration: 3 x=3.162319422151 h=-0.016252006421

iteration: 4 x=3.162277660444 h=-0.000041761707

iteration: 5 x=3.162277660168 h=-0.000000000276

and we can see that the iterations stop when the correction, h, no longer affects the sixth decimal place.If the expression being evaluated during the execution of a while-loop always holds then the iterations

will continue indefinitely. For this reason, it is not a bad idea to include some condition on the number ofiterations. For example, in the above process we could change the expression to:

while abs(h)>5*10ˆ(-p-1) & n<100

which ensures that the number, n, of iterations does not get too large. Do not forget that MATLAB calcula-

tions can be terminated from the keyboard with CNTRL+C.An infinite loop, of the form

repeat=1;

while repeat==1

statements

repeat=input(’repeat? 1=yes, 0=no’);

end

can be used to repeat a program while getting different inputs from the user. For example, we might want

to keep repeating the newton2 program while obtaining different values for p from the user. We can do this

as follows:

111

Page 117: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

%newton2.m

%throw-away program to find the root xˆ2=10.

%illustrates the use of a while-loop

%illustrates the use of an infinite while-loop to repeat input

%

%repeats

repeat=1;

while repeat==1

%iterations

n=0;

%first estimates

x=2;

h=1;

%number of places

p=input(’number of places = ’);

out=[n x h];

while abs(h)>5*10ˆ(-p-1)

h=-(xˆ2-10)/(2*x);

x=x+h;

n=n+1;

out=[out; n x h ];

end

out=out’;

disp(’Using Newton’’s method to find the root of xˆ2-10=0’);

fprintf(’iteration: %-3.0f x=%-15.12f h=%-10.12f \n’,out)

repeat=input(’Do another? 1=yes, 0=no’);

end

5.5 Switch-Case

If an test variable can take on one of a number of results and the statements to be executed depends on the

result of the test then we use the switch-case construct.It has the form:

switch test

case result 1

code block 1

case result 2

code block 2

.

.

.

case result m

code block m

otherwise

code block (m+1)

end

The test variable is evaluated and the block of statements following the first matching result are

executed.

To illustrate this, let us write a function which computes the number of days in a month. We number the

months 1 to 12 and so months 1,3,5,7,8,10,12 have 31 days, months 4,6,9,11 have 30 days while February,

month 2, has 29 or 28 days. This depends on whether the year is a leap–year or not. Now the year is a leap

112

Page 118: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

year if it is: (divisible by 4 but not divisible by 100) or it is divisible by 400. So 2000 and 2004 were leap

years but 1900 was not.

Here is a function which does the job.

function days=monthdays(year,month)

% computes the number of days in a month for a given year

switch month

case {1,3,5,7,8,10,12}

days=31;

case {4,6,9,11}

days=30;

case 2

if (rem(year,4)==0 & rem(year,100)˜=0)|rem(year,400)==0

days=29;

else

days=28;

end

end

Check it out:

>> days=monthdays(1900,2)

days =

28.00

>> days=monthdays(2000,2)

days =

29.00

>> days=monthdays(2004,2)

days =

29.00

>> days=monthdays(2008,1)

days =

31.00

>> days=monthdays(2008,4)

days =

30.00

For a program that involves a lot of computation, we might want to allow the user to input the speed ofthe computer being used. Say the computation involves forming linspace(0,1,n) and we want to choosen higher for faster computers. We could include the code:

s=input(’computer speed =? 0 = slow, 1 = medium, 2= fast’);

switch s

case 0

n=100

case 1

n=500

case 2

n=1000

otherwise

n=200

end

to do the job.

113

Page 119: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

5.5.1 Exercise

[1] The sequence:

p1;

q

1Cp

1;

r

1Cq

1Cp

1; � � �

is a monotonically increasing sequence which converges to the golden ratio: 1Cp

52

. Write a program,called gold.m which prompts for a tolerance, r , and then computes the terms of the sequence untilthey are changing by less than r . Typical dialogue:

>> gold

r = .001

1.000000000000

1.414213562373

1.553773974030

1.598053182479

1.611847754125

1.616121206508

1.617442798527

1.617851290610

the golden ratio is:

1.618033988750

Modify the program, calling it gold2.m, to contain an infinite loop which allows the user to simply

rerun gold with a different tolerance. Typical output:

>> gold2

r = .01

1.000000000000

1.414213562373

1.553773974030

1.598053182479

1.611847754125

1.616121206508

the golden ratio is:

1.618033988750

another? 1=yes, 0=no 1

r = .001

1.000000000000

1.414213562373

1.553773974030

1.598053182479

1.611847754125

1.616121206508

1.617442798527

1.617851290610

the golden ratio is:

1.618033988750

another? 1=yes, 0=no 0

114

Page 120: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

[2] Two armies, X; Y are in battle. Let:

� x.n/ = the number of X -army soldiers on day n of battle;

� y.n/ = the number of Y -army soldiers on day n of battle;

� a = the number of Y -army soldiers killed per X -army soldier per day;

� b = the number of X -army soldiers killed per Y -army soldier per day.

Thenx.nC 1/ D x.n/ by.n/

y.n C 1/ D y.n/ ax.n/

is a pair of difference equations which model the battle.

(a) Write a program, called battle1.m, which prompts for initial values of x; y as well as the kill

rates: a; b and computes the values of x.n/; y.n/ until the battle is over. You need to decide on

a sensible definition of what is meant by a battle being over. The graph of y versus x should

then be plotted. Typical dialogue is:

Input:

>> battle1

Simulates a battle between two armies.

Here we have the simple model:

x(n+1) = x(n) -by(n)

y(n+1) = y(n) -ax(n)

Investigate the outcomes for various values of a,b,x(0),y(0)

________________________________________________________________

initial size of x army = 100000

initial size of y army = 200000

Now for the kill rates.

Typically, these rates are in the order of .01,

in other words, about 1 enemy kill per 100 friendly soldiers.

________________________________________________________________

number of y-army soldiers killed per 1-army soldier = .002

number of x-army soldiers killed per 2-army soldier = .001

Output:

The winner is the Y army with 141333 soldiers remaining after 625 days

115

Page 121: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

0 2 4 6 8 10

x 104

0

0.2

0.4

0.6

0.8

1

1.2

1.4

1.6

1.8

2x 10

5

initial x = 100000 x−kill rate = 0.0200

initial y = 200000 y−kill rate = 0.0100

Conventional Battle

(b) Now suppose that the armies are reinforced daily. Modify the equations above and call theprogram battle2.m. Sample dialogue:

>> battle2

Simulates a conventional war between two armies with replacements.

Here we have the simple model:

x(n+1) = x(n) -by(n) + r

y(n+1) = y(n) -ax(n) + s

Investigate the outcomes for various values of a,b,x(0),y(0)

________________________________________________________________

initial size of x army=10000

initial size of y army=20000

Now for the kill rates.

Typically, these rates are in the order of .01,

in other words, about 1 enemy kill per 100 friendly soldiers.

________________________________________________________________

number of y-army soldiers killed per 1-army soldier =.01

number of x-army soldiers killed per 2-army soldier =.005

Now for the replacement rates.

Typically, these rates are in the order of 10,

________________________________________________________________

number of x-army soldiers replaced per day = 40

number of y-army soldiers replaced per day = 4

116

Page 122: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

0 2000 4000 6000 8000 100000

0.2

0.4

0.6

0.8

1

1.2

1.4

1.6

1.8

2x 10

4

initial x = 10000 x−kill rate = 0.0100 x−reinforcement rate=40

initial y = 20000 y−kill rate = 0.0050 y−reinforcement rate=4 Conventional Battle with Replacements

Give some thought to what happens if the reinforcement rates are high enough in relation to the

kill rates to ensure that the armies both grow indefinitely. Your program should check for this

and terminate after a suitable number of iterations.

[3] A derangement of n objects is a rearrangement, or permutation, of the objects such that no object is

in its original position. For example

.1; 2; 3/! .3; 1; 2/ and .1; 2; 3/ ! .2; 3; 1/

are the only two derangements of three objects. Let dn denote the number of derangements of n

objects. Then it can be shown that

dn D .n 1/.dn 1 C dn 2/: .1/

It is easy to see that

d1 D 0 and d2 D 1: .2/

Since there are n! permutations of n objects, the probability, pn, of a derangement occuring if the

objects are shuffled randomly is given by

pn Ddn

n!: .3/

(a) Write a program, called der.n that prompts for a number N and then uses Equations 1, 2 and

3 to generate the numbers .pn W n 2 f1; : : : N g/ and plot the points f.n; pn/ W n 2 f1; : : :N gg.Typical output is:

117

Page 123: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> der

N = 12

prob. of derangement of 1 objects = 0.000000000

prob. of derangement of 2 objects = 0.500000000

prob. of derangement of 3 objects = 0.333333333

prob. of derangement of 4 objects = 0.375000000

prob. of derangement of 5 objects = 0.366666667

prob. of derangement of 6 objects = 0.368055556

prob. of derangement of 7 objects = 0.367857143

prob. of derangement of 8 objects = 0.367881944

prob. of derangement of 9 objects = 0.367879189

prob. of derangement of 10 objects = 0.367879464

prob. of derangement of 11 objects = 0.367879439

prob. of derangement of 12 objects = 0.367879441

0 2 4 6 8 10 120

0.05

0.1

0.15

0.2

0.25

0.3

0.35

0.4

0.45

0.5

Number of objects

Probability of a Derangement

Derangements

(b) It can be shown that

limn!1

pn D1

e:

Modify der.m, calling it der2.m, to identify the points on the graph where

ˇ

ˇ

ˇ

ˇ

pn 1

e

ˇ

ˇ

ˇ

ˇ

<1

10000

with a different marker. Here is typical output:

118

Page 124: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

0 2 4 6 8 10 120

0.05

0.1

0.15

0.2

0.25

0.3

0.35

0.4

0.45

0.5Derangements 2

Number of objects

Pro

ba

bili

ty o

f d

era

ng

em

en

t

[4] Starting with the points:

p1 D .0; 1/; p2 D .1; 1/; p3 D .1; 0/; p4 D .0; 0/

construct further points by the rule:

pk Dpk 4 C pk 3

2:

(a) Write a program, called midpoints.m, which prompts for the number, n, of points to plot andthen plots the n points. For example:

>> midpoints

number, n, of points = 12

find limit? 1=yes, 0=no 0

−0.5 0 0.5 1 1.5−0.5

0

0.5

1

1.5

(b) Modify the program, calling it midpoints2.m, to find the limit of the sequence. It is of theform: .m

7; n

7/, where m; n are for you to discover. Do this by setting a suitable tolerance, e,

and then computing the points while the length of the vector joining successive points is greaterthan e. Get the program to display the (approximation to the) limit in fractional form.

>> midpoints

number, n, of points = 12

find limit? 1=yes, 0=no 1

119

Page 125: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

limit is:

ans =

m/7 n/7

[5] The square wave has equation

f .x/ D�

1 if x < 0

1 if x � 0

The Fourier series for the square wave is a series of sine functions of the form:

1X

kD0

bk sin k t:

The coefficients, bk , are determined by an integral and, in this case, they are:

bk D2

k�

1 . 1/k�

:

The partial sums:

Sn.t/ Dn

X

kD1

bk sin k t

converge pointwise to the square wave on the interval Œ 1; 1�. Illustrate this by writing a program

called fseries1.m which prompts the user for a number, m, of terms and then plots the partial

sums, Sn, of the Fourier series, superimposed on the square wave, for n increasing to m. Typical

output is as follows:

−4 −3 −2 −1 0 1 2 3 4−1.5

−1

−0.5

0

0.5

1

1.5Partial sum of the Fourier series for the square wave

2 terms

120

Page 126: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

−4 −3 −2 −1 0 1 2 3 4−1.5

−1

−0.5

0

0.5

1

1.5Partial sum of the Fourier series for the square wave

6 terms

−4 −3 −2 −1 0 1 2 3 4−1.5

−1

−0.5

0

0.5

1

1.5Partial sum of the Fourier series for the square wave

14 terms

−4 −3 −2 −1 0 1 2 3 4−1.5

−1

−0.5

0

0.5

1

1.5Partial sum of the Fourier series for the square wave

36 terms

As a refinement, adjust the pause time between figures as n increases and make the length of the

pause decrease for large n.

121

Page 127: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

[6] Let pi denote the i th prime number. So p1 D 2; p2 D 3; � � � . MATLAB has the function primes

which returns the prime numbers.

For natural number n 2 N, let

n D p˛1

1 p˛2

2 � � �p˛mm

be the unique factorisation of n. For example,

6552 D 233271131 D p31p2

2p14p1

6

Define the function:

p.n/ D

8

ˆ

<

ˆ

:

0 if any ˛i is repeated

1 if m is odd

1 if m is even

and define p.1/ D 1. So p.1/ D 1; p.2/ D 1; p.3/ D 1; p.4/ D 0; p.5/ D 1; p.6/ D 1; � � � .For n 2 N define

M.n/ Dn

X

kD1

p.k/:

So

M.1/ D 1; M.2/ D 0; M.3/ D 1; � � � :

Write a script, called ??? which returns M.n/. Check that M.n/ �p

n for any n that you enter.

This may make us propose that this is true for all n. However, a number, n, has been found for which

this fails. The number is in the order of 101064:4

, way beyond the capacity of a computer to process

directly. (There are only about 1080 particles in the universe).

122

Page 128: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Chapter 6

Functions

6.1 Function m-files

MATLAB comes with hundreds of functions which enormously shorten the task of programming. It ispossible to define custom-made functions in MATLAB. We could call these function m-files. The procedureis similar to the one for making programs except that the first lines must be of the form:

function [output variables]=fname(input variables)

%documentation

statements

There may be any number of output and input variables and they may be scalars, vectors or matrices.So, if there are n output variables: y1; � � � ; yn and m input variables: x1; � � � ; xm, the first line will looklike:

function [y1, ..., yn]=fname(x1, ..., xm)

%documentation

For example :

function f=c2f(c)

%c2f.m

%A function which converts Centigrade to Fahrenheit

%

f=9/5*c+32;

Open a new M-file (File, new, M-file) and save it as c2f.m. Type in the above script and save it. Nowapply this function in the command window:

>> c2f(32)

ans =

89.6000

>> c2f(-23.4)

ans =

-10.1200

Our function accepts scalars, vectors and matrices. MATLAB automatically adjusts the output variable.

>> c2f([14:20])

ans =

57.2000 59.0000 60.8000 62.6000 64.4000 66.2000 68.0000

123

Page 129: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>>w=c2f([[0:9]’ , [10:19]’, [20:29]’])

w =

32.0000 50.0000 68.0000

33.8000 51.8000 69.8000

35.6000 53.6000 71.6000

37.4000 55.4000 73.4000

39.2000 57.2000 75.2000

41.0000 59.0000 77.0000

42.8000 60.8000 78.8000

44.6000 62.6000 80.6000

46.4000 64.4000 82.4000

48.2000 66.2000 84.2000

When a program m-file is run, it uses existing variables in the workspace or the ones created in the

program. The variables created are left behind and can, in this way, communicate with other programs and

functions. This has an advantage and a disadvantage.

The advantage is that variables are easily passed from program to program via the workspace. Further-

more, since the variables remain behind after the program has run, they can be inspected afterwards while

checking the program for errors.

The disadvantage is that the variables left behind in the workspace may be used in unexpected ways.

For example, say a program creates a variable r . If another program also uses a variable called r but in

this second program the programmer forgets to define it. The second program will compute on the basis of

the value of r left behind by the first program, which may not be what the programmer intended. There will

be no syntactical error, just incorrect output.When a function

[y1, ..., ym] = f(x1, ..., xn)

is invoked, MATLAB makes a copy of the variables: x1; � � � ; xn in its own workspace, performs the

required operations, returns the variables: y1; � � � ; ym to the user and then deletes the copies of the variables

x1; :::; xn. You may end a function with the statement: return to remind you of this. The input argument

list: x1; � � � ; xn is a list of names representing values that will be passed to the function. We could call the

names, x1; � � � ; xn dummy arguments, since they are just placeholders for the actual arguments that will be

passed to the function when it is invoked. Similarly, the output argument list: y1; � � � ; ym, is a list of names,

dummy arguments, that act as placeholders for the actual values that will be returned when the function has

been executed.To see this, clear all variables with:

>>clear

Now run our temperature conversion program, temp.m, that we wrote some time ago:

>>temp

Enter a temperature in Celsius = 25

25.00 degrees Celsius is 77.00 degrees Fahrenheit

Now check on the variables that are in the workspace:

>>whos

Name Size Bytes Class

c 1x1 8 double array

f 1x1 8 double array

out 2x1 16 double array

Grand total is 4 elements using 32 bytes

In contrast, a function leaves no trace of its dummy variables behind. Clear the variables, run thefunction: c2f and see what variables there are in the workspace:

124

Page 130: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> clear

>> c2f(25)

ans =

77

>> whos

Name Size Bytes Class

ans 1x1 8 double array

Grand total is 1 elements using 8 bytes

The only variable is ans, the dummy variables: c and f used in the function are gone.

6.2 Global Variables

If another program is to use the variable f or we want it to stay resident in the workspace, we declare it

to be a global variable. This is done before that variable is introduced in the function. The variable is then

in a common area of memory and is accessible to any function or program that also declares it as a global

variable. For example, the period, T , of a pendulum of length L is given by

T D 2�

s

L

g

where g is the acceleration due to gravity. Let’s make a function to compute T .

function T=pend(L)

%pend

%computes the period of a pendulum of length L

%needs g to be a global variable

global g

T=2*pi*sqrt(L/g);

To pass the variable g to the function it must be declared global in both the sender and the receiver. Inthis case we need to declare g to be global in the command window and the function. If not, you get awarning:

>> T=pend(20)

Warning: One or more output arguments not assigned during call to ’pend’.

Alright, alright already! We do the right thing and declare g to be a global variable in the workspacetoo:

>> global g

>> g=9.81;

Now the variable is passed on the function:

>> T=pend(20)

T =

8.9714

Beware! Global variables are the source of very curious and frustrating errors. They hang around inshared memory and any function or program that uses a variable of the same name uses the current value.It is better to include parameters in the function definition. For example

function T=pend(L,g)

%pend

T=2*pi*sqrt(L/g);

125

Page 131: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

Now the function gets g as input.

>> T=pend(20,9.81)

T =

8.9714

Let us write a function which accepts a list, A D ŒA1; � � � ; An�, of amplitudes, a list,

K D Œk1; � � �kn�, of frequencies a list t and plots

y Dn

X

iD1

Ai sin kit

The lists A and K must be of the same length so we include an error message in the program, whichterminates execution in the case of an error.

function y=sinsumf(A,K,t)

%sinsumf.m

%Calculates y=sum_i(A_i*sin(k_i*t))

%A: The amplitude vector,

%K: frequency vector,

%t: the time vector

%

if length(A)˜=length(K)

error(’A and k must be the same length’);

end

t=t(:)’%get t as a row vector

A=A(:);K=K(:);

AA=repmat(A,1,length(t));

y=sum(AA.*sin(K*t));

We can use this function in the command window:

>> t=linspace(0,2*pi,301);

>> y=sinsumf([10 5 1],[1 4 16],t);

>> hold on

>> plot(t,y)

>> plot([t(1) t(end)],[0 0]) %x axis

>> hold off

>>xlabel(’t’)

>>ylabel(’y’)

0 1 2 3 4 5 6 7−15

−10

−5

0

5

10

15

t

y

126

Page 132: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

6.3 Inline Functions

MATLAB has the facility to create “one-line” functions defined by a string. These are called inline func-

tions. For example suppose that we need to solve the equation

x3 x 10 D 0

accurate to within various tolerances. We find a first estimate of the root as follows:

>> f=inline(’xˆ3 -x -10’)

f =

Inline function:

f(x) = xˆ3 -x -10

>> f(2)

ans =

-4

>> f(3)

ans =

14

Since the function is continuous, we know that the root is between 2 and 3. We write a function to dothe job:

function [root, iter]=newton4(estimate, tol)

%newton4

%accepts an estimate of a root of the function

%f(x)=xˆ3-x-10

%and a tolerance and returns the root and the number of iterations

%required

%

if nargin<2

tol=eps;

end

x=estimate;

iter=0;

h=1;

while abs(h)>tol

h=-(xˆ3-x-10)/(3*xˆ2 -1);

x=x+h;

iter=iter+1;

end

root=x;

We have employed the MATLAB function nargin, which counts the number of input arguments, sothat the tolerance is set to eps if none is specified by the user. (>>help nargin) Here is how this functionresponds:

>>format long

>> newton4(2.5, .001)

ans =

2.30890732471029

Just the root is displayed.

>> [root,iter]=newton4(2.5,1e-10)

root =

2.30890731976509

iter =

5

127

Page 133: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

MATLAB also has the function nargout which we use in the next function. Suppose that we want to

write a function which accepts a list of marks and then returns:

� the sorted list or

� the sorted list and the mean or

� the sorted list, the mean and the standard deviation.

function [xs,m,s]=marks2(x)

%function [xs,m,s]=marks2(x)

%x is a list of marks

%xs is the sorted list

%m is the mean

%s is the standard deviation

%

xs=sort(x);

if nargout>1, m=mean(x);end

if nargout>2,s=std(x);

end

Note that the little if constructs here are written in one line with commas separating the statements. Here

is how the function responds.

>> x=[ 56 76 12 87 54 43];

>> xs=marks2(x)

xs =

12 43 54 56 76 87

>> [xs,m]=marks2(x)

xs =

12 43 54 56 76 87

m =

54.66666666666666

>> [xs,m,s]=marks2(x)

xs =

12 43 54 56 76 87

m =

54.66666666666666

s =

26.30335846744037

6.4 Evaluating Functions with FEVAL

If f is a function, then MATLAB has two ways of evaluating f at an argument x.

� The first way is by means of f .x/.

� The second way is by means of feval.f; x/.

For example

>> f=inline(’xˆ2*exp(-x)-1’)

f =

Inline function:

f(x) = xˆ2*exp(-x)-1

>> f(2)

128

Page 134: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

ans =

-0.45865886705355

>> feval(f,2)

ans =

-0.45865886705355

Similarly:

>> sin(pi/4)

ans =

0.70710678118655

>> feval(’sin’,pi/4)

ans =

0.70710678118655

Try it out on our marks2 function:

>> [xsort,mean,sdev]=feval(’marks2’,[34, 45, 56, 43, 87, 98, 12])

xsort =

12 34 43 45 56 87 98

mean =

53.57142857142857

sdev =

29.98253459853555

To convert a number to a string we use the MATLAB function num2str. To see this function in action:

>> clear

>> k=2;

>> ks=num2str(k)

ks =

2

>> whos

Name Size Bytes Class

k 1x1 8 double array

ks 1x1 2 char array

Grand total is 2 elements using 10 bytes

Here , k is a number while ks, which looks the same, but is a string.The feval function works on a string and the string can be defined beforehand. For example:

>> k=3;

>> str=[’(1/’, num2str(k), ’)*sin(’,num2str(k),’*x)’]

str =

(1/3)*sin(3*x)

>> f=inline(str)

f =

Inline function:

f(x) = (1/3)*sin(3*x)

>> y=feval(f,[pi/2, pi])

y =

-0.33333333333333 0.00000000000000

Here the string (character array), str, is a vector of the form:

[s1, s2, s3, s4, s5]

129

Page 135: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

where the five components s1, s2, s3, s4, s5 are strings.

The feval function can be used in the case where the input into the program consists of function names.

For example:

%trig.m

%plots the graphs of

%trig(k*t)

%for various k and various trig functions supplied by the user

%illustrates the use of feval and TEX labelling

%

clear all

f=input(’f= ’,’s’);

k=input(’k= ’);

k=num2str(k);

t=[-2*pi:pi/100:2*pi];

str=[f, ’(’, k, ’*x)’ ];

g=inline(str);

y=feval(g,t);

close

plot(t,y)

%set the labels on the x-axis using Tex symbols:

set(gca,’xtick’,[-2*pi:pi:2*pi])

%clear the xticklabels

set(gca,’xticklabel’,[])

%insert the Tex labels

text(-2*pi-.4,-1.05,’-2\pi’)

text(2*pi-.4,-1.05,’2\pi’)

text(-pi-.4,-1.05,’-\pi’)

text(pi-.4,-1.05,’\pi’)

text(0,-1.05,’0’)

title(sprintf(’%s\n’,str))

−1

−0.8

−0.6

−0.4

−0.2

0

0.2

0.4

0.6

0.8

1

−2π 2π−π π0

cos(3*x)

130

Page 136: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

6.5 Variable Numbers of Arguments

We will need to define functions which accept, or return, a variable number of input or output arguments.

This is achieved using the varargin and varargout functions. For example, let us write a function that

produces vectors, matrices or higher dimensional arrays of random numbers which are uniformly distributed

in the interval Œa; b/.

If d D .d1; � � � ; dn/, the function rand(d) produces an n-dimensional array, sizes specified by the di,

of numbers in the interval Œ0; 1/. For example:

>> m2=rand(2,3)

m2 =

0.3046 0.1934 0.3028

0.1897 0.6822 0.5417

>> m3=rand(2,3,4)

m3(:,:,1) =

0.1509 0.3784 0.8537

0.6979 0.8600 0.5936

m3(:,:,2) =

0.4966 0.8216 0.8180

0.8998 0.6449 0.6602

m3(:,:,3) =

0.3420 0.3412 0.7271

0.2897 0.5341 0.3093

m3(:,:,4) =

0.8385 0.3704 0.5466

0.5681 0.7027 0.4449

>> m4=rand(2,3,2,2)

m4(:,:,1,1) =

0.6946 0.7948 0.5226

0.6213 0.9568 0.8801

m4(:,:,2,1) =

0.1730 0.2714 0.8757

0.9797 0.2523 0.7373

m4(:,:,1,2) =

0.1365 0.8939 0.2987

0.0118 0.1991 0.6614

m4(:,:,2,2) =

0.2844 0.0648 0.5828

0.4692 0.9883 0.4235

We want a function which will accept any vector, d, and return rand(d). The first part of the help fileis:

>> help varargin

VARARGIN Variable length input argument list.

Allows any number of arguments to a function. The variable

VARARGIN is a cell array containing the optional arguments to the

function. VARARGIN must be declared as the last input argument

and collects all the inputs from that point onwards. In the

declaration, VARARGIN must be lowercase (i.e., varargin).

Here we see reference to a cell array. We will discuss cell arrays and structures later but for now it

is sufficient to understand that a cell array is an array whose elements hold data of different types. The

elements are specified using curly brackets as opposed to the round brackets for vectors.

For example

131

Page 137: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> c{1}=[1 2; 3 4]

c =

[2x2 double]

>> c{2}=3

c =

[2x2 double] [3]

>> c{3}=’string’

To see the whole cell array:

>> c

c =

[2x2 double] [3] ’string’

We are told that the cell, c, has three elements consisting of a 2 � 2 matrix of numbers, a number and astring. To see the first element:

>> c(1)

ans =

[2x2 double]

Using the round brackets reveals the type of data in the first element of the cell. To see the contents ofthe first cell element, we use the curly brackets:

>> c{1}

ans =

1 2

3 4

To see all of the contents of all of the elements we use the colon as for matrices:

>> c{:}

ans =

1 2

3 4

ans =

3

ans =

string

>> c{1}

ans =

1 2

3 4

So cfWg unpacks the cell contents. That’s all we need to know about cells for now.The MATLAB function clock produces a vector with the date and time which continually varies. For

example

>> format bank

>> clock

ans =

2002.00 8.00 22.00 15.00 27.00 47.43

The help file on the function rand tells us how to set the state of the random number generator, usingthe clock function, so that a different array of random numbers is generated each time:

RAND(’state’,sum(100*clock)) resets it to a different state each time.

There is also the function: setstate which does the same thing.Finally a simple scaling process changes the numbers from being distributed on Œ0; 1/ to Œa; b/. So,

putting these together, here is the function which produces variable size arrays of numbers uniformly dis-tributed in Œ0; 1/:

132

Page 138: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

function v=randu(a,b,varargin);

%randu.m

%computes a matrix of size varargin uniformly distributed in [a,b)

%usage: v=randu(a,b,matrixsize) (matrix may be multidimensional)

setstate%set the state: s=sum(100*clock);rand(’state’,s)

z=rand(varargin{:});%get the size of the array:

v=(b-a)*z+a;%scale and translate

For example

>> format short

>> randu(0,100,2,5,2)

ans(:,:,1) =

50.6147 29.8034 44.3719 33.1618 29.3733

98.2711 60.9498 10.4180 73.0067 22.2210

ans(:,:,2) =

29.6311 30.1545 97.9683 56.9009 69.3254

78.8330 9.1423 43.5336 18.8254 94.6035

The function returns an array with 2 pages of 2�5 matrices of numbers uniformly distributed in the interval Œ0; 100/.

6.6 Subfunctions

In a previous example we wrote a program which called a function. This meant that we had to write a separate function,

with its unique name, and save it somewhere in the path. This could lead to a proliferation of functions and, after a

while, we may be at a loss to find suitable function names. However, functions can have subfunctions defined within

them and these functions are visible only to the main function. Their names may be used in other functions with no

conflict of interest. For example, suppose that we need a function which returns the sum of the p -norms of the columns

of a matrix. Here is a function that does this. It has a subfunction which computes the p-norm of a vector. We may call

this function pnorm, even though we have a program with the same name.

function pn=pnormsum(M,p)

%returns the sum of the p-norms of the columns of a matrix

s=size(M);

pn=0; %pn is to be the required sum

for k=1:s(2)

pn=pn+pnorm(M(:,k),p);

end

%subfunction the p-norm of a vector

function n=pnorm(x,p)

switch p

case inf

n=max(x);

otherwise

n=(sum(abs(x).ˆp))ˆ(1/p);

end

6.7 Functions With No Arguments

The general form of a function is

[y1, ..., yn]=fname(x1, ..., xm)

but the function need not have any arguments at all. In other words, we may write a funtion of the form:

133

Page 139: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

function fname

%documentation

code

For example, a first order differential equation can always be written in the form:

dy

dtD f .t; y/

In this, f .t; y/ is a formula for the slope of the function y D y.t/. So if t 2 Œa; b� and y.a/ is known, then we can

find y D y.t/ as follows.

� Partition the interval into a suitably large number, n, of sub-intervals.

� Let the length of each sub-interval be h. Then

h Db a

n

and t D Œa W h W b� D Œt.1/; : : : ; t.nC 1/�.

� Let y D Œy.1/; : : : ; y.n C 1/� be the corresponding values of y D y.t/. Then knowing the initial value, y.1/,

the rest are calculated by lettingdy

dtD f .t; y/ D

y.t C h/ y.t/

h:

Thus

y.t C h/ D y.t/C hf .t; y/:

In other words, y.1/ D y.t.1// and for each k > 1

y.k C 1/ D y.k/C hf .t.k/; y.k//:

This simple-minded algorithm is called Euler’s Method and we can write a program to find y D y.t/ from the

initial value and the derivative function f .t; y/.

Suppose that the derivative is given bydy

dtD ry:

Now we write the function that calls on this function as a subfunction to evaluate the derivatives at the beginning

of each subinterval. So, in the main function we will use a loop to evaluate the derivatives:

y(1)=y0;

for k=2:n+1

y(k)=y(k-1)+h*feval(’f’,t(k-1),y(k-1),r);

end

Each computation calls on the derivative function:

function dydt=f(t,y,r)

dydt=r*y;

whose name is simply ’f’. MATLAB actually prefers to call functions by means of a function handle, which contains

all the information about the function. Type

help function_handle

for details. In this case the function is called by

y(k)=y(k-1)+h*feval(@f,t(k-1),y(k-1),r);

instead of ’f’. Of course, any legal name may be used to describe the derivative function and this name must be used

when calling the function. For example

y(k)=y(k-1)+h*feval(@deriv,t(k-1),y(k-1),r);

134

Page 140: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

function dydt=deriv(t,y,r)

dydt=r*y;

Here is the whole script:

function euler

disp(’solves dy/dt=r*y on the interval [a,b]’)

%n=number of subintervals of [a, b]

n=500;a=0;b=50;y0=5;r=.03;

close all

h=(b-a)/n;

t=[a:h:b];

y=zeros(1,length(t));

%numerical integration using Euler method

y(1)=y0;

for k=2:n+1

y(k)=y(k-1)+h*feval(@f,t(k-1),y(k-1),r);

end

plot(t,y)

title(sprintf(’Euler method with %d sub-intervals\n’,n))

xlabel(’t’); ylabel(’y’)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%derivative function

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function dydt=f(t,y,r)

dydt=r*y;

The advantage of this over a program is that we do not have to find a unique name for the derivative function. The

simple name: f can be used. A disadvantage is that variables are transient and cannot be examined using >>whos in

the command window, or by putting the pointer over the variable in the debugging window. It’s your choice.

6.8 Self–Referential Functions

We have seen examples of functions which have sub–functions which are called during computation. Is it possible to

define a function which calls itself? Amazingly, this can be done using an input variable: levels. If the function is of

the form f(x,levels), then f(x,0) is defined and then f(x,k) is defined in terms of f(x,k-1).

For example, we define a function: triangles(u,v,x,levels) such that

� triangles(u,v,w,0) draws a triangle with vertices at u,v,w:

>> triangles([0;0],[1;0],[.5;sqrt(3)/2],0)

135

Page 141: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

Triangles within triangles: level 0

� triangles(u,v,w,1) calls triangles(u,v,w,0) to draw three triangles within the first:

>> triangles([0;0],[1;0],[.5;sqrt(3)/2],1)

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

Triangles within triangles: level 1

� triangles(u,v,w,2) calls triangles(u,v,w,1) (which calls triangles(u,v,w,0) to drawthree triangles within the all of the previously drawn triangles:

>> triangles([0;0],[1;0],[.5;sqrt(3)/2],2)

136

Page 142: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

Triangles within triangles: level 2

� triangles(u,v,w,k) calls triangles(u,v,w,k-1) (which calls triangles(u,v,w,k-2...) to

draw three triangles within all of the previously drawn the triangles

Here is a function which achieves this:

function triangles(u,v,w,level)

%vertices at 2-vectors u,v,w

if level==0

x=[u(1);v(1);w(1);u(1)];

y=[u(2);v(2);w(2);u(2)];

hold on

plot(x,y)

else

triangles(u,(u+v)/2,(u+w)/2,level-1);

triangles((u+v)/2,v,(v+w)/2,level-1);

triangles((u+w)/2,(v+w)/2,w,level-1);

end

axis(’equal’)

title(sprintf(’Triangles within triangles: level %d\n’,level))

hold off

When this function is invoked at the command line, it is necessary to close all figures beforehand.Inserting the line close all within the script closes the previously drawn triangles. For example,

>> close all

>> triangles([0;0],[1;0],[.5;sqrt(3)/2],5)

137

Page 143: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

Triangles within triangles: level 5

6.9 Pseudocode

The first time that a script is called in a session it is parsed (analysed syntactically). This takes a fewmicroseconds for the type of scripts that we have encountered up to now. But for larger scripts, which callon many other scripts, it is possibly worth pre-parsing them. Suppose that we want to parse cour euler.mThis is achieved with the command:

pcode -inplace euler

This parses euler.m and saves it in the form of pseudocode as euler.p in the same directory as

euler.m. Also, the file euler.p cannot be read in the editor. So use pcode if you would like the code in

the script to be hidden from view.

6.9.1 Exercise

[1] The updown function is defined by

f .x/ D(

x2

if x is even,

3x C 1 if x is odd.

Write a function, called udf.m which performs the actions of the updown function. Test drive it:

>> udf(3)

ans =

10

>> udf(ans)

ans =

5

>> udf(ans)

ans =

16

>> udf(ans)

ans =

8

>> udf(ans)

ans =

4

>> udf(ans)

138

Page 144: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

ans =

2

>> udf(ans)

ans =

1

Try it out on a number of starting values and you will find that it always eventually produces a value

of 1 (after which it oscillates: 1; 4; 2; 1; 4; 2; � � � ). Does this always happen? In other words, for any

starting value, x, does the recursively defined sequence above always converge to 1? Write scripts

which investigates this. For example, updown.m prompts for the first value, computes subsequent

values until 1 is attained, displays the sequence and plots the sequence points. The program could

also output interesting information such as:

� the number of terms;

� the growth ration: (max value)/(initial value);

� the down ratio: (number of terms � initial term)/(number of terms)

For example

>> updown

first value = 345

The sequence is:

345

1036

518

.

.

.

5

16

8

4

2

1

The number of terms is: 126

The growth ratio: max/initial is: 26.75942

The down ratio, sum(x<=I)/#terms, is: 0.4920634921

0 20 40 60 80 100 120 1400

1000

2000

3000

4000

5000

6000

7000

8000

9000

10000

position in sequence, starting value: 345

value

The Updown Sequence

This simple example unearths a great mystery. There is no proof that the updown function always

converges to 1. If the updown script is run millions of times and terminates each time it still does not

prove that it will terminate every time. The problem is worthy of further investigation.

139

Page 145: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

Modify the updown function, calling it, updown2.m, to include a menu from which the user candecide whether to display the terms of the sequnce or not. (>>help menu). For example:

mv=menu(’click on your option: ’,’display sequence’,’do not display’);

switch mv

case 1;

display=1;

case 2;

display=0;

end

Now use a decison tree based on the value stored in the variable display. The shrink ratio is given

by (number of terms)/(initial term) and you are invited to think of other interesting statistics. Write

a script, called updown3.m, which accepts as input a list of starting values for the updown function

and returns corresponding lists of interesting ratios such as shrink, growth and down ratios defined

above. Here is sample output:

0 100 200 300 400 500 600 700 800 900 10000

50

100

150

200

250

300

350

400

growth factor = max/I

I=initial value0 100 200 300 400 500 600 700 800 900 10000

0.5

1

1.5

2

2.5

3

3.5

4

4.5

shrink ratio = #terms/initial term

I=initial value

0 100 200 300 400 500 600 700 800 900 10000

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

1

down ratio = sum(x<=I)/n

I=initial value

[2] MATLAB has its own function, primes, which produces a list of the primes less than or equal to a

given number. (>>help primes). So, for example :

>> primes(20)

ans =

2 3 5 7 11 13 17 19

>> See also FACTOR, ISPRIME.

The factor function is also useful.

140

Page 146: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>>help factor

FACTOR Prime factors.

FACTOR(N) returns a vector containing the prime factors of N.

This function uses the simple sieve approach. It may require large

memory allocation if the number given is too big. Technically

it is possible to improve this algorithm, allocating less

memory for most cases and resulting in a faster execution

time. However, it will still have problems in the worst

case, so we choose to impose an upper bound on the input number

and error out for n > 2ˆ32.

For example:

>> factor(234688)

ans =

2 2 2 2 2 2 19 193

This expresses the fact that

234688D 261911931:

Write a function, called factorise.m, whose usage is:

factorise(n) = M

where M(1, :) is a list of the prime factors of n and M(2, :) is a list of the powers of the correspondingfactors. For example

>> factorise(12345648)

ans =

2 3 7 29 181

4 1 2 1 1

[3] Modify the function randu to obtain a function which produces a random array of integers in aspecified closed interval. The first lines should be of the form:

function v=randui(a,b,varargin);

%randui.m

% computes a matrix of size varargin

% true random integers, k, such that a<=k<=b

% uniformly distributed in [a, b]

%

Check your output with the hist function which bins the values in a specified number of bins. Forexample

>> v=randui(0,2,1,6)

v =

0 1 2 2 1 0

>> v=randui(0,2,1,6)

v =

1 2 2 0 2 2

>> v=randui(0,2,1,6)

v =

0 1 1 2 2 1

The function is producing values in the closed interval Œ0; 2�. Now let’s see if the distribution is

uniform. The function hist(v,n) distributes the values in the vector v into n bins.

141

Page 147: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> v=randui(0,9,1,1000);

>> close all

>> hist(v,10)

0 1 2 3 4 5 6 7 8 90

20

40

60

80

100

120

try again with a larger number of values:

>> v=randui(0,9,1,100000);

>> close all

>> hist(v,10)

0 1 2 3 4 5 6 7 8 90

2000

4000

6000

8000

10000

12000

Seems OK.

[4] Write a script, called euler2.m, which uses the euler method to solve the Logistic Equation:

dy

dtD ry.M y/

where are r and M are parameters.

[5] The Euler Method uses the slope f .t; y/ to compute the next value of y using:

ykC1 D yk C hf .tk ; yk/

It would be better to use the average slope:

f .tk ; yk /C f .tkC1 ; ykC1/

2:

Ja well, no fine! This uses the very thing, namely ykC1, that we are trying to find. But here is a

cunning plan. Use the Euler Method to predict an estimate, pkC1, to ykC1 and then use the slope

f .tk ; yk/C f .tkC1 ; pkC1/

2

142

Page 148: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

to compute ykC1. This is known as the Predictor-Corrector Method or the Improved Euler Method.

Write scripts, called pc.m, pc2.m analogous to euler.m, euler2.m, which use the Predictor-

Corrector Method to solve the differential equations:

dy

dtD ry

anddy

dtD ry.M y/:

[6] If x D .x1; � � � ; xn/ then the mean (average), Nx, is defined by

Nx D 1

n

nX

iD1

xi

and the standard deviation, sx , of x is defined by

sx D

v

u

u

u

t

nP

iD1

.xi Nx/2

n 1

If x is a list of measurements of the same quantity, then the quantity is usually quoted in the form

Nx ˙ sx:

So, for example, if the pH of a solution is measured six times and the measurements are

x D .6:71; 6:75; 6:74; 6:77; 6:73; 6:74/

then

Nx D 6:74; sx D 0:02:

So the pH is quoted as being 6:74˙ 0:013. Write function, called av.m which accepts a list, x, ofnumbers and returns Nx and sx . For example

>> [xm xs]=av([6.71 6.75 6.78 6.73 6.80 ])

xm =

6.7540

xs =

0.0365

[7] Write a function, called myperms, which lists all of the permutations of a vector v.

>> myperms([1,2])

ans =

1 2

2 1

>> myperms([1,2,3])

ans =

1 1 3

1 2 2

2 1 3

2 2 1

3 1 2

3 2 1

143

Page 149: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>> myperms([1,2,3,4])

ans =

1 1 1 4

1 1 2 3

1 2 1 4

1 2 2 2

1 3 1 3

1 3 2 2

2 1 1 4

2 1 2 3

2 2 1 4

2 2 2 1

2 3 1 3

2 3 2 1

3 1 1 4

3 1 2 2

3 2 1 4

3 2 2 1

3 3 1 2

3 3 2 1

4 1 1 3

4 1 2 2

4 2 1 3

4 2 2 1

4 3 1 2

4 3 2 1

MATLAB does have a function, perms which does this. But see if you can improve on this by

getting myperms(v), with length(v)=n, to call myperms(u) n times where u varies over n vectors

of length n 1.

[8] You may find this a bit challenging butit is worth the effort to try. Write a function, called line-

fractal such that

� linefractal(u,v,0) draws a line between points u; v in the plane;

� linefrcatal(u,v,1) erects a triangle on the mid–third of the previously drawn line

� linefractal(u,v,k) erects triangles on the mid–thirds of all previously drawn lines.

For example:

>> close

>> clear all

>> linefractal([0;0],[1;0],0)

>> close

>> clear all

>> linefractal([0;0],[1;0],1)

produces:

144

Page 150: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1−1

−0.8

−0.6

−0.4

−0.2

0

0.2

0.4

0.6

0.8

1

linefractal at level 0

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

−0.2

−0.1

0

0.1

0.2

0.3

0.4

0.5

linefractal at level 1

>> close

>> clear all

>> linefractal([0;0],[1;0],2)

>> close

>> clear all

>> linefractal([0;0],[1;0],5)

produces:

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

−0.2

−0.1

0

0.1

0.2

0.3

0.4

0.5

linefractal at level 2

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

−0.2

−0.1

0

0.1

0.2

0.3

0.4

0.5

linefractal at level 5

145

Page 151: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

[9] Write a function, called polyfractal, of the form polyfractal(sides, level), which callslinefractal to draw a line-fractal of the given level on each the sides of a regular polygon with thegiven number of sides. For example,

>>polyfractal(4,0)

>>polyfractal(4,1)

>>polyfractal(4,2)

>>polyfractal(4,4)

produces:

−1 −0.8 −0.6 −0.4 −0.2 0 0.2 0.4 0.6 0.8 1−1

−0.8

−0.6

−0.4

−0.2

0

0.2

0.4

0.6

0.8

1

polyfractal at level 0

−1 −0.5 0 0.5 1−1

−0.8

−0.6

−0.4

−0.2

0

0.2

0.4

0.6

0.8

1

polyfractal at level 1

−1 −0.5 0 0.5 1−1

−0.8

−0.6

−0.4

−0.2

0

0.2

0.4

0.6

0.8

1

polyfractal at level 2

−1 −0.5 0 0.5 1−1

−0.8

−0.6

−0.4

−0.2

0

0.2

0.4

0.6

0.8

1

polyfractal at level 4

6.10 The Mandelbrot Set

Let c 2 C and let

f W C ! C; z 7! z2 C c:

We use the function f to generate a sequence Mc by letting

Mc.1/ D c D 02 C c; Mc.2/ D Mc.1/2 C c; Mc.3/ D Mc.2/2 C c; � � �

146

Page 152: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

In other words,

Mc.1/ D c; Mc.k C 1/ D Mc.k/2 C c for k D 1; 2; � � �

or

Mc D .c; c2 C c; .c2 C c/2 C c; � � � /

We call Mc the orbit of c.

We encountered this in the introduction, where we saw that for some c the orbit Mc diverged and for

some c the orbit was bounded. The Mandelbrot Set, M is defined to be the set of all c 2 C such that the

orbit Mc is bounded. In other words,

M D fc 2 C W Mc is bounded.g

Here it is, a strange beetle shaped object with amazing convolutions. There are convolutions within the

convolutions and deep inside we find replicas of the entire set. Copies of itself within itself - it is self-

similar.

−2 −1.5 −1 −0.5 0 0.5

−1

−0.8

−0.6

−0.4

−0.2

0

0.2

0.4

0.6

0.8

1

The curious thing is that for a number c, the orbit Mc may be bounded but for c0 right close to it the

orbit Mc0 is not bounded. Bear in mind what you are looking at when you peer at this wonderful set. It is a

region in the complex plane for which the orbits of a simple function are bounded.

The contourf function allows us to easily plot the set. It produces a filled contour:

>> help contourf

CONTOURF Filled contour plot.

CONTOURF(...) is the same as CONTOUR(...) except that the contours are filled.

Areas of the data at or above a given level are filled.

Areas below a level are either left blank or are filled by a lower level.

NaN’s in the data leave holes in the filled contour plot.

C = CONTOURF(...) returns contour matrix C as described in CONTOURC

and used by CLABEL.

[C,H,CF] = CONTOURF(...) also returns a column vector H of handles to PATCH

objects and the contour matrix CF for the filled areas.

The UserData property of each object contains the height value for each contour.

147

Page 153: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

Example:

z=peaks; contourf(z), hold on, shading flat

[c,h]=contour(z,’k-’); clabel(c,h), colorbar

See also CONTOUR, CONTOUR3, CLABEL, COLORBAR.

Experiment with this function. For example

>> x=[-2:.4:2];

>> y=x;

>> [X,Y]=meshgrid(x,y);

>> z=sin(X)+cos(Y);

>> contourf(x,y,z);

−2 −1.5 −1 −0.5 0 0.5 1 1.5 2−2

−1.5

−1

−0.5

0

0.5

1

1.5

2

Here is a script that generates the Mandelbrot set and allows us to probe its depths. We compute the

orbits for each c in a region. Of course we use vectorised commands to achieve this. Then we find the

absolute values of the last elements of each orbit. Finally we use the contourf function to plot these. The

function gplot allows the user to provide input by means of crosshairs. It puts crosshairs on the figure and

when you right-click at the point defined by the crosshairs that point is taken as input.

%mandelbrot

close all

clear all

%profile on -history

n=501;

maxit=100;

hw=waitbar(0,’computing ...’);

%the Mandelbrot whole set

x=linspace(-2.1,0.6,n);

y=linspace(-1.1,1.1,n);

[X,Y]=meshgrid(x,y);

c=complex(X,Y);

z=c;

for k=1:maxit

z=z.ˆ2+c;

waitbar(k/maxit)

end

148

Page 154: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

close(hw);

zmax=1000000;

a=abs(z);

contourf(x,y,a<zmax)

%while loop to allow s to delve into the set

repeat=1;

while repeat==1

disp(’define the centre of the next plot with the crosshairs’);

p=ginput(1);

xp=p(1);

yp=p(2);

dx=(max(x)-min(x))/4;

dy=(max(y)-min(y))/4;

x1=xp-dx;x2=xp+dx;

y1=yp-dy;y2=yp+dy;

close all

%hw=waitbar(0,’computing ...’);

x=linspace(x1,x2,n);

y=linspace(y1,y2,n);

[X,Y]=meshgrid(x,y);

c=complex(X,Y);

z=c;

for k=1:maxit;

z=z.ˆ2+c;

h=waitbar(k/maxit);

end

a=abs(z);

close(h);

close all

contourf(x,y,a<zmax)

% %printing to a specified file using functional form of PRINT

% pr=input(’print? 1 or 0 ’)

% if pr==1

% printname=input(’printname= ’,’s’);

% printfile=[’C:\data\courses\mathprog\2003mathprog\’,printname,’.eps’];

% print(’-deps’,’-r600’,printfile);

% end

repeat=input(’repeat? ’);

end

%profile viewer

Note the use of the waitbar function which shows the user how the computation is progressing. Output:

If you zoom into the Mandelbrot set you will see very curious structures.

There is “Sea Horse Alley” around . :8; :2/

149

Page 155: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

−1.05 −1 −0.95 −0.9 −0.85 −0.8 −0.75

0.05

0.1

0.15

0.2

0.25

0.3

−0.9 −0.85 −0.8 −0.75

0.14

0.16

0.18

0.2

0.22

0.24

0.26

Furthermore, as you probe deeper and deeper into the set you find the original beetle-shaped set again.

−0.5 −0.4 −0.3 −0.2 −0.1 0 0.1

0.6

0.65

0.7

0.75

0.8

0.85

0.9

0.95

1

1.05

1.1

−0.3 −0.25 −0.2 −0.15 −0.1 −0.05 0

0.65

0.7

0.75

0.8

0.85

0.9

Probe into this and you will find it again. It is self-similar at all levels. Within the small beetle we find

seahorse alley again. Such a set is called a fractal.

−0.26 −0.25 −0.24 −0.23 −0.22 −0.21 −0.2 −0.19 −0.18

0.67

0.68

0.69

0.7

0.71

0.72

0.73

f

−0.25 −0.245 −0.24 −0.235 −0.23 −0.225 −0.22 −0.215 −0.21

0.7

0.705

0.71

0.715

0.72

0.725

0.73

Experiment with this script, descend into another world.

6.11 The Julia Set

Investigate the function

f W C ! C; z 7! z2 C c

with fixed c and z varying through some rectangle. So for each z in some rectangle we compute the orbit

J.z; c/ D .z; z2 C c; .z2 C c/2 C c; � � � /:

150

Page 156: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

We keep c fixed and, for this c, The Julia Set, Jc is defined to be the set of z such that J.z; c/ is bounded.

In other words,

Jc D fz 2 C W J.z; c/ is boundedg:Write a script to generate the Julia set for given c. Sample output with c D :123C i � :745:

−2 −1.5 −1 −0.5 0 0.5 1 1.5 2−2

−1.5

−1

−0.5

0

0.5

1

1.5

2

Julia Set Jc with c=−0.123+i0.745

Once you have got the basic script working, extend it, as we did for the Mandelbrot set, to allow probing

searches. There is one Mandelbrot set but there are infinitely many Julia sets. Let c D 0 and you will get

what you should expect. For some values of c the set Jc is not very interesting but for other values the set

has amazing complexity. Explore.

6.12 Animation

There are two ways to produce animated plots with MATLAB.

� An n–frame movie is a sequence M D .M.k/ W k 2 f1 W ng/ of n figures. Typically, the figures,

M.k/, are produced and saved in a for–loop. The k th figure, M.k/, is captured with the command

M(k)=getframe and then the movie, M , can be replayed with the command movie(M).

� By default the plot function erases old plots when new ones are drawn. This can be changed by

setting the erasemode to none or background in the same way as the marker options are set. So

new plots are superimposed in the same figure window. Then, in a for–loop, the data being plotted

can be set and drawn, using drawnow. This produces a moving point which either leaves a trail of

drawn points behind it or which moves alone.

Here are the details with examples.

Movies

Suppose that we want to plot the curves

y D sin . k�

5 / sin x

for x 2 Œ0; 2�� and for increasing k . We set x–axis and then, for each k we generate the y -values, plot andsave the figure.

151

Page 157: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

%animate1: animation using movie

%

x=[0:.01:2*pi];

for j=1:25

y=sin(j*pi/6)*sin(x);

plot(x,y);

%ensure that all plots have the same axis.

axis([0,2*pi,-2,2]);

M(j)=getframe;

end

save M

disp(’Hit any key to play the movie’)

pause

movie(M);

As another example, suppose we want to plot the surface:

z D 1C cos.˛.x2 C y2//

for increasing ˛ and watch the surfaces changing as ˛ changes.The following script does the job:

%animate1a.m

%example of movie generation

%page 201 in Higham

%

clear all

close all

th=[0:pi/40:2*pi];

r=[0:.01:4];

[T,R]=meshgrid(th,r);

[x,y]=pol2cart(T,R);

%create the movie with 21 frames

for k=1:11

%generate z-values

z=1+cos(k/10*(x.ˆ2+y.ˆ2));

%plot the surface

surfl(x,y,z);

xlabel(’x’);ylabel(’y’);zlabel(’z’)

axis tight

%capture the picture

M(k)=getframe;

end

disp(’hit any key to see the movie’)

pause

movie(M)

Comet-like Animation

When a curve is plotted we obtain a line–object (a curve) in an axis-system, within a figure which is withinthe computer screen. The computer is called the root-object and it has the figure as a child. The figurealso has children, including the axes–object. The axes object has children, including the line–object. All ofthese have properties which can be set. To illustrate:

152

Page 158: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

>>R=1;

>>k=2;

>>n=4;

>>t=linspace(0, n*2*pi, 500*n + 1);

>>x = R*t-k*sin(t);

>>y = R - k*cos(t);

>>close all

>>xlim([0,n*2*pi]);

>>ylim([-2*k,2*k]);

>> plot(x,y)

The plot function produces a line–object. To see this:

>> h=findobj

h =

0

1.0000

151.2452

152.2457

>> get(h,’type’)

ans =

’root’

’figure’

’axes’

’line’

The vector h is a handle which describes (to MATLAB ) the properties of the line object that we havegenerated. These properties can be set. To see the options:

>> set(h(4))

ans =

Color: {}

EraseMode: {4x1 cell}

LineStyle: {5x1 cell}

LineWidth: {}

Marker: {14x1 cell}

MarkerSize: {}

MarkerEdgeColor: {2x1 cell}

MarkerFaceColor: {2x1 cell}

XData: {}

YData: {}

ZData: {}

ButtonDownFcn: {}

and many more.We will set the erasemode:

>> set(h(4),’erasemode’)

[ {normal} | background | xor | none ]

and the xdata and ydata at each plot. There are four options for erasemode and the one we need is none.

This is done in the same way as setting the markerstyle. The strategy is to plot a single point, set the

erasemode to none, and then, in a loop, plot the other points by changing the xdata and ydata.

%animate3 uses ’erasemode’ set to ’none’ and drawnow for animation

%plots the cycloid graph

echo on

%Plots a cycloid after prompting for the following information,

153

Page 159: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

%R = radius of the wheel

%k = distance of the point from the centre of the wheel

%n = number of revolutions

%

echo off

close all

R = input(’Enter a value for R = ’);

k = input(’Enter a value for k = ’);

n = input(’Enter the number of revolutions = ’);

%initialise a time vector

t=linspace(0, n*2*pi, 500*n + 1);

x = R*t-k*sin(t);

y = R - k*cos(t);

%plotting

%add new points without erasing the current figure

p=plot(x(1),y(1),’.’,’erasemode’,’none’);

%old point erased and new one plotted: produces moving point

%p=plot(x(1),y(1),’.’,’erasemode’,’background’);

xlim([0,n*2*pi]);

ylim([-2*k,2*k]);

hold on

for j=2:length(t)

%redraws the point by resetting the xdata and ydata properties

set(p,’xdata’,x(j),’ydata’,y(j));

set(p,’markersize’,1);

drawnow

%pause(.01);

end

title(’Cycloid’)

xlabel(sprintf(’R=%1.2f, k=%1.2f \n ’,R,k))

ylabel(’y’)

plot(x,y)

hold off

6.13 Sound

The MATLAB function sound operates on a vector z to produce the sound that the waveform z would

produce. The duration in seconds, d.z/ of the vector z is given by

d.z/ D length

8192:

Try:

>> t=0:.1*pi:250*pi;

>>x=0:.1*pi:1000*pi;

>> p=zeros(1,200);

>> s=sin(t);

>> s2=sin(4*x/5);

>> sound([s p s p s p s2])

154

Page 160: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

The vector s is the sound of a pure sine wave with duration 25018192

seconds, and p is a pause of length200

8192seconds. Beethoven would be impressed. Carrying on with this:

>> s3=sin(8/9*t);

>> s4=sin(3/4*x);

>> sound([s p s p s p s2 p p p p p s3 p s3 p s3 p s4])

Now Beethoven would be really impressed.

155

Page 161: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Part II

Numerical Methods

156

Page 162: Rhodes University...Contents I The MATLAB ComputationalEnvironment iii 1 Introduction 1 1.1 About MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

AM 2.2 NUMERICAL METHODS MHB 2009

In the first part of this course we developed the computational skills necessary to implement numerical

algorithms. We can now write programs and functions which accept input from the user or read it from an

Excel file, produce output to the screen, write to an Excel file or produce graphical output. This is enough

to proceed.

Numerical Methods or Numerical Analysis is a huge, rapidly growing area of mathematical enquiry. It

is born of the need to solve real–world problems and it is the birthplace of a great deal of pure mathematics.

A problem is posed, mathematical tools are used to solve the problem and then these mathematical tools are

studied. For example, a real–world problem might require that we solve a system of linear equations. This

leads us into the study of matrices and linear transformations. This, in turn, provokes the study of normed

vector spaces and so on. In this course, we investigate some of the numerical methods required to solve the

most commonly occurring problems. Further techniques and more theoretical investigations will be studied

in the third–year course. We will constantly refer the prescribed book by Kharab and Guenther, which will

also be prescribed for the third–year course. Our objective will be to develop procedures and algorithms,

implemented by MATLAB scripts, which solve problems. We will not allow ourselves to be distracted by

the many alternative methods mentioned in Kharab and many important topics will have to be omitted in

this course. This is not a comprehensive course - it is just an appetiser.

157