programming in matlab - cp³-originscp3-origins.dk/content/pdf/cp3-srp2014/cosmology/matlab...

23
University of Southern Denmark An introductory set of notes Programming in MATLAB Authors: Nicky C. Mattsson Christian D. Jørgensen Web pages: imada.sdu.dk/ nmatt11 imada.sdu.dk/ chjoe11 November 10, 2014

Upload: ngoxuyen

Post on 06-Feb-2018

250 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Programming in MATLAB - CP³-Originscp3-origins.dk/content/pdf/CP3-SRP2014/Cosmology/Matlab noter.pdf · Programming in MATLAB Authors: ... your own computer and access other computers

University of Southern Denmark

An introductory set of notes

Programming in MATLAB

Authors:Nicky C. Mattsson

Christian D. Jørgensen

Web pages:imada.sdu.dk/ ∼ nmatt11imada.sdu.dk/ ∼ chjoe11

November 10, 2014

Page 2: Programming in MATLAB - CP³-Originscp3-origins.dk/content/pdf/CP3-SRP2014/Cosmology/Matlab noter.pdf · Programming in MATLAB Authors: ... your own computer and access other computers

Contents

0 Preparation 20.1 How do I get MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

0.1.1 SSH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20.2 Where do I buy it? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

1 Getting started 51.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.2 Using variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

1.2.1 Creating Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61.2.2 Retrieving the information . . . . . . . . . . . . . . . . . . . . . . . . . . 61.2.3 Automatic creation of variables . . . . . . . . . . . . . . . . . . . . . . . 7

1.3 Elementary operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91.3.1 Matrix operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91.3.2 Element-wise operations . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

1.4 Graphics; including plots, figures etc. . . . . . . . . . . . . . . . . . . . . . . . . 111.5 Control statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

1.5.1 Boolean operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131.5.2 Conditional execution (if/else-statements) . . . . . . . . . . . . . . . . . 141.5.3 The ”for”-loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151.5.4 The ”while”-loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

1.6 Important build-in functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171.7 Create your own function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181.8 Case: Print and plot the first n Fibonacci numbers . . . . . . . . . . . . . . . . 20

2 Taking your skills to the next level 222.1 FF505 - Computational Science . . . . . . . . . . . . . . . . . . . . . . . . . . . 222.2 MM533 - Mathematical and Numerical analysis . . . . . . . . . . . . . . . . . . 222.3 MM532 - Iterative methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222.4 MM534 - Differential equations . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

1

Page 3: Programming in MATLAB - CP³-Originscp3-origins.dk/content/pdf/CP3-SRP2014/Cosmology/Matlab noter.pdf · Programming in MATLAB Authors: ... your own computer and access other computers

Chapter 0

Preparation

0.1 How do I get MATLAB

There are two main ways of getting MATLAB, either you can use the edition which is installedat IMADA’s computers by using SSH, or you can buy your own. The downside of using SSHis that you need to be connected to the internet all the time, and the speed of your connectionwill decide how fast you can edit your files.

0.1.1 SSH

SSH stands for Secure Shell, which basically mean that it’s a secure method to shell, i.e. runprograms on another computer. So the strength or whole idea of SSH is that you can useyour own computer and access other computers and use their programs, for instance MATLABwhich is the program we’re interested in.

So how do I use this secure shell?First of all, you will need a Unix-terminal, this is standard on Macintosh and all Linux distri-butions. So if you have any of these computers, you can jump directly to the section tellingyou how to connect. If you have a Windows based computer, don’t worry, the help is near, it’llonly require you to install two small programs called puTTy and XServer to do the same asthe you can on Macintosh and Linux.

Second you’ll need a login to the computer you try to get access to; as this guide focusses onusing MATLAB on the computers of IMADA, you’ll just need a login to IMADA’s computers.Which you can get by asking Per who is one of the librarians.

Yup, I have a Pc

The way to fix your terminal such that it becomes useful, you’ll first have to download aprogram called puTTy, this you can do by using the following link:

http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html

and chose the one called puTTy under the headline ”For Windows on Intel x86”. puTTyshouldn’t be installed, as it’s an executable file, which you just execute every time you have touse it. Next thing you have to download is an x Server, in this case we use one called Xming,this one you can download from:

http://sourceforge.net/projects/xming/files/

and choose the one called just ”Xming”, this one you have to install. Do this by simplyfollowing the steps.When both programs are installed you open up puTTY and look under the Connection

2

Page 4: Programming in MATLAB - CP³-Originscp3-origins.dk/content/pdf/CP3-SRP2014/Cosmology/Matlab noter.pdf · Programming in MATLAB Authors: ... your own computer and access other computers

category, expand SSH and click the Enable X11 Forwarding checkbox. In the field Xdisplay location, you now write:� �

:0 (colon + zero)� �Now you go back to the session page. Under Host name you now write:� �

[email protected]� �Then you go the box Saved sessions and give the connection a name, and press save. Nowyou can simply double click the saved session every time you want to SSH onto IMADA’scomputers. When you try to access IMADA’s computers it’ll ask for your password, type it,but notice that it won’t show that you write anything, hit enter and wait for it to login. Whenyou’re logged in, write Matlab in the terminal and wait for it to start.

I have Linux or Macintosh

It’s actually quite easy to use SSH. The basic way is to simply type the following into yourterminal:� �

ssh [email protected]� �After which you’ll have to type your password, notice that the terminal wont write anythingas you type your password. You do now have access to the computer and you can basically doanything with it, but you do only have the terminal to work from, which means that you can’tsee the user interface MATLAB haves. There are ways such that you can use the interface, oneway is to use an XServer, which was standard on Macintosh, it still is in Ubuntu (probably themost Linux distributions). You can get it for Macintosh just by searching Google for ”XServerMac”, and download it. This you apply by using the following command in stead of the firstone:� �

ssh -X [email protected]� �But use it with care, as it takes a huge amount of your internet connection, and might slowyour work considerably, and it isn’t always necessary to use the user interface. Again you’llhave to type your password. Now as you have taken control over the computer, you can openany program by just entering its name into the terminal. So to open MATLAB, simply typeMatlab and wait.

0.2 Where do I buy it?

If you’re going to use MATLAB more than just in one course, you might want to considerbuying the program, which will make you independent of the internet connection present. As astudent the price of MATLAB and Simulink lies just around 600 dkk, and the price only differsa little depending on where you buy it. As with everything nowadays you have the followingto options:

1. Buy it from the internet (digital) 1

2. Buy it in a book store (hard copy) 2

1http://www.mathworks.se/index.html2The book store at SDU does sell a hard copy

3

Page 5: Programming in MATLAB - CP³-Originscp3-origins.dk/content/pdf/CP3-SRP2014/Cosmology/Matlab noter.pdf · Programming in MATLAB Authors: ... your own computer and access other computers

The benefit of buying it from the internet is that you get it directly from mathworks itself,further in the most smaller and newer computers, there is not installed any CD drive, so youcan’t use the hard copy. Further can you download MATLAB to all of your own computers,and if you at any time have to format your computer (or buy a new one), you can simplydownload it again. So you should not be afraid of having to buy it again if anything happensto your computer.

On the other hand if you feel more safe by buying it in a book store and getting a hardcopy, we’re sure that the same terms should apply.

4

Page 6: Programming in MATLAB - CP³-Originscp3-origins.dk/content/pdf/CP3-SRP2014/Cosmology/Matlab noter.pdf · Programming in MATLAB Authors: ... your own computer and access other computers

Chapter 1

Getting started

1.1 Introduction

Matlab is a program build on the programming language C, and it contains functions whichhave been optimized for using matrices and vectors. This is fantastic when working with suchthings, because things as matrix multiplication happen almost without you have to think. Thedownside of this is however that you’ll have to think, whenever you don’t work with matricesand vectors, and then tell Matlab that this is just some numbers without structure. FurthermoreMatlab is really suited for working with big arrays, because of the underlying C structure. Sooverall Matlab is really suited for solving problems involving large systems of equations, orsimply handling large arrays. At the University of Southern Denmark, Matlab is especiallyused in the courses:

1. Computational Science

2. Iterative methods for sparse linear systems

3. Mathematical and numerical analysis

4. Differential equations

These are also the courses which we’ll focus on in the second half of this set of notes, whereasthe first part will focus on getting started using Matlab, and introduces the basic stuff, whichyou’ll need over and over again. Matlab will automatically color the code for you, which willmake it easier for you to debug, when you get more experiensed. At some places in the noteswe will use pseudo code, this is code that you cannot write directly into Matlab, but moreexplains what you should do, those will be marked by a white box, whereas rest of the codewill be marked by gray boxes. But let’s get started

5

Page 7: Programming in MATLAB - CP³-Originscp3-origins.dk/content/pdf/CP3-SRP2014/Cosmology/Matlab noter.pdf · Programming in MATLAB Authors: ... your own computer and access other computers

1.2 Using variables

1.2.1 Creating Variables

First we’ll need to be able to create variables; variables are Matlab’s way to store information,and they can contain numbers and letters. First we can create a variable containing a number:� �

a = 2;� �Then ”a” is a variable containing the number 2. This we can extend to creating two types ofvectors, a horizontal and a vertical:� �

b = [4,5,6,7];� �will create a horizontal vector named ”b”, with the elements 1, 2, 3, 4, you can also just usespace to separate the elements in the vector in stead of the comma. Similarly:� �

c = [4 ; 5 ; 6 ; 7];� �Will create a vertical vector named ”c”, with the same elements. You can transpose a vectorand matrix by using apostrophe, so (As we’ll mention in chapter 1.5.1 the double equality isn’ta mistake):� �

b == c’;� �Now we can combine the two types of vectors to create our first matrix:� �A = [1,2 ; 3,4];� �

This creates a matrix called ”A” (which is different from ”a”) containing the elements 1 and 2on the first row and the elements 3 and 4 on the second row.

Matlab can also handle variables which contain text for instance can you create an array(vector) containing a sentence:� �

SomeText = ’This is a sentence!’;� �Then the variable called ”SomeText” is a vector where each entrance is an ASCII symbol (letter,space, symbol). This can be justified if you want to use what’s called data structures. A datastructure is basically just an easy way to store several informations on the same thing. Forinstance can you store informations on persons:� �

person.name = ’Nicky ’;

person.age = 21;� �This can be extended to several persons:� �

person1.name = ’Nicky’;

person1.age = 21;

person2.name = ’Christian ’;

person2.age = 21;

persons = [person1 , person2]� �Then you have a vector where each entrance is a person, each containing two informationsabout the person.

1.2.2 Retrieving the information

After you’ve created your variable, you can of course retrieve the informations that you’veentered. If you’re interested in everything in one variable, for instance the entire vector or theentire matrix, then you just write the name of the variable:

6

Page 8: Programming in MATLAB - CP³-Originscp3-origins.dk/content/pdf/CP3-SRP2014/Cosmology/Matlab noter.pdf · Programming in MATLAB Authors: ... your own computer and access other computers

� �A� �

This will now print out:� �A =

1 2

3 4� �Notice that the semicolon at the end of the previous statements silences the output, so when weabove don’t write the semicolon at the end of the statement Matlab prints out what it contains.

You can also tell Matlab what you want to print, if you don’t want Matlab to print thewhole vectors/matrices. For instance if we have the vector ”b” again then we can print out thefirst element by writing:� �

b(1)� �Note that the first element is numbered 1 and not 0 as in most programming languages. Wecan also use this value and assign it to a variable:� �

d = b(1)� �Now ”d” contains the first element in ”b”, you can also assign values in the other direction. Ifyou want the last value of an vector and don’t know it’s length, then you can use the command”end” which will give you the last element, which we know is 4 in this case. Therefore thefollowing will be true (Matlab returns the value 1)1� �

7 == b(end)� �When extended to matrices you’ll of course need two numbers to specify a single number

in the matrix, the syntax is:� �A(row ,column)� �

You can also choose a vector from a matrix by using colon, the operation:� �A(2,:)� �

Will give you the entire second row.

1.2.3 Automatic creation of variables

Often when working with large vectors, which are simple in their construction, you can usesome of Matlabs build in functions to create them. If you want a matrix with all elementsequal zero, you can use the command zeros(row,column):� �

zero = zeros (3,2)� �Similarly you can create a matrix with all ones. To do so,type the following:� �

one = ones (3,2)� �If you want any other numbers than ones or zeros, you simply scale the matrix or vector asyou’ll learn in section 1.3.1.

When plotting or evaluating functions or doing for-loops (explained in chapter 1.5.3) it’soften necessary to create an array, which starts at some value and then counts up or down tosome end value with some in-/decrement. This you do in the following way:

1From now until chapter 1.5.1, Matlab should return 1 everytime we use the double equality ”==”.

7

Page 9: Programming in MATLAB - CP³-Originscp3-origins.dk/content/pdf/CP3-SRP2014/Cosmology/Matlab noter.pdf · Programming in MATLAB Authors: ... your own computer and access other computers

� �i=1:1:10

i =

1 2 3 4 5 6 7 8 9 10� �So the first number is the start value, the second is the increment, and the last one is end value.Per standard the increment is one, so a shorter way of writing the above is:� �

i=1:10

i =

1 2 3 4 5 6 7 8 9 10� �MATLAB can also create identity matrices for you, an example is the 6x6 identity matrix:� �I = eye(6)

I =

1 0 0 0 0 0

0 1 0 0 0 0

0 0 1 0 0 0

0 0 0 1 0 0

0 0 0 0 1 0

0 0 0 0 0 1� �

8

Page 10: Programming in MATLAB - CP³-Originscp3-origins.dk/content/pdf/CP3-SRP2014/Cosmology/Matlab noter.pdf · Programming in MATLAB Authors: ... your own computer and access other computers

1.3 Elementary operations

Now as we have created the variables we should be able to work with them. There are basicallytwo types of operations. Those who act on matrices and vectors, and those who act element-wise.

1.3.1 Matrix operations

When dealing with matrices, it is basically just using the ordinary operators. So you canmultiply two matrices by using the command ”*”:� �

A = [1,2 ; 3,4];

B = [2,4 ; 1,3];

C = A*B;� �The rest of the chapter we always define the matrix A at each example, but if you’re usingthe same Matlab session, you don’t have to redefine it every time. If one of the matrices is anumber, then you just scale the matrix:� �

A = [1,2 ; 3,4];

b= 2;

C = A*b == [2,4 ; 6,8];� �Plus and minus works in the same manner, though you can’t add or subtract a single numberto a matrix/vector:� �

A = [1,2 ; 3,4];

B = [2,4 ; 1,3];

C = A+B;� �and� �

A = [1,2 ; 3,4];

B = [2,4 ; 1,3];

C = A-B;� �Then finally there’s the inverse. This one is a little more interesting, as there are different waysof doing it. The most simple one is the inv command:� �

A = [1 2 ; 3 4];

invA = inv(A);� �This is though a quite slow way of doing it. You can however not notice it for small matrices,or when you just have to do it once or twice, but when you have to do it for large matrices ormany times, other ways are considerably faster. The typical way for normal sized matrices isto use the mldivide function, this inverts the first matrix and multiplies it to the second one,so the above invert command corresponds to:� �

A = [1 2 ; 3 4];

C = mldivide(A,eye (2));� �But often you don’t need the inverse matrix itself, but to multiply it with another vector ormatrix, here you simply change the last argument in mldivide to:� �

A = [1 2 ; 3 4];

B=A;

C = mldivide(A,B);� �A faster syntax for this is however; note that it’s the same operation, just different syntax:

9

Page 11: Programming in MATLAB - CP³-Originscp3-origins.dk/content/pdf/CP3-SRP2014/Cosmology/Matlab noter.pdf · Programming in MATLAB Authors: ... your own computer and access other computers

� �A = [1 2 ; 3 4];

B = A

C =A\B� �1.3.2 Element-wise operations

In MATLAB, when possible, the matrix operation is default. Therefore when you want to doelement-wise operations you have to tell Matlab to do so. This is for instance important whendeclaring a function; Here you either have to specify that it’s always element-wise operationsor to figure out whether it’s possible for the function to have an array or a matrix as input. Sothe element-wise plus and minus is exactly the same, as when you add or subtract to vectorsor matrices, it’s always element by element. But when you want to multiply two numbers in amatrix or vector with another matrix or vector, it’s no longer element-wise, so here you haveto specify it. In MATLAB you specify element-wise operations by using a dot (.) in front ofthe operator (*). The following code will multiply 1 with 1 and 2 with 2 etc. and make a newmatrix with this output:� �

A = [1 2 ; 3 4];

B = [1 2 ; 3 4];

C = A .*B

C =

1 4

9 16� �In the same manner you can use divide and power:� �

A = [1 2 ; 3 4];

B = [1 2 ; 3 4];

C = A ./B;

D = A.^2;� �Please notice the difference between the two slashes (Forward slash and backward slash).

10

Page 12: Programming in MATLAB - CP³-Originscp3-origins.dk/content/pdf/CP3-SRP2014/Cosmology/Matlab noter.pdf · Programming in MATLAB Authors: ... your own computer and access other computers

1.4 Graphics; including plots, figures etc.

The basic command you have to use when plotting functions is the following:� �plot(x,y)� �

Here x and y are equally sized vectors. You either get all the values from a build-in function or amathematical function. So if you have two values, you can simply use the command, otherwiseyou can generate the other vector the following way:� �

x = -10:0.1:10;

f = @(x) 2*x.^2 +4; %notice the element -wise notation

func = f(x);

plot(x,func)� �This will first create a vector with elements ranging from -10 to 10 with 0.1 increments. Thenwe define a function, which depends on x2, notice that you need to use element-wise notation,as we put an array into it and save the new array into the variable func. Finally we plot the twovectors against each other with the command plot. The percentage sign denotes a comment,which won’t get executed. This can be even more dense:� �

x = -10:0.1:10;

f = @(x) 2*x.^2 +4;

plot(x,f(x))� �If you want a function of severable variables, you simply extend the above function definitionto � �

f = @(x,y) 2*x.*y + y + x;

x = -10:0.1:10;

y = -10:0.1:10;

[x,y] = meshgrid(x,y)

plot3(x,y,f(x,y))� �MATLAB changes the axis according to the range of the vectors, but you can change them

manually with the following command:� �axis([xmin xmax ymin ymax])� �

You can change the text on the axis with the following command:� �xlabel(’text on x-axis’) %notice the ’ ’

ylabel(’text on y-axis’)� �A final important function regarding plots is the ”hold”-function. This will hold the plot, suchthat if you plot something again it’ll plot on top of what’s already plotted in the figure. It’llcontinue do this until you close the window:� �

x = 0.1:0.1:5;

f=@(x) x;

g=@(x) exp(x);

h=@(x) log(x);

figure (1)

hold on

plot(x,f(x))

plot(x,g(x))

plot(x,h(x))

axis ([0 5 0 5])

hold off� �2This is due to the @(x) in front of the expression.

11

Page 13: Programming in MATLAB - CP³-Originscp3-origins.dk/content/pdf/CP3-SRP2014/Cosmology/Matlab noter.pdf · Programming in MATLAB Authors: ... your own computer and access other computers

This gives the following plot:

12

Page 14: Programming in MATLAB - CP³-Originscp3-origins.dk/content/pdf/CP3-SRP2014/Cosmology/Matlab noter.pdf · Programming in MATLAB Authors: ... your own computer and access other computers

1.5 Control statements

Control statements are exactly as the name suggests statements that control the code, whichoften leads to the execution of a piece of the code. There are different kinds of control state-ments, and the three frequently used will be discussed below. The first of them is to checkwhether you should execute a piece of the code, whereas the other two are to control how manytimes you should execute a part of the code.

1.5.1 Boolean operators

So to control whether a piece of the code should be executed we first need to introduce theboolean operators.

The easiest way to explain boolean operators is to compare it to yes/no (values 1 or 0)questions. Here you can for instance ask: Is A equal to B, is A larger or equal to B etc..Almost all of those operators are rather simple to remember, as the syntax for asking if A islarger than B is:� �

A = 4;

B = 2;

C = A>B;� �C will now contain the value 1, as in this case it’s true as 4 is larger than 2, and 1 correspondsto true. On the other hand 0 corresponds to false. Now smaller than follows similar syntax.

Now you might also want to ask if A is larger than or equal to B, which is written as:� �A = 4;

B = 2;

C = A>=B;� �Again C will contain the value 1 as A is larger than or equal to B. Again less than or equalfollows the same idea.

The more interesting syntax is the result of checking the question: Is A equal B, becauseas we use the equality sign to assign values to variables, we can’t use this alone, so the syntaxhere is (as we’ve seen before) the double equality sign:� �

A = 4;

B = 2;

C = A==B;� �Now C will contain the value 0 as 4 isn’t equal to 2, we can also write ”not equal to”, thissyntax is:� �

A = 4;

B = 2;

C = A~=B;� �In general the tilde means ”not”, so it changes true to false and false to true.

All of these operations here are always(!) element-wise, so if A and B are vectors or matrices,then the output is a matrix of the same size containing zero and ones, declaring the result ofcomparing the same entrance from both A and B with each other. So:� �

A = [1;2;3];

B = [3;2;1];

C = A==B;� �C will now be the vector containing the elements [0;1;0]. Again very important, the booleanoperations do not compare entire vectors or matrices, but elements. If you want to know if twovectors or matrices are in some relations to each other you can do the following:

13

Page 15: Programming in MATLAB - CP³-Originscp3-origins.dk/content/pdf/CP3-SRP2014/Cosmology/Matlab noter.pdf · Programming in MATLAB Authors: ... your own computer and access other computers

� �A = [4;2;3];

B = [2;1;0];

C = A>B;

d = all(C)� �Note the function ”all” returns true if and only if all elements in C are true or 1, so in theexample d will contain the value 1 as all elements in C are one, so A is in fact larger than B.The comparison can of course be switched to any you like to check for.

You also have the ability to connect statements using the boolean operators for ”AND” and”OR”. The boolean AND requires everything to be true for it to return true. The boolean ORjust require one of the statements to be true for it to return true. You can of course combinethem in any way you like. The syntax for them are the ampersand ( & ) for AND, and pipe (| ) for ”OR”, so one example of using OR is:� �

A = 4;

B = 2;

C = A<B | A>B;

D = A~=B

E = C==D� �So we can ask if A is either smaller or larger than B, which is the same as asking for if A is notequal to B. An example of using AND is that we can rewrite the vector check above to the onebelow.� �

A = [4;2;3];

B = [2;1;0];

C = A(1)>B(1) & A(2)>B(2) & A(3)>B(3);� �1.5.2 Conditional execution (if/else-statements)

Now that we can work with boolean operators, we do of course want to control something withit. You can control which lines of code are being executed by using the if-statement. It simplychecks if what you have written is true (equal to 1), and if it is then it executes the code. Thesyntax is the following� �

if (condition)

code

end� �Where ”condition” is the condition that has to be true for the ”code” to be executed. ”end”ends the statement.

A simple example could be:� �A=2

B=6

if A>0 & B>0

C=A+B

end� �As both A and B are larger than 0, 8 is assigned to C.

We can extend this with the ”else” statement. Else catches what doesn’t end in the ifstatement, so:� �

A=2

B=-1

if A>0 & B>0

C=A+B

14

Page 16: Programming in MATLAB - CP³-Originscp3-origins.dk/content/pdf/CP3-SRP2014/Cosmology/Matlab noter.pdf · Programming in MATLAB Authors: ... your own computer and access other computers

else

C=A-B

end� �Now we won’t access the if case because B is less than zero, so we enter the else case, and Cnow contains the value -1. To extend this further we can use ”elseif”, which checks the first ifcase, if this isn’t true, then it checks the elseif cases, and in the end else catches the rest.

1.5.3 The ”for”-loop

The for-loop is a statement that simply repeats a piece of the code a certain amount of times.The most simple of the for-loops is to repeat some code n times, this is done by the followingsyntax� �

for i = 1:n

code

end� �This will repeat the code, n times. Each time we go through the loop, ”i” will be the valuecorresponding to how many times you’ve been through the loop, so it starts with the value 1,then next time through the loop it has the value 2 etc.. This is often highly useful if you wantto store the values at different places in an array. An example could be:� �

for i = 1:6

A(i) = i^2;

end� �Then the loop will return a vector A with 6 elements, and each element is equal to the indexsquared.

In the for-loops i can also start with a different value than 1, by just changing the 1 toanother value. One can also change the increment, as we saw in chapter 1.2.3:� �

k=1;

for i = 4:0.5:6

A(k) = i^2;

k=k+1;

end� �However, since we now have increments that are different from 1, we can no longer use i asindex, therefore we introduce k.

1.5.4 The ”while”-loop

The while-loop is a generalisation of the for-loop, and you can therefore build the for-loop fromthe while loop. However the while-loop is often used when you don’t know how many times thecode should be repeated, but you want it repeated until some other property is fulfilled. Thesyntax is:� �

while (condition)

code

end� �This means that the code is repeated as long as the condition is true. An example could be:� �

i=1

while i<=6

A(i)=i^2;

i=i+1;

end� �15

Page 17: Programming in MATLAB - CP³-Originscp3-origins.dk/content/pdf/CP3-SRP2014/Cosmology/Matlab noter.pdf · Programming in MATLAB Authors: ... your own computer and access other computers

This while loop is repeated until i > 6, so this piece of code does the same as the for-loopbefore. It can be much different, for instance:� �

a=8

b=4

while (a~=1 & b~=1)

a=0.5*a;

b=2*b;

end

ATimesB = b;� �Then ATimesB will contain the value 32 = 8 · 4

16

Page 18: Programming in MATLAB - CP³-Originscp3-origins.dk/content/pdf/CP3-SRP2014/Cosmology/Matlab noter.pdf · Programming in MATLAB Authors: ... your own computer and access other computers

1.6 Important build-in functions

This section will provide you with the most important functions build into Matlab. For allfunctions in MATLAB you can write:� �

help function� �where ”function” is substituted by the function you want to know more about without thequotation marks. Matlab will then provide you with different information on how to use thefunction. Further can you clear the workspace by writing:� �

clear all� �Or removing the text by writing:� �

clc� �The first functions are per definition element-wise, so for instance:� �

log([exp(3) , exp (5)]) == [log(exp (3)) log(exp (5))] == [3 , 5];� �1. sqrt(): Square root: x→

√x

2. abs(): Absolute value: x→ |x|

3. exp(): Exponential: x→ ex

4. log(): Natural logarithm: x→ lnx

The next functions work on arrays, so if you give the function a matrix, then it’ll return anarray with length equal to the number of columns of the matrix, for instance:� �

A = [1 2 ; 3 4];

max(A) == [3 , 4];� �1. sum(): Returns the sum of observations per column

2. max(): Returns the maximal observation per column

3. min(): Returns the minimal observation per column

4. mean(): Returns the mean of the observations per column

5. median(): Returns the median of the observations per column

6. var(): Returns the variance of the observations per column

7. std(): Returns the standard deviation of the observations per column

17

Page 19: Programming in MATLAB - CP³-Originscp3-origins.dk/content/pdf/CP3-SRP2014/Cosmology/Matlab noter.pdf · Programming in MATLAB Authors: ... your own computer and access other computers

1.7 Create your own function

You have now made it so far that you are ready to put everything you’ve learned togetherinto a MATLAB function. A function is a collection of all (or some of) the previous learnedcommands, where they will be executed in a chronologically way, which in general is from topto bottom. So this is important if you want to store your programs for later use, and for easyaccess if you made a mistake, then you don’t have to retype everything again. Another benefitis that you can create a function which depends on what you give it as input, so it adapts.A last but important benefit is that you can split your program into several functions eachcontaining one method, so you get a structure of the program, which will make it easier todebug, when you make a mistake.

First we need to create a file, which will eventually contain our function, these files arenamed as:� �

nameoffile.m� �and the easiest way to create such file is to navigate to the folder, where you want to save yourfile, inside Matlab, and write the following in the MATLAB terminal:� �

edit nameoffile.m� �Then it’ll say that the file doesn’t exists, and ask whether you want to create it, answer yes tothis. Now you have created the file, where you can write your function inside. Every functionstarts with:� �

function [out1 , out2 ,...] = nameoffile(in1 , in2 ,...)� �Where out1, out2,... are the variables that the function returns, nameoffile is the name of thefunction, the first function inside a file, should have the same name as the file (without the end”.m”). Now you’ve created your first function and an example could be:

Here we have a file named fib.m, the first and only function in the file is named fib. It takesone input ”x” and gives one output, namely ”res”.

18

Page 20: Programming in MATLAB - CP³-Originscp3-origins.dk/content/pdf/CP3-SRP2014/Cosmology/Matlab noter.pdf · Programming in MATLAB Authors: ... your own computer and access other computers

In this function we can use what’s previously learned, so a simple function we can create isa function calculating the sum over ”i” for i = 0 to i = x. So the function takes the length ofthe sum as input, in our program called ”x”. Then we create an array containing the numbersfrom 0 to x. Then we have to sum them all up, for this we use the sum function, so now wehave:� �

function [res] = fib(x)

i = 0:x;

res = sum(i);� �Save the file, and you have now created your first function.

Now we have to call the function from Matlabs command window, so go to the commandwindow, and type the following:� �

x = fib (10);� �This will call the function ”fib”, give it the argument ”10”, then the function calculates thesum and returns it to the variable ”x”, then you can print out x, and you get the following:

19

Page 21: Programming in MATLAB - CP³-Originscp3-origins.dk/content/pdf/CP3-SRP2014/Cosmology/Matlab noter.pdf · Programming in MATLAB Authors: ... your own computer and access other computers

1.8 Case: Print and plot the first n Fibonacci numbers

To finish off the introduction chapter, we’ve created this case, which comes around most of thethings you’ve just learned. So our suggestion, is that you read the problem description and tryfor yourself to create the function, if you get stuck, try to ask a friend. If you get completelystuck and are clueless about how to continue; look in the answer.

Problem description:Fibonacci considers the growth of an idealized (biologically unrealistic) rabbit population, as-suming that: a newly born pair of rabbits, one male, one female, are put in a field; rabbitsare able to mate at the age of one month so that at the end of its second month a female canproduce another pair of rabbits; rabbits never die and a mating pair always produces one newpair (one male, one female) every month from the second month on. The puzzle that Fibonacciposed was: how many pairs will there be in one year? The answer to this question is givenby the Fibonacci numbers. The Fibonacci numbers are a sequence of numbers given by therecursion formulae:

Fn = Fn−1 + Fn−2 ; Where F0 = 0 and F1 = 1

So the fast way is to either store all Fibonacci numbers, or at least store the previous twonumbers, such that you don’t have to calculate the entire recursion at every step.

Your task is now to create a MATLAB function, which will take a number ”n” as input,and then print/plot/return the first n Fibonacci numbers.Remarks: Remember to consider the cases where n ≤ 0, n = 1 and n = 2

20

Page 22: Programming in MATLAB - CP³-Originscp3-origins.dk/content/pdf/CP3-SRP2014/Cosmology/Matlab noter.pdf · Programming in MATLAB Authors: ... your own computer and access other computers

Solution:

� �function [fibnum] = fib(n)

%Function called fib , takes number n, and returns fibnum

%-----Init ------

if n<0

error(’Cannot calculate a negative number of Fibornacci numbers ’)

end

%Creating an appropiate sized array for storing the Fib numbers

fibnum = zeros(1,n);

%Initializing the second Fib number (first one already 0)

if n >1

fibnum (2) = 1;

end

%-----Test ------

%Create an array for plotting

j = 3:n;

%If n > 2 then we have to calculate

if n>2

%Calculate n-2 times

for i = j

% Using the recursive formulae

fibnum(i) = fibnum(i-1) + fibnum(i-2);

end

end

%Making the two arrays equally sized

j = 1:n;

%Plotting the numbers

plot(j,fibnum)� �

21

Page 23: Programming in MATLAB - CP³-Originscp3-origins.dk/content/pdf/CP3-SRP2014/Cosmology/Matlab noter.pdf · Programming in MATLAB Authors: ... your own computer and access other computers

Chapter 2

Taking your skills to the next level

2.1 FF505 - Computational Science

2.2 MM533 - Mathematical and Numerical analysis

2.3 MM532 - Iterative methods

2.4 MM534 - Differential equations

22