MAS1801: MATLAB - Welcome - Andrew...

52
MAS1801: MATLAB Andrew W. Baggaley [email protected]

Transcript of MAS1801: MATLAB - Welcome - Andrew...

Page 1: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

MAS1801: MATLAB

Andrew W. [email protected]

Page 2: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

http://abag.wikidot.com

Licensed under the Creative Commons Attribution-NonCommercial 3.0 Unported License (the“License”). You may not use this file except in compliance with the License. You may ob-tain a copy of the License at http://creativecommons.org/licenses/by-nc/3.0. Unlessrequired by applicable law or agreed to in writing, software distributed under the License isdistributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,either express or implied. See the License for the specific language governing permissions andlimitations under the License.

Page 3: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

Contents

1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

1.1 About these notes 51.1.1 Assesment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

1.2 Introduction 6

1.3 Getting started 6

1.4 Vectors and matrices in MATLAB 11

1.5 Complex numbers 13

2 Easter Eggs & Script Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

2.1 Easter Eggs 15

2.2 Script Files 15

3 Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

3.1 Basic Plotting 17

3.2 Vectors and Arrays 203.2.1 Column vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203.2.2 Vectorised arithmatic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

3.3 Vector products 22

3.4 Further plotting 233.4.1 Subplots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243.4.2 Hard copy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

3.5 Plotting surfaces 25

3.6 Making movies 26

Page 4: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

4 Loops and if-statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

4.1 Introduction 29

4.2 Logicals 30

4.3 If. . . then . . . else 32

4.4 Further intrinsic functions 334.4.1 Summing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334.4.2 Rounding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344.4.3 max and min . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

5 Random numbers & Code timing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

5.1 Generating uniform random numbers 37

5.2 Other distributions 38

5.3 Code timing 38

6 Function m-files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

6.1 Introduction 41

6.2 Reading Data 44

7 Solving ODEs with MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

7.1 Anonymous functions 47

7.2 1st-order ODEs 48

7.3 2nd-order ODEs 49

Page 5: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

About these notesAssesment

IntroductionGetting startedVectors and matrices in MATLABComplex numbers

1. Introduction

1.1 About these notes

Welcome to the MATLAB component of MAS1801. Many important mathematical, physicaland engineering problems cannot be solved with analytic (pen and paper) techniques. Even if wecan find an analytic solution can be found it is often difficult to visualise it without the help ofadvanced plotting routines. In this course we shall learn some of the basic (and more advanced)aspects of the programming and visualisation package MATLAB. You cannot learn to programby watching someone else do it. Hence you are expected to work through these notes yourselfduring the 3 hour computing sessions. Don’t be afraid to go off on tangents if something interestsyou and you would like to go beyond the notes, google (other search engines are available – butnot as good!) and the wider internet is your friend here.

1.1.1 Assesment

Scattered throughout the notes, at the end of key chapters are “Chapter Exercises” (look out forthe black boxes), this forms part of the in-course assessment for the module. Each of these is tobe submitted through NESS (see figure 1.1 below for guidance) by 5pm on the Friday of eachweek in the following formats:

Page 6: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

6 Chapter 1. Introduction

Exercise 1 Friday 17th Nov Take a screenshot of your MATLAB command win-dow clearly showing your working and solution tothe problem. Submit this image to NESS

Exercise 2 Friday 24th Nov Submit 3 files 1) A figure (jpeg format) showingthe intersection of y = cos(x) and y = x (use in-sert → textbox to add the coordinates of the pointof intersection to the figure) 2) a screen shot ofthe MATLAB script file you have written to plotf (x,y) = exp{−x2− y2} 3) A jpeg image of this sur-face to NESS.

Exercise 3 Friday 1st Dec Submit 4 files, screenshots of the two scripts, onewhich gives an approximate solutions to the Baselproblem another which plots π(x)

x/ lnx and two jpeg im-ages of the graphical output of both scripts.

Exercise 4 Friday 8th Dec Submit 2 files 1) a screenshot of the script to com-pute the mean of a set of numbers 2) a figure (jpeg)showing the comparison between the exact pdf of anormal distribution, and one estimated from a largerandom sample (drawn from the same distribution).

The red boxes provide extension questions, which are not to be submitted, but should beattempted. These questions will challenge your knowledge of the material presented in thechapter and help to consolidate knowledge.

1.2 Introduction

• MATLAB is an interactive system for doing numerical computations.• A numerical analyst called Cleve Moler wrote the first version of MATLAB in the 1970s.

It has since evolved into a successful commercial software package.• MATLAB relieves you of a lot of the mundane tasks associated with solving problems nu-

merically.This allows you to spend more time thinking, and encourages you to experiment.• MATLAB makes use of highly respected algorithms and hence you can be confident about

your results.• Powerful operations can be performed using just one or two commands.• You can build up your own set of functions for a particular application.• Excellent graphics facilities are available, and the pictures can be inserted into LATEX and

Word documents.

1.3 Getting started

MATLAB can be opened on university machines by going to the start menu→ scientific software→MATLAB. It is also accessible through the remote access system https://ras-gateway.ncl.ac.uk/vpn/index.html. Once opened you will be greeted with a larger graphical userinterface, with a number of separate windows, which are indicated in figure 1.2.

MATLAB can be used in a number of different ways or modes; as an advanced calculatorin the calculator mode, in a high level programming language mode and as a subroutine calledfrom a C-program. More information on the first two of these modes is provided by these notes.When used in calculator mode all MATLAB commands are entered to the command line (in thecommand window) from the keyboard at the “command line prompt” indicated with >>.

Page 7: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

1.3 Getting started 7

Figure 1.1: A guide to NESS submission of the assessed work.

Page 8: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

8 Chapter 1. Introduction

This section lists the script and function

files in your working folder

Workspace shows the names and values of the variables defined

by the user

Command History lists the copy of the commands you have run on the command

window

Command Window is the main window that you write your

commands

Figure 1.2: The MATLAB command window.

Type help at any time to exit from MATLAB. Extensive documentation is available, eithervia the command line by using the ‘help topic’ command (see below) or via the internet.

As mentioned, MATLAB has many capabilities, such as the fact that one can write programsmade up of MATLAB commands. The simplest way to use MATLAB, though, is as an interactivecomputing environment (essentially, a very fancy graphing calculator). You enter a commandand MATLAB executes it and returns the result. Here is an example:

>> clear>> 2+2ans =

4

You can assign values to variables for later use:

>>x=2x =

2

The variable x can now be used in future calculations:

>>x^2ans =

4

Page 9: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

1.3 Getting started 9

At any time, you can list the variables that are defined with the who command:

>> whoYour variables are:

ans x

If you enter a variable that has not been defined, MATLAB prints an error message:

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

To clear a variable from the workspace, use the clear command:

>>who

Your variables are:

ans x

>>clear x

who

Your variables are:

ans

To clear all of the variables from the workspace, just use clear by itself, try it now.As we start to write more complicated programs it is very useful to be able to add comments

to our code. These are readable annotations in the source code of our ‘program’, which areignored by MATLAB.

>> a = 1; %I am setting a to be 1>> b = 2; %and be to be 2>>c = a^2 + b^2 %what is 1^2+2^2c=

5

Note these examples have introduced a few new concepts. The semicolon (;) was used in the finalexample to suppress MATLAB writing everything to the screen (which gets a little annoying).We have also met our first inbuilt function ^n is the syntax for f (x) = xn. MATLAB knows theelementary mathematical functions: trigonometric functions, exponentials, logarithms, squareroot, and so forth. Here are some examples:

sqrt(2)ans =

1.4142

sin(pi/3)ans =

0.8660

Page 10: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

10 Chapter 1. Introduction

exp(1)ans =

2.7183

log(ans)ans =

1

A couple of remarks about the above examples: MATLAB knows the number π , whichis called pi. Computations in MATLAB are done in floating point arithmetic by default. Forexample, MATLAB computes the sine of π/3 to be (approximately) 0.8660 instead of exactly√

3/2. A complete list of the elementary functions can be obtained by entering “help elfun”:

>>help elfunElementary math functions.

Trigonometric.sin - Sine.sind - Sine of argument in degrees.sinh - Hyperbolic sine.asin - Inverse sine.asind - Inverse sine, result in degrees.asinh - Inverse hyperbolic sine.cos - Cosine.cosd - Cosine of argument in degrees.cosh - Hyperbolic cosine.acos - Inverse cosine.acosd - Inverse cosine, result in degrees.acosh - Inverse hyperbolic cosine.tan - Tangent.tand - Tangent of argument in degrees.tanh - Hyperbolic tangent.atan - Inverse tangent.atand - Inverse tangent, result in degrees.atan2 - Four quadrant inverse tangent.atanh - Inverse hyperbolic tangent.sec - Secant.secd - Secant of argument in degrees.sech - Hyperbolic secant.asec - Inverse secant.asecd - Inverse secant, result in degrees.asech - Inverse hyperbolic secant.csc - Cosecant.cscd - Cosecant of argument in degrees.csch - Hyperbolic cosecant.acsc - Inverse cosecant.acscd - Inverse cosecant, result in degrees.acsch - Inverse hyperbolic cosecant.cot - Cotangent.cotd - Cotangent of argument in degrees.coth - Hyperbolic cotangent.acot - Inverse cotangent.acotd - Inverse cotangent, result in degrees.acoth - Inverse hyperbolic cotangent.hypot - Square root of sum of squares.

Exponential.exp - Exponential.

Page 11: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

1.4 Vectors and matrices in MATLAB 11

expm1 - Compute exp(x)-1 accurately.log - Natural logarithm.log1p - Compute log(1+x) accurately.log10 - Common (base 10) logarithm.log2 - Base 2 logarithm and dissect floating point number.pow2 - Base 2 power and scale floating point number.realpow - Power that will error out on complex result.reallog - Natural logarithm of real number.realsqrt - Square root of number greater than or equal to zero.sqrt - Square root.nthroot - Real n-th root of real numbers.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.

For more information about any of these elementary functions, type “help <function_name>”.For a list of help topics like “elfun”, just type “help”. There are other commands that formpart of the help system; to see them, type “help help”.

1.4 Vectors and matrices in MATLABThe default type for any variable or quantity in MATLAB is a matrix—a two-dimensional array.Scalars and vectors are regarded as special cases of matrices. A scalar is a 1 by 1matrix, while avector is an n by 1 or 1 by n matrix. A matrix is entered by rows, with entries in a row separatedby spaces or commas, and the rows separated by semicolons. The entire matrix is enclosed insquare brackets. For example, I can enter a 3 by 2 matrix as follows:

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

1 23 45 6

Page 12: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

12 Chapter 1. Introduction

Here is how I would enter a 2 by 1 (column) vector:

>>x=[1;-1]x =

1-1

A scalar, as we have seen above, requires no brackets:

>>a=4a =

4

A variation of the who command, called whos, gives more information about the definedvariables:

>>whosName Size Bytes Class Attributes

A 3x2 48 doublea 1x1 8 doubleans 1x1 8 doublex 2x1 16 double

The column labeled “size" gives the size of each array; you should notice that, as I mentionedabove, a scalar is regarded as a 1 by 1 matrix (see the entry for a, for example). You can alsoget the size of a specific variable, for example try size(A). MATLAB can perform the usualmatrix arithmetic. Here is a matrix-vector product:

>>A*xans =

-1-1-1

Here is a matrix-matrix product:

>>B=[-1 3 4 6;2 0 1 -2]B =

-1 3 4 62 0 1 -2

>>A*Bans =

3 3 6 25 9 16 107 15 26 18

MATLAB signals an error if you attempt an operation that is undefined:

>>B*A??? Error using ==> mtimesInner matrix dimensions must agree.

Page 13: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

1.5 Complex numbers 13

>>A+B??? Error using ==> plusMatrix dimensions must agree.

1.5 Complex numbersMATLAB can easily deal with complex numbers, we use the syntax 1i to denote the imaginaryunit i, for example

>>1+1ians =

1.0000 + 1.0000i

or,

>>1+2ians =

1.0000 + 2.0000i

Of course we can create a vector (or array) of complex numbers:

>> C=[1+1i 1-1i 1 1i]

C =

1.0000 + 1.0000i 1.0000 - 1.0000i 1.0000 + 0.0000i 0.0000 + 1.0000i

We can then take advantage of some of MATLAB’s intrinsic functions to find out some of theproperties of these numbers. For example:

>> conj(C)

ans =

1.0000 - 1.0000i 1.0000 + 1.0000i 1.0000 + 0.0000i 0.0000 - 1.0000i

>> abs(C)

ans =

1.4142 1.4142 1.0000 1.0000

>> angle(C)

ans =

0.7854 -0.7854 0 1.5708

Page 14: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

14 Chapter 1. Introduction

We could even get very fancy (some may say silly)!

>> D=abs(C).*exp(1i*angle(C))

D =

1.0000 + 1.0000i 1.0000 - 1.0000i 1.0000 + 0.0000i 0.0000 + 1.0000i>> D==C

ans =

1 1 1 1

If you do not understand any aspect of this make sure you google the commands used - or checkwith one of us!

Exercise 1

Given

A =

1 0 30 1 51 −2 4

, B =

−1 1 −32 2 −3−1 −2 4

Compute the matrix product C = A×B. If the vector f = (1,−1,1)T , then use MATLABto find the vector x which satisfies

Ax = f.

Hint: help inv may prove useful! Note the T means to take the transpose of the vector,if you have not met this before google it.

Extension Task

Given

A =

1 −2 4−1 −4 36 6 6

Find both the determinant and subsequently the inverse of A analytically. Check youranswers using MATLAB.

Page 15: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

Easter EggsScript Files

2. Easter Eggs & Script Files

2.1 Easter Eggs

Working through these notes is probably at points a little dry, sorry sometimes that is just theway of things. However now is time for a little break. MATLAB is full of easter eggs1 try someof the following:

>> lorenz>>fifteen>>load handel>>sound(y,Fs)>>life %this one is fascinating - we will explore this more later in the ...

course>>why %do this more than once>>xpbombs>>x=[-2:.001:2];>>y=(sqrt(cos(x)).*cos(200*x)+sqrt(abs(x))-0.7).*(4-x.*x).^0.01;>>plot(x,y);

Some are mathematical, some are just daft. Give the mathematical ones (I trust you can judge) agoogle.

2.2 Script Files

Script files are ordinary ASCII (text) files that contain MATLAB commands. It is essentialthat such files have names having an extension .m (e.g., myfile.m) and, for this reason, they arecommonly known as m-files. The commands in this file may then be executed using

>> myfile

Note: the command does not include the file name extension .m. Script files are created with thebuilt-in editor (it is possible to change to your favourite editor in the Preferences window), forexample try:

>> edit plot_the_function_below.m

1An Easter egg is an intentional inside joke, hidden message, or feature in a computer program.

Page 16: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

16 Chapter 2. Easter Eggs & Script Files

As mentioned, any text that follows % on a line is ignored. This enables descriptive commentsto be included. It is possible, via a mouse menu, to highlight commands that appear in the“Command History” pane to create a script file. Cut and paste can be used to copy individualcommands from the Command History into a script file. In the next chapter we shall lookat plotting. Once you have understood the basic mechanics of plotting put together a samplem-file to plot some elementary functions, for example make a script to plot f (x) = sin(x)+cos(4x), x ∈ [0,2π].

Page 17: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

Basic PlottingVectors and Arrays

Column vectorsVectorised arithmatic

Vector productsFurther plotting

SubplotsHard copy

Plotting surfacesMaking movies

3. Plotting

3.1 Basic Plotting

Two-dimensional graphics are particularly easy to understand: If you define vectors x and yof equal length (each with n components, say), then MATLAB’s plot command will graph thepoints (x1,y1),(x2,y2), . . . ,(xn,yn) in the plane and connect them with line segments. Here is anexample:

>>x=[0,0.25,0.5,0.75,1] ;>>y=[0,1,0,1,0] ;plot(x,y)

Which produces the following (admittedly uninspiring) figure. Another (perhaps more useful)example is given by the following set of commands:

>>x=linspace(0,1,6) ;>>y=sin(2*pi*x) ;plot(x,y)

Two features of MATLAB have been used here to generate the (rough) plot of y= sin(2πx), x∈[0,1]. First of all, the command linspace creates a vector with linearly spaced components—essentially, a regular grid on an interval. (Mathematically, linspace creates a finite arithmeticsequence.) To be specific, linspace(a,b,n) creates the (row) vector whose components area,a+h,a+2h, . . . ,a+(n−1)h, where h = (b−a)/(n−1). The second feature that makes iteasy to create graphs is the fact that all standard functions in MATLAB, such as sine, cosine,exp, etc., are vectorized. A vectorized function f , when applied to a vector x, returns a vector y(of the same size as x) with ith component equal to f (xi).

Of course, the previous figure is not a very good plot of y = sin(2πx), as the grid is toocoarse. Next we shall create a finer grid and thereby obtain a better graph of the function.

>>x=linspace(0,1,100) ;>>y=sin(2*pi*x) ;plot(x,y)

Page 18: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

18 Chapter 3. Plotting

There are still a few deficiencies with this figure. MATLAB default font size is puny, let’s makeit bigger:

>>set(gca,'FontSize',16)

Page 19: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

3.1 Basic Plotting 19

(gca returns the handle to the current axes for the current figure, but don’t worry about this now).Now we can label up the axis,

>>xlabel('x','FontSize',16)>>ylabel('y=sin(2\pi x)','FontSize',16)

Much better! linspace is not the only way to generate a vector, we can also use colons notation:This is a shortcut for producing row vectors:

>> 1:4ans =

1 2 3 4>> 3:7ans =

3 4 5 6 7>> 1:-1ans =

[]

More generally a : b : c produces a vector of entries starting with the value a, incrementing bythe value b until it gets to c (it will not produce a value beyond c). This is why 1:-1 produced theempty vector []. Whilst we are discussing generating vectors it is sensible to also discuss theirmanipulation.

Page 20: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

20 Chapter 3. Plotting

3.2 Vectors and ArraysBeing able to plot functions is heavily dependent on having a good understanding of vectors andarrays in MATLAB. Let’s define a vector:

>> r5 = [1:2:6, -1:-2:-7]r5 =

1 3 5 -1 -3 -5 -7

To get the 3rd to 6th entries:

>> r5(3:6)ans =

5 -1 -3 -5

To get alternate entries:

>> r5(1:2:7)ans =

1 5 -3 -7

What does r5(6:-2:1) give? See help colon for a fuller description.

3.2.1 Column vectorsAs we have seen, these have similar constructs to row vectors except that entries are separated by; or “new- lines”:

>> c = [ 1; 3; sqrt(5)]c=

1.00003.00002.2361

>> c2 = [345]c2 =

345

We can convert a row vector into a column vector (and vice versa) by a process called transposingwhich is denoted by '.

>> c, c'c=1.0003.0002.2362

ans =

1.0000 3.0000 2.2361

Page 21: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

3.2 Vectors and Arrays 21

If x is a complex vector, then ' gives the complex conjugate transpose of x:

>>x = [1+3i, 2-2i]

x =

Column 1

1.0000 + 3.0000i

Column 2

2.0000 - 2.0000i

>>x'

ans =

1.0000 - 3.0000i2.0000 + 2.0000i

3.2.2 Vectorised arithmatic

The basic arithmetic operations have vectorised versions in MATLAB. For example, I canmultiply two vectors component-by-component using the “.*” operator. That is, z=x.*y sets zi

equal to xiyi. Here is an example:

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

123

>>y=[2;4;6]y =

246

>>z=x.*yz =

28

18

The “./” operator works in an analogous fashion. There are no “.+” or “.-” operators, sinceaddition and subtraction of vectors are defined component-wise already (check this). However,there is a “.^” operator that applies an exponent to each component of a vector.

>>xx =

123

>>x.^2

Page 22: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

22 Chapter 3. Plotting

ans =149

Finally, scalar addition is automatically vectorised in the sense that a+x, where a is a scalar andx is a vector, adds a to every component of x. The vectorised operators make it easy to graph afunction such as f (x) = x/(1+ x2). Here is how it is done:

>>x=linspace(-5,5,41);>>y=x./(1+x.^2);>>plot(x,y)

3.3 Vector productsJust like skinning a cat, there’s more than one way to multiply two vectors. Here we shall discusstwo of the more common vector products. The inner (dot or scalar) product is an algebraicoperation that takes two equal-length sequences of numbers (i.e. two vectors) and returns a singlenumber (a scalar). The dot product of two vectors x = [x1,x2, . . . ,xn] and y = [y1,y2, . . . ,yn] isdefined as

x ·y =n

∑i=1

xiyi = x1y1 =+x2y2 + . . .+ xnyn

Page 23: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

3.4 Further plotting 23

It is easy to compute the dot product of two vectors in MATLAB:

>>clear all>>x=[1 2 3];>>y=[3 2 1];>> xydot=dot(x,y)

xydot =

10

The cross product (or vector product) is an operation on two vectors in three-dimensional space,denoted by the symbol × (or ∧/⊗). The cross product x×y of two linearly independent vectorsx and y is a vector that is perpendicular to both (and therefore normal to the plane containingthem), with a length (magnitude) dependent on the magnitude of the vectors x and y, and theangle between them:

x×y = xysinθn

where θ is the angle between x and y, x and y are the magnitudes of vectors, and n is a unitvector perpendicular to the plane containing a and b in the direction given by the right-hand rule(google it). Again it is straighforward to compute the cross product of two vectors in MATLAB:

>>clear all>>x=[1 2 3];>>y=[3 2 1];>> z=cross(x,y)

z =

-4 8 -4

Why doesn’t the following give the same answer?

>> z=cross(y,x)

z =

4 -8 4

3.4 Further plottingIt may not always be appropriate to plot solid lines, for example we can just graph the pointsthemselves, or connect them with dashed line segments. Here are examples:

>>plot(x,y,'.')>>plot(x,y,'o')>>plot(x,y,'--')

To see more examples (how to change line colours and the different plotting symbols that can beused type help plotting. Try plotting your favourite functions using different lines stylesand symbols.It is not much harder to plot two curves on the same graph. For example, we can plot y = x2 andy = x3 together:

Page 24: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

24 Chapter 3. Plotting

>>x=linspace(-1,1,101);>>plot(x,x.^2,x,x.^3)

As is often the case there is typically more than one way to skin a cat. The followingcommands give essentially the same result:

>>x=linspace(-1,1,101);>>plot(x,x.^2)>>hold on>> plot(x,x.^3)>>hold off

hold retains the current plot when adding new plots, try repeating the commands above butomitting the hold statements.

3.4.1 SubplotsThe graphics window may be split into an mxn array of smaller windows into each of which wemay plot one or more graphs. The windows are counted 1 to mn row-wise, starting from the topleft. Note hold can be used on the current subplot.

Page 25: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

3.5 Plotting surfaces 25

>>clear all>>clc>>x=linspace(0,2*pi,100);>> subplot(221), plot(x,sin(3*pi*x))>> xlabel('x'),ylabel('sin 3 \pi x')>> subplot(222), plot(x,cos(3*pi*x))>> xlabel('x'),ylabel('cos 3 \pi x')>> subplot(223), plot(x,sin(6*pi*x))>> xlabel('x'),ylabel('sin 6 \pi x')>> subplot(224), plot(x,cos(6*pi*x))>> xlabel('x'),ylabel('cos 6 \pi x')

subplot(221) (or subplot(2,2,1)) specifies that the window should be split into a 2 x 2array and we select the first subwindow.

We often need to “zoom in” on some portion of a plot in order to see more detail. Clickingon the Zoom in or Zoom out button on the Figure window is simplest but one can also use thecommand

>> zoom

Pointing the mouse to the relevant position on the plot and clicking the left mouse button willzoom in by a factor of two. This may be repeated to any desired level. Clicking the right mousebutton will zoom out by a factor of two. Holding down the left mouse button and dragging themouse will cause a rectangle to be outlined. Releasing the button causes the contents of therectangle to fill the window; zoom off turns off the zoom capability.

3.4.2 Hard copy

To obtain a printed copy select Print from the File menu on the Figure toolbar. Alternativelyone can save a figure to a file for later printing (or editing). A number of formats are available(use help print to obtain a list). To save the current figure in Encapsulated Colour PostScript(EPS) format, issue the MATLAB command

print -depsc fig1.eps

which will save a copy of the image in a file called fig1.eps.

print -djpeg90 figb.jpg

will save figure 4 as a jpeg file figb.jpg at a quality level of 90. It should be borne in mind that,despite its name, the “print” command does not send the file to a printer.

3.5 Plotting surfaces

A surface is defined mathematically by a function of two independent variables f (x,y), such thatfor each value of (x,y) we compute the ‘height’ of the function by

z = f (x,y).

In order to plot this we need to specify the ranges of both x and y, for example we take 2≤ x≤ 4and 1≤ y≤ 3. This gives a square in the (x,y)-plane. Next, we need to choose a grid on thisdomain, i.e. how fine or course or resolution is. Here we take a grid with intervals 0.5 in eachdirection for illustration. The x and y coordinates of the grid lines are

Page 26: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

26 Chapter 3. Plotting

>>clear all>>x = 2:0.5:4; y = 1:0.5:3;

We then construct the grid with meshgrid:

>>[X,Y] = meshgrid(x, y);

If we wish to plot the surface defined by the function

f (x,y) = (x−3)2− (y−2)2, 2≤ x≤ 4, 1≤ y≤ 3.

Then we can use the following commands

>> [X,Y] = meshgrid(2:.2:4, 1:.2:3);>> Z = (X-3).^2-(Y-2).^2;>> surf(X,Y,Z)

This may look a little rough, use google or MATLAB’s search function to find out whatshading interp does in the next set of commands:

>> [X,Y] = meshgrid(2:.02:4, 1:.02:3);>> Z = (X-3).^2-(Y-2).^2;>> surf(X,Y,Z)>>shading interp

Use the following webpage http://uk.mathworks.com/help/matlab/surface-and-mesh-plots-1.html to reproduce some of the other figures displayed here. Can you find other ways of plottinga function of two independent variables?

3.6 Making moviesOften it is very useful to create a movie, for example if you have a solution to an equation thatevolves in time. The following example will show how to use the commands

getframemoviemovie2avi

to make a movie in MATLAB, look at the help files for the above commands. Here we are goingto make a movie of a wave propagating through a membrane. First, we clear all the variables andclose all the open figures. We then make a 2D surface that represents the membrane.

clear; close all;

x=linspace(0,1,100);[X,Y] = meshgrid(x,x);

The command getframe will save the content of the currently selected figure as a frame, whichwe use to create a movie in the following loop.

Page 27: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

3.6 Making movies 27

N=100; % Number of framesfor i = 1:N

% Example of plotZ = sin(2*pi*(X-i/N)).*sin(2*pi*(Y-i/N));surf(X,Y,Z)

% Store the frameM(i)=getframe(gcf); % leaving gcf out crops the frame in the movie.

end

The variable M is the movie. To view the movie in MATLAB you can use the command

movie(M)

Various options can be passed to movie. For example, to change the frame rate, look at the helpfiles for more information. To save the movie to file you can use the command

movie2avi(M,'WaveMovie.avi');

which saves the movie as the file WaveMovie.avi in the current working directory. Againthere are many options you can pass to movie2avi to change the frame rate or the type ofcompression used. Look at the help files for more information.

Page 28: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

28 Chapter 3. Plotting

Exercise 2

Draw graphs of the functions

y = cosx, y = x, x ∈ [0,2π]

on the same window. Use the zoom facility to determine the point of intersection of thetwo curves (and, hence, the root of x = cosx) to two significant figures. Write your ownscript to plot (you pick how) the following function:

f (x,y) = exp{−x2− y2} −2≤ x≤ 2, −2≤ y≤ 2.

Extension Task I

We can also plot vector fields in MATLAB. A vector field is a field such that every pointin space (or a subset of space) is associated with a vector (of a given dimension). Vectorfields are often used to model, for example, the speed and direction of a moving fluid(the air in this room say), or the strength and direction of some force (such as gravity)as it changes from point to point. In MATLAB we can define a 2D-vector field in thefollowing way:

[x,y] = meshgrid(0:0.2:2,0:0.2:2);u = cos(x).*y;v = sin(x).*y;

We can visualise the field using the quiver command

figurequiver(x,y,u,v)

Now visualise the following three dimensional vector field u(x,y,z) = (ux,uy,uz):ux = sin(y)+cos(z), uy = sin(z)+cos(x), uz = sin(x)+cos(y), x,y,z∈ [−π,π]

Extension Task II

Pick a few of your favourite elementary functions ( f (x) = ex,sin(x),cos(x), ln(1+x), . . .)compute the Maclaurin series of the function, up to and including x5 terms. Using thehold on command show how the approximation to the function improves as more termsare included.

Page 29: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

IntroductionLogicalsIf. . . then . . . elseFurther intrinsic functions

SummingRoundingmax and min

4. Loops and if-statements

4.1 IntroductionThere are many occasions that we want to repeat a segment of code a number of different times;to do this we use a loop, more specifically in MATLAB we can use a for-loop. A standard forloop has the form

>> for counter = 1:20%do something

end

which repeats the code as far as the end with the variable counter=1 the first time, counter=2the second time, and so on. This can be seen by running:

>> for counter = 1:20counter

end

More generally

>> for counter = [23 11 19 5.4 6]%insert nobel prize winning science

end

repeats the code with counter=23 the first time, counter=11 the second and so on.As an example the Fibonnaci sequence starts off with the numbers 0 and 1, then succeeding

terms are the sum of its two immediate predecessors. Mathematically, f1 = 0, f2 = 1 and

fn = fn−1 + fn−2,n = 3,4,5, . . .

Test the assertion that the ratio fn−1/ fn of two successive values approaches the golden ratio(√

5−1)/2 = 1.6180 . . .

Page 30: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

30 Chapter 4. Loops and if-statements

>>clear all>>F(1)=0;F(2)=1;>>for i = 3:20

F(i) = F(i-1) + F(i-2);end

>>plot(1:19, F(1:19)./F(2:20),'-o')>>hold on>>xlabel('n','FontSize',16)>>plot([0 20], (sqrt(5)-1)/2*[1,1],'--')>>legend('Ratio of terms f_{n-1}/f_n','(5^{1/2}-1)/2')>> set(gca,'FontSize',16)

Note the use of the legend command to add a legend to the figure to improve its clarity.When an loop is running ctrl + c (just ctrl and c ) will exit any loop. You have to do this in

the command window when the loop is running (i.e. you do not have the >> prompt and itshows ’busy’ on the status bar– which is usually the case when MATLAB is performing anyoperation.. ). This can be useful if you make a mistake and end up trapped in an infinite loop(https://en.wikipedia.org/wiki/Infinite_loop.

4.2 LogicalsMATLAB represents true and false by means of the integers 0 and 1.true = 1, false = 0

If at some point in a calculation a scalar x, say, has been assigned a value, we may make certainlogical tests on it:

>> x==2 %is x equal to 2?>> x>2 %is x greater than 2?>> x<2 %is x less than 2?

Page 31: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

4.2 Logicals 31

>> x> =2 %is x greater than or equal to 2?>> x< =2 %is x less than or equal to 2?

Pay particular attention to the fact that the test for equality involves two equal signs ==

>> x = pix=

3.1416>> x > 3, x ==pi, x==3ans =

1ans =

1ans =

0

When x is a vector or a matrix, these tests are performed elementwise:

>> x=[1 1 1 ; 1 2 1]

x =

1 1 11 2 1

>> x==1

ans =

1 1 11 0 1

>> x==2

ans =

0 0 00 1 0

>> x<1

ans =

0 0 00 0 0

Page 32: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

32 Chapter 4. Loops and if-statements

We may combine logical tests, as in

>> x==1 & x<2

ans =

1 1 11 0 1

>> x==1 | x< =2

ans =

1 1 11 1 1

As one might expect, & represents and, and (not so clearly) the vertical bar | means or; also ∼means not as in ∼= (not equal), ∼(x>0), etc. Have a play around with these and make surethey make sense.

4.3 If. . . then . . . else

This allows us to execute different commands depending on the truth or falsity of some logicaltests. To test whether or not πe is greater than, or equal to, eπ :

>> a = pi^exp(1); c = exp(pi);>> if a > = c

b = sqrt(a^2 - c^2)end

so that b is assigned a value only if a ≥ c. There is no out put, so we deduce that πe ≤ eπ . Amore common situation is

>>if a> =cb = sqrt(a^2 - c^2)else b=0endb=

0

which ensures that b is always assigned a value and confirming that a < c. A more extendedform is

>> if a > = cb = sqrt(a^2 - c^2)

elseif a^c > c^ab = c^a/a^celse

b = a^c/c^aend

b=0.2347

Page 33: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

4.4 Further intrinsic functions 33

4.4 Further intrinsic functionsThere are a variety of ways of rounding and chopping real numbers to give integers, which isoften useful in many situations:

4.4.1 Summingsum applied to a vector adds up its components (as in sum(1:10)).

>> clear all>> x=[1 3 4 6]

x =

1 3 4 6

>> y=[-1 2 -3 5]

y =

-1 2 -3 5

>> sum(x)

ans =

14

>> sum(x.*y)

ans =

23

>> dot(x,y)

ans =

23

Note dot is the intrinsic function to compute the dot product between two vectors. For a matrix,it adds up the components in each column and returns a row vector. sum(sum(A)) then sumsall the entries of A.

>> A=[1:3; 4:6; 7:9]

A =

1 2 34 5 67 8 9

>> s=sum(A)

s =

12 15 18

>> ss=sum(sum(A))

Page 34: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

34 Chapter 4. Loops and if-statements

ss =

45

>> s2=sum(A,2)

s2 =

61524

>> ssq=sum(A.^2)

ssq =

66 93 126

Use help sum to see why sum(A,2) gave the result it did.

4.4.2 Rounding

>> x=[-4 1 1 4]*pi

x =

Columns 1 through 3

-12.5664 3.1416 3.1416

Column 4

12.5664

>> round(x)

ans =

-13 3 3 13

>> fix(x)

ans =

-12 3 3 12

>> floor(x)

ans =

-13 3 3 12

>> ceil(x)

ans =

-12 4 4 13

Page 35: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

4.4 Further intrinsic functions 35

>> sign(x)

ans =

-1 1 1 1

>> rem(x,3)

ans =

Columns 1 through 3

-0.5664 0.1416 0.1416

Column 4

0.5664

4.4.3 max and min

These functions act in a similar way to sum. If x is a vector, then max(x) returns the largestelement in x

>> x = [1.3 -2.4 0 2.3]x=1.3000 -2.4000 0

>> max(x), max(abs(x))ans =

2.3000ans =

2.4000>> [m, j] = max(x)m=

2.3000j=

4

When we ask for two outputs, the first gives us the maximum entry and the second the index ofthe maximum element. For a matrix, A, max(A) returns a row vector containing the maximumelement from each column. Thus, to find the largest element in A, we use max(max(A)). minworks in exactly the same manner but obviously returns the minimum values.

Page 36: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

36 Chapter 4. Loops and if-statements

Exercise 3

i) The Basel problem is a problem in mathematical analysis, first posed by Pietro Mengoliin 1644 and subsequently solved by Euler in 1734. Simply stated:

∑n=1

1n2 =

π2

6

First write a MATLAB script to test the theorem. Can you prove it analytically?

ii) MATLAB includes an intrinsic function isprime to test if a number is prime. Theprime counting function, π(x), returns the number of primes less than or equal to x(e.g. π(10) = 4 because there are four prime numbers less than 10). Write a MATLABfunction which computes π(x) from x = 10 to 105, use this to demonstrate that

limx→∞

π(x)x/ lnx

= 1

Extension Task

You manage a very successful company which sells something (whatever you want). Youdecide to change the arrangements for the commission your sales team earns. Rather thanpay a flat rate of commission, perhaps it is fairer to pay more commission to those salespeople who have worked harder and sold more items. You decide to pay commission asfollows:

• Sales from £1 to £49 earns 10% commission• Sales between £50 to £99 earns 15% commission• If they sell over £100 they earn £20 % commission

The following tale contains this month’s sales figures. Write a script to automaticallycompute each persons commission.

Name Sales (£)

Terry 123Debbie 53Sally 43Gary 24Harry 265Molly 110Holly 82Toby 67

In a similar vein write a script to automate the calculation of Stamp Duty Land Taxhttps://www.gov.uk/stamp-duty-land-tax/residential-property-rates.

Page 37: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

Generating uniform random numbersOther distributionsCode timing

5. Random numbers & Code timing

5.1 Generating uniform random numbersThe function rand(m,n) produces an mxn matrix of random numbers, each of which is in therange 0 to 1. rand on its own produces a single random number.

>> clear all>> x=rand(100,1);>> plot(1:100,x)

rand generates numbers from a uniform distribution such that X ∼U (0,1), this can be seenby plotting histograms of the data:

>> histogram(x)>> x=rand(1000,1);>> histogram(x)>> x=rand(100000,1);>> histogram(x)

We can give the histogram command a second input, can you work out what this does?

>> x=rand(10000,1);>> histogram(x,10)>> histogram(x,20)

Using more complicated commands (use help to see what these commands mean) an estimateof the samples probability density function (PDF) can be plotted:

>>clear all>>N=10000>>histogram(rand(N,1),50,'Normalization','pdf');;

For a uniformly distributed random variable X ∼U (a,b) the PDF is given by:

f (x) =

{1

b−a ; for a≤ x≤ b,0 ; for x < a or x > b.

Page 38: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

38 Chapter 5. Random numbers & Code timing

We see for large values of N the normalised histogram approaches f (x).

5.2 Other distributions

We can also sample from a number of other important statistical distributions, for examplenormally distributed random variables can be drawn (with mean µ , standard deviation s) usingthe following command:normrnd(mu,s,n,m)

which generates an nxm matrix of normally distributed random numbers. Try the followingcommands:

>> x=normrnd(0,1,1000,1);>> plot(x)>> figure>> histogram(x)

Use the MATLAB help to search for other distributions.

5.3 Code timing

It is often useful to test how long a script (or a section of a script) takes to run. For example therecould be a particular bottleneck in your code that could be tweaked to improve performance.Fortunately there is a very easy way to time a section of commands in MATLAB by using thefunctions tic and toc. tic switches on a stopwatch while toc stops it and returns the CPUtime (Central Processor Unit) in seconds. The timings will vary depending on the model ofcomputer being used and its current load.

>> tic, sum((1:10000).^2);tocElapsed time is 0.001133 seconds.>> tic, sum((1:100000).^2);tocElapsed time is 0.002808 seconds.>>tic, sum((1:100000000).^2);tocElapsed time is 1.228138 seconds.

Earlier you were asked to write a script to investigate the Basel problem. Perhaps the mostelegant way to do this is to use the intrinsic function cumsum:

>> n = 1:100;>> S = cumsum(1./n.^2);>>plot(n,S,[n(1) n(end)],(pi^2/6)*[1,1])>>disp('relative error N=100 (%)') ; 100*abs(S(end)-(pi^2/6))/(pi^2/6)>>figure>> n = 1:1000;>> S = cumsum(1./n.^2);>>plot(n,S,[n(1) n(end)],(pi^2/6)*[1,1])>>disp('relative error N=1000 (%)') ; 100*abs(S(end)-(pi^2/6))/(pi^2/6)

How does the time this code takes to run compared to the code you wrote using a for loop? Thisexample has also introduced a few new bits of syntax. If n is a vector n(end) gives the value ofthe final component of the vector and n(1) gives the first component. figure is used to opena new figure window, you can open multiple figure windows through the repeated use of thiscommand. abs gives the absolute value ( f (x) = |x|) of a scalar/vector/array. Finally disp is

Page 39: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

5.3 Code timing 39

used to print to the screen. Try another one, we know the mean of a data set x1,x2, . . . ,xn is givenby

x =1n

n

∑i=1

xi.

MATLAB has an intrinsic function to compute the mean for example:

>> clear all ; clc>> x=rand(100000,1);>> mean(x)

ans =

0.4996

Exercise 4

Write your own script to compute the mean using a for loop. How does the timing of thecode compare to MATLAB’s intrinsic function?In a separate script generate a vector of normally distributed random data. Check (as wedid for the uniform random sample) that if you generate a large sample the estimated PDFis comparable to the PDF of the normal distribution:

f (x | µ,σ) =1

σ√

2πexp{−(x−µ)2

2σ2

}

Extension Task

I have just bought Meat Loaf’s seminal album ‘Bat out of Hell’. Write a script that willgenerate a random playlist from the album (100 songs as I have a long drive). Check theplaylist you have suggested, I really don’t like listening to the same song twice in a row.In fact when companies first introduced random playlists people complained that theyweren’t random enough, as we underestimate the number of repetitions which occur in arandom sequence of numbers. Adapt your script to avoid repetitions.

Page 40: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6
Page 41: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

IntroductionReading Data

6. Function m-files

6.1 IntroductionWe can extend the number of MATLAB’s built-in functions by writing our own. They are specialcases of m-files. Fot example, the area, A, of a triangle with sides of length a, b and c is given by

A =√

s(s−a)(s−b)(s− c),

where s = (a+b+ c)/2. Write a MATLAB function that will accept the values a, b and c asinputs and return the value of A as output.

The procedure is as follows1. Decide on a name for the function, making sure that it does not conflict with a name that

is already used by MATLAB. In this example the name of the function is to be area, soits definition will be saved in a file called area.m

2. The first line of the file must have the format: function [list of outputs] = function name(listof inputs) For our example, the output (A) is a function of the three variables (inputs) a, band c so the first line should readfunction [A] = area(a,b,c)

3. Document the function. That is, describe briefly the purpose of the function and how itcan be used. Remember these lines should be preceded by % which signify that they arecomment lines that will be ignored when the function is evaluated.

4. Finally include the code that defines the function. This should be interspersed withsufficient comments to enable another user to understand the processes involved.

Page 42: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

42 Chapter 6. Function m-files

Here is an example of a well written function which does the job:

function [A]=area(a,b,c)%Compute the area of a triangle whose sides%have length a, b and c%Inputs:% a,b,c: Length of sides%Output:% A: area of triangle%Usage:% Area=area(2,3,4)s=(a+b+c)/2;A=sqrt(s*(s-a)*(s-b)*(s-c));

Note the command>> help area

will produce the leading comments from the file. To evaluate the area of a triangle with side oflength 10, 15, 20:

>> Area = area(10,15,20)Area =

72.6184

where the result of the computation is assigned to the variable Area–the use of a capitalisedvariable name is critical here, otherwise there would be confusion between the variable nameand the function name. If we inadvertently use a variable name that coincides with a functionname, as in

>> sin = sin(pi/6)sin =

0.5000>> sin(pi/2)??? Subscript indices must either be

real positive integers or logicals.

MATLAB now considers the name sin to refer to a variable and pi/2 in the commandsin(pi/2) is interpreted as an index to a vector. To reclaim the function name we clearthe variable sin from memory with>> clear sin The variable s used in the definition of the area function above is a ‘localvariable’: its value is local to the function and cannot be used out- side:

>> s??? Undefined function or variable s.

If we were interested in the value of s as well as A, then the first line of the file should be changedtofunction [A,s] = area(a,b,c) where there are two output variables.This function can be called in several different ways:

• No outputs assigned

>> area(10,15,20)ans =

72.6184

Page 43: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

6.1 Introduction 43

gives only the area (first of the output variables from the file) assigned to ans; the secondoutput is ignored.

• One output assigned

>> Area = area(10,15,20)Area =

72.6184

again the second output is ignored.• Two outputs assigned

>> [Area, hlen] = area(10,15,20)Area =

72.6184hlen =

22.5000

The previous examples illustrate the fact that a function may have a different number of outputs.It is also possible to write function files that accepts a variable number of inputs. For example, inthe context of our area function, to calculate the area of a right angled triangle it is only necessaryto specify the lengths of two of the sides since the third (the hypotenuse) can be calculated byPythagoras’s theorem. So our amended function operates as previously described but, when onlytwo input arguments are supplied, it assumes the triangle to be right angled. It does this by usingthe reserved variable nargin that holds the number of input arguments. The revised function,called area2, might then resemble the following code:

function [A]=area2(a,b,c)%Compute the area of a triangle whose sides%have length a, b and c%Inputs: either% a,b,c: Length of sides%or% a,b: Length of two shortest sides of a right angled triangle%Output:% A: area of triangle%Usage:% Area=area(2,3,4)%or% Area=area(2,3)if nargin <2

error( 'Not enough arguments')elseif nargin==2

c = sqrt(a^2+b^2);ends = (a+b+c)/2;A = sqrt(s*(s-a)*(s-b)*(s-c));%%%%%%%%% end of area2 %%%%%%%%%%%

The command error issues an error message to the screen and could be usefully employed inthe following exercise. What is wrong with the following function call:area(4,5,10) Edit the function to avoid this situation.

Page 44: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

44 Chapter 6. Function m-files

6.2 Reading Data

Direct input of data from keyboard becomes impractical when• the amount of data is large and• the same data is analysed repeatedly.

In these situations input and output is preferably accomplished via data files. When data arewritten to or read from a file it is crucially important that a correct data format is used. The dataformat is the key to interpreting the contents of a file and must be known in order to correctlyinterpret the data in an input file. There are two types of data files: formatted and unformatted.Formatted data files uses format strings to define exactly how and in what positions of a recordthe data is stored. Unformatted storage, on the other hand, only specifies the number format. Weshall focus here on the simplest case which is formatted data.

We shall write a dummy data file, open up a basic text editing program (Notepad in Windows)and create a file called table.log. Write the following numbers into the file, save it and close theeditor.

100 2256200 4564300 3653400 6798500 6432

Using MATLAB navigate to where the data file has been saved (or perhaps better save the datafilealong with your MATLAB scripts). There are more flexible ways to read in the data, howeverthe simplest way is to use the load command:

>> A=load('table.log')A =

100 2256200 4564300 3653400 6798500 6432

We have now loaded the data into the variable A, now we can manipulate and analyse the data aswe wish, for example we can plot the data:

>> plot(A(:,1),A(:,2),'ko','MarkerSize',8,'MarkerFaceColor','k')>>set(gca,'FontSize',16)>>xlabel('x','FontSize',16)>>ylabel('y','FontSize',16)

There looks to be some correlation between the independent variable x (the number of catsowned?) and the y variable (the number of hours spent per year emptying the litter tray?); let’sexplore this a little further. Type

>> help polyfit

use this documentation to explore a linear fit to the data (i.e. yi = αxi +βi + εi) can you producea figure similar to the one below?Next download the following data file:

Page 45: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

6.2 Reading Data 45

http://abag.wdfiles.com/local--files/teaching/example_data.log. Plot this data,note there does not appear to be a linear relationship between x and y. Again using polyfit’shelp explore a quadratic fit to the data (i.e. yi = αx2

i +βxi + γi + εi) can you produce a figuresimilar to the one below? How are the errors ε distributed?

Page 46: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

46 Chapter 6. Function m-files

Extension Task I

Write a function-file that will simulate N throws of a pair of dice. You may find therounding functions useful. Check your function by plotting the histogram of the combinedscore from N = 10000 rolls of a pair of dice, do the frequencies match what you wouldexpect?

Extension Task II

Conway’s game of life is an example of a cellular automaton, which consists of a regulargrid of cells, each in one of a finite number of states, such as ‘on’ and ‘off’ (‘dead’ or‘alive’). Create a random 50 by 50 array of 0s and 1s:

A=randi(50,50)

In the original version of the game each cell interacts with its eight neighbours, which arethe cells that are horizontally, vertically, or diagonally adjacent. To deal with cells whichare at the edges of the domain At each step in time, the following transitions occur:

• Any live cell with fewer than two live neighbours dies, as if caused by under-population.

• Any live cell with two or three live neighbours lives on to the next generation.• Any live cell with more than three live neighbours dies (over-population).• Any dead cell with exactly three live neighbours becomes a live cell (reproduction).

Write a function file (edit GOL_live_die) which takes row and column index asinputs (along with the matrix A) and returns wether that cell lives or dies based on therules above. Use this function along with the following script to play with the game oflife and investigate the rich behaviour it can display.

A=randi(50,50);for itime=1:1000 %how many iterations in time

for i=1:50for j=1:50

newA(j,i)=GOL_live_die(i,j); %this is your functionend

endA=newA;pcolor(A) ; daspect([1 1 1])pause %this means you need to press a button on the keboard ...

evert step%you could replace this with pause(0.1)

end

What are the steady states of the game?

Page 47: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

Anonymous functions1st-order ODEs2nd-order ODEs

7. Solving ODEs with MATLAB

7.1 Anonymous functionsA differential equation is an equation, the unknown is a function, and both the function andits derivatives may appear in the equation. Differential equations are essential for a mathe-matical description of nature. They are at the core of many physical theories: Newton’s andLagrange equations for classical mechanics, Maxwell’s equations for classical electromagnetism,Schrödinger’s equation for quantum mechanics, and Einstein’s equation for the general theory ofgravitation, to mention a few of them.

If the unknown function is a function of only one independent variable then we have anordinary differential equation (as only ordinary rather than partial derivatives appear). Here weshall focus on using MATLAB to find numerical solutions to first order – ordinary differentialequations (ODEs), which take the form

dxdt

= f (x, t), t ∈ [t0, t1], x(t0) = x0

this is a specific type of ODE know as an initial value problem (IVP). x = x(t) is the unknownfunction we wish to find and f (x, t) is a specific function which depends on the physical problemwe wish to model. For example if x is the number of radioactive atoms in a sample of polonium-210 then we would model the decay of the radioactive sample as

dxdt

=−λx,

where λ is a constant. Before we attempt to solve this ODE with MATLAB first we need to beable to specify anonymous functions. An anonymous function is a one-line expression-basedMATLAB function that does not require a program file.For example, the statement

sqr = @(x) x.^2;

creates an anonymous function that computes the square of its input argument x. The @ operatormakes sqr a function handle, giving you a means of calling the function:

Page 48: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

48 Chapter 7. Solving ODEs with MATLAB

sqr(20)ans =

400

Make an anonymous function to plot

x(t) = sin(2πt)+0.3sin(4πt +0.3)+0.1sin(6πt +0.8), t ∈ [0,1].

If the function is a function of more than one variable then we use the following syntax

f=@(t,x) x*(5-x)*(t^2);

which is equivilent to f (x, t) = x(5− x)t2.

7.2 1st-order ODEs

We shall make use of one of MATLABs inbuilt functions, ode45 to seek a numerical (henceapproximate) solution to an ODE. Formally this routine uses a variable step Runge-Kutta Methodto solve differential equations numerically, however we shall not worry about these details now.The mathematics of numerical ODE solvers will be discussed later in your degree, however theinterested reader can find many resources from the internet 1. To solve an ODE of the form

dxdt

= f (x, t), t ∈ [t0, t1], x(t0) = x0

we first specify the right-hand side of the ODE ( f ) as an anonymous function. The the range oft is specified and an initial value for x. We can then use the ode45 function. For example thefollowing code solves,

dxdt

= x(1− x), t ∈ [0,1], x(t0) = 0.1

t=0:0.001:10; % timeinitial_x=0.1; %initial vale of xrhs=@(t,x) x*(1-x); %rhs of ODE[t,x]=ode45( rhs, t, initial_x); %ode45 syntaxplot(t,x); %plot the functionxlabel('t'); ylabel('x'); %label axis

The ODE we have just solved arises from the Logistic Model2. The logistic differential equationis written:

dxdt

= γx(1− x/K),

where γ is the growth rate and K the carrying capacity. An analytic solution can be found byusing separation of variables (try it) to give:

x =K

1+Ae−kt , A =K− x0

x0.

How close is your numerical solution to the true analytic solution?

1Keywords: “Euler’s method", “Runge-Kutta", “Runge-Kutta-Fehlberg", “time stepping methods"2google Logistic Model in the context of population growth

Page 49: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

7.3 2nd-order ODEs 49

7.3 2nd-order ODEs2nd-order ODEs are a little more tricky as ode45 only works with first order equations, hencewe must reduce a second order PDE to a system of ODEs. This is best illustrated by an example.We shall consider the classical problem of a mass on a spring. This can be modelled using twoimportant physical principles. Firstly Newton’s second law tells us that the acceleration of anobject (as produced by a net force) is directly proportional to the magnitude of the force, andinversely proportional to the mass of the object. In 1D:

F = ma = mdxdt

.

Secondly, Hooke’s law states that the force F needed to extend or compress a spring by a distancex is proportional to that distance,

F =−k′x.

Combining these leads to the following 2nd order ODE

x′′+ kx = 0, x(0) = a, x′(0) = b, t > 0,

where x is the distance of the mass from its equilibrium position, k is a constant related tothe spring (and mass), and a and b tell us about the mass’s initial position and velocity. If weintroduce y1 = x, y2 = x′ then the problem can be recast as a system of two first order ODEs

y′1 = y2

y′2 =−kx1

withy1(0) = a, y2(0) = b

Let’s take a = 1, b = 0 and k = 1 and write a MATLAB code which can solve this numerically.First we write a function file and save it to F.m

function yp=F(t,x)yp=zeros(2,1); % since output must be a column vectoryp(1)=x(2);yp(2)=-x(1);

then write the following as a script file (with the name of your choice)

t0=0.; %initial timetf=20.; %final timey10=1.; %initial positiony20=0.; %initial velocity[t,x]=ode45('F',[t0,tf],[y10,y20]); %ode45 syntaxplot(t,x(:,1)) %plot position vs timexlabel('t','FontSize',16)ylabel('x','FontSize',16)set(gca,'FontSize',16)

figureplot(x(:,1),x(:,2)) %plot phase planexlabel('x','FontSize',16)ylabel('dx/dt','FontSize',16)set(gca,'FontSize',16)daspect([1 1 1]) %make aspect ratio 1:1 so we see a circle

Page 50: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

50 Chapter 7. Solving ODEs with MATLAB

The first figure is a plot of x vs. t (as x is stored as y1), the second figure plots dx/dt vs. x whichis called the phase plane (a coordinate plane with axes of the two state variables). Our model isnot particularly realistic if I knocked a mass on a spring and came back to it a day later would itstill be bouncing up and down? No, it is ‘braked’ by air resistance. We can add another term tothe ODE which models air resistance:

x′′ =−kx−βx′, x(0) = a, x′(0) = b, t > 0,

Again we take a = 1, b = 0 and k = 1. We fix β = 0.25, all we need do is modify the F.m

function to account for the additional term, try doing this and see if you find the following plots:We see the affect of adding a term to model resistance dampens the mass-spring system and

the trajectory of the phase plane is an inward spiral. Technically our first model was energyconserving, once we added the ‘friction’ term to the right hand side of the ODE our systembecomes dissipative and energy is lost in time.

Indeed the energy of the system can be decomposed into two parts:

E = Ek +Ep

where E is the total energy, Ek is the kinetic energy (the energy associated with the mass moving)and Ep is the potential energy (the elastic potential energy of the spring due to stretching orcompression). If Ek = mv2/2 (where v = x′ is the velocity of the mass) and Ep = kx2 then

Page 51: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

7.3 2nd-order ODEs 51

(assuming m = 1)

E =x2 + x′2

2

Note the radius of the spiral (and the circle when β = 0) in the phase-plane is√

E, hence it isclear that the first model conserves energy and the second loses energy. If we plot (for the secondmodel with β = 0.25) E vs. t we obtain the following figure:

Notice how the Energy is lost in steps, why is this? Think about what the dissipative term isproportional to.

Page 52: MAS1801: MATLAB - Welcome - Andrew Baggaleyabag.wdfiles.com/local--files/teaching/MAS1801_MATLAB.pdf1.1 About these notes5 1.1.1 Assesment.....5 1.2 Introduction6 1.3 Getting started6

52 Chapter 7. Solving ODEs with MATLAB

Extension Task I

The Lotka-Volterra equations, are a pair of first-order, non-linear, ordinary differentialequations frequently used to describe the dynamics of biological systems in which twospecies interact, one in the role of a predator and the other as prey. The populationschange through time according to the the following equations:

dxdt

= αx−βxy (7.1)

dydt

= δxy− γy (7.2)

Where• x is the number of prey• y is the number of predators• t is time• α,β ,γ,δ are positive real parameters which depend on the system we are mod-

elling.Take α = 1,β = 0.05,γ = 0.5 and δ = 0.02. For the initial populations take x(t = 0) =y(t = 0) = 10, i.e the same number of predator and prey. Using the previous example asa guide code up a function and script file to simulate this system. Plot the populations asa function of time, does your result make sense?

Extension Task II

Bernoulli Differential equations have the form

dydx

+ p(x)y = q(x)yn

where y = y(x). To solve them analytically we first divide the ODE by yn

y−ny′+ p(x)y1−n = q(x)

(note the shorthand notation y′ = dy/dx), and then using the substitution v = y1−n. Afterimplicit differentiation (try it) we find the ODE can be recast as

11−n

v′+ p(x)v = q(x)

which is a linear 1st order ODE and thus can be solved using the integrating factor method.Find the analytic solution to the following ODE:

y′+4x

y = x3y2, y(2) =−1, x > 2.

then write a MATLAB script to numerically solve the same ODE and compare thenumerical and analytic solutions.