Programming in MATLAB

Similar documents
AMATH 352 Lecture 3 MATLAB Tutorial Starting MATLAB Entering Variables

Beginner s Matlab Tutorial

Section 1.5 Exponents, Square Roots, and the Order of Operations

Lecture 2 Mathcad Basics

MATLAB Functions. function [Out_1,Out_2,,Out_N] = function_name(in_1,in_2,,in_m)

2x + y = 3. Since the second equation is precisely the same as the first equation, it is enough to find x and y satisfying the system

MATRIX ALGEBRA AND SYSTEMS OF EQUATIONS

Creating Basic Excel Formulas

3.2. Solving quadratic equations. Introduction. Prerequisites. Learning Outcomes. Learning Style

CD-ROM Appendix E: Matlab

ALGEBRA. sequence, term, nth term, consecutive, rule, relationship, generate, predict, continue increase, decrease finite, infinite

CALCULATIONS & STATISTICS

2+2 Just type and press enter and the answer comes up ans = 4

Part 1 Expressions, Equations, and Inequalities: Simplifying and Solving

Financial Econometrics MFE MATLAB Introduction. Kevin Sheppard University of Oxford

SYSTEMS OF EQUATIONS AND MATRICES WITH THE TI-89. by Joseph Collison

u = [ 2 4 5] has one row with three components (a 3 v = [2 4 5] has three rows separated by semicolons (a 3 w = 2:5 generates the row vector w = [ 2 3

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

Session 7 Bivariate Data and Analysis

Linear Programming. March 14, 2014

14:440:127 Introduction to Computers for Engineers. Notes for Lecture 06

Equations, Lenses and Fractions

SAS: A Mini-Manual for ECO 351 by Andrew C. Brod

DERIVATIVES AS MATRICES; CHAIN RULE

CSC 120: Computer Science for the Sciences (R section)

Lecture 2 Matrix Operations

Basic Formulas in Excel. Why use cell names in formulas instead of actual numbers?

Appendix: Tutorial Introduction to MATLAB

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Algebra I Notes Relations and Functions Unit 03a

G563 Quantitative Paleontology. SQL databases. An introduction. Department of Geological Sciences Indiana University. (c) 2012, P.

MatLab Basics. Now, press return to see what Matlab has stored as your variable x. You should see:

This unit will lay the groundwork for later units where the students will extend this knowledge to quadratic and exponential functions.

Linear Programming Notes V Problem Transformations

Simple Regression Theory II 2010 Samuel L. Baker

How Does My TI-84 Do That

1.2 Solving a System of Linear Equations

Solution to Homework 2

MATHEMATICS FOR ENGINEERING BASIC ALGEBRA

To give it a definition, an implicit function of x and y is simply any relationship that takes the form:

Operation Count; Numerical Linear Algebra

[1] Diagonal factorization

MATLAB Basics MATLAB numbers and numeric formats

Session 7 Fractions and Decimals

Euler s Method and Functions

Introduction to Matrix Algebra

How long is the vector? >> length(x) >> d=size(x) % What are the entries in the matrix d?

Solving Systems of Linear Equations Using Matrices

Chapter 7: Additional Topics

7 Gaussian Elimination and LU Factorization

Review of Fundamental Mathematics

0 Introduction to Data Analysis Using an Excel Spreadsheet

MATRIX ALGEBRA AND SYSTEMS OF EQUATIONS. + + x 2. x n. a 11 a 12 a 1n b 1 a 21 a 22 a 2n b 2 a 31 a 32 a 3n b 3. a m1 a m2 a mn b m

CURVE FITTING LEAST SQUARES APPROXIMATION

MBA Jump Start Program

Below is a very brief tutorial on the basic capabilities of Excel. Refer to the Excel help files for more information.

MATLAB Workshop 3 - Vectors in MATLAB

The Dummy s Guide to Data Analysis Using SPSS

Matrices 2. Solving Square Systems of Linear Equations; Inverse Matrices

Curve Fitting, Loglog Plots, and Semilog Plots 1

COLLEGE ALGEBRA. Paul Dawkins

Microeconomic Theory: Basic Math Concepts

REVIEW EXERCISES DAVID J LOWRY

Vector and Matrix Norms

Solving systems by elimination

Engineering Problem Solving and Excel. EGN 1006 Introduction to Engineering

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

SAT Math Facts & Formulas Review Quiz

Linear Algebra Notes for Marsden and Tromba Vector Calculus

2.2 Derivative as a Function

Pre-Algebra Lecture 6

Question 2: How do you solve a matrix equation using the matrix inverse?

Updates to Graphing with Excel

Section V.3: Dot Product

Continued Fractions and the Euclidean Algorithm

Click on the links below to jump directly to the relevant section

The Center for Teaching, Learning, & Technology

Exponential and Logarithmic Functions

Summary of important mathematical operations and formulas (from first tutorial):

Unit 1 Number Sense. In this unit, students will study repeating decimals, percents, fractions, decimals, and proportions.

Microsoft Excel 2010 Part 3: Advanced Excel

8 Square matrices continued: Determinants

2. Select Point B and rotate it by 15 degrees. A new Point B' appears. 3. Drag each of the three points in turn.

Unit 7 The Number System: Multiplying and Dividing Integers

(!' ) "' # "*# "!(!' +,

Chapter 11 Number Theory

Algebra 2 Chapter 1 Vocabulary. identity - A statement that equates two equivalent expressions.

3. Mathematical Induction

Page 18. Using Software To Make More Money With Surveys. Visit us on the web at:

Quick Tour of Mathcad and Examples

Decision Making under Uncertainty

A Quick Algebra Review

Graphing Parabolas With Microsoft Excel

Notes on Determinant

Using Casio Graphics Calculators

Chapter 4. Spreadsheets

1.6 The Order of Operations

Dealing with Data in Excel 2010

Math 120 Final Exam Practice Problems, Form: A

Introduction to Matlab

Transcription:

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

Contents 0 Preparation 2 0.1 How do I get MATLAB............................... 2 0.1.1 SSH...................................... 2 0.2 Where do I buy it?.................................. 3 1 Getting started 5 1.1 Introduction...................................... 5 1.2 Using variables.................................... 6 1.2.1 Creating Variables.............................. 6 1.2.2 Retrieving the information.......................... 6 1.2.3 Automatic creation of variables....................... 7 1.3 Elementary operations................................ 9 1.3.1 Matrix operations............................... 9 1.3.2 Element-wise operations........................... 10 1.4 Graphics; including plots, figures etc......................... 11 1.5 Control statements.................................. 13 1.5.1 Boolean operators............................... 13 1.5.2 Conditional execution (if/else-statements)................. 14 1.5.3 The for -loop................................ 15 1.5.4 The while -loop............................... 15 1.6 Important build-in functions............................. 17 1.7 Create your own function............................... 18 1.8 Case: Print and plot the first n Fibonacci numbers................ 20 2 Taking your skills to the next level 22 2.1 FF505 - Computational Science........................... 22 2.2 MM533 - Mathematical and Numerical analysis.................. 22 2.3 MM532 - Iterative methods............................. 22 2.4 MM534 - Differential equations........................... 22 1

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 installed at IMADA s computers by using SSH, or you can buy your own. The downside of using SSH is that you need to be connected to the internet all the time, and the speed of your connection will 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. run programs on another computer. So the strength or whole idea of SSH is that you can use your own computer and access other computers and use their programs, for instance MATLAB which 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 distributions. So if you have any of these computers, you can jump directly to the section telling you how to connect. If you have a Windows based computer, don t worry, the help is near, it ll only require you to install two small programs called putty and XServer to do the same as the 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 on using 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 a program called putty, this you can do by using the following link: http://www.chiark.green.org.uk/~sgtatham/putty/download.html and chose the one called putty under the headline For Windows on Intel x86. putty shouldn t be installed, as it s an executable file, which you just execute every time you have to use 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 simply following the steps. When both programs are installed you open up putty and look under the Connection 2

category, expand SSH and click the Enable X11 Forwarding checkbox. In the field X display location, you now write: :0 ( colon + zero ) Now you go back to the session page. Under Host name you now write: username@login. imada. sdu.dk Then you go the box Saved sessions and give the connection a name, and press save. Now you can simply double click the saved session every time you want to SSH onto IMADA s computers. 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. When you 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 your terminal: ssh username@login. imada. sdu.dk After which you ll have to type your password, notice that the terminal wont write anything as you type your password. You do now have access to the computer and you can basically do anything with it, but you do only have the terminal to work from, which means that you can t see the user interface MATLAB haves. There are ways such that you can use the interface, one way is to use an XServer, which was standard on Macintosh, it still is in Ubuntu (probably the most Linux distributions). You can get it for Macintosh just by searching Google for XServer Mac, and download it. This you apply by using the following command in stead of the first one: ssh -X username@logon. imada. sdu.dk But use it with care, as it takes a huge amount of your internet connection, and might slow your work considerably, and it isn t always necessary to use the user interface. Again you ll have to type your password. Now as you have taken control over the computer, you can open any program by just entering its name into the terminal. So to open MATLAB, simply type Matlab 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 consider buying the program, which will make you indepent of the internet connection present. As a student the price of MATLAB and Simulink lies just around 600 dkk, and the price only differs a little deping on where you buy it. As with everything nowadays you have the following to options: 1. Buy it from the internet (digital) 1 2. Buy it in a book store (hard copy) 2 1 http://www.mathworks.se/index.html 2 The book store at SDU does sell a hard copy 3

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 you can 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 simply download it again. So you should not be afraid of having to buy it again if anything happens to your computer. On the other hand if you feel more safe by buying it in a book store and getting a hard copy, we re sure that the same terms should apply. 4

Chapter 1 Getting started 1.1 Introduction Matlab is a program build on the programming language C, and it contains functions which have been optimized for using matrices and vectors. This is fantastic when working with such things, because things as matrix multiplication happen almost without you have to think. The downside of this is however that you ll have to think, whenever you don t work with matrices and vectors, and then tell Matlab that this is just some numbers without structure. Furthermore Matlab is really suited for working with big arrays, because of the underlying C structure. So overall Matlab is really suited for solving problems involving large systems of equations, or simply handling large arrays. At the University of Southern Denmark, Matlab is especially used 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, whereas the first part will focus on getting started using Matlab, and introduces the basic stuff, which you ll need over and over again. Matlab will automatically color the code for you, which will make it easier for you to debug, when you get more experiensed. At some places in the notes we will use pseudo code, this is code that you cannot write directly into Matlab, but more explains what you should do, those will be marked by a white box, whereas rest of the code will be marked by gray boxes. But let s get started 5

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 ext to creating two types of vectors, 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 use space 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 vector and matrix by using apostrophe, so (As we ll mention in chapter 1.5.1 the double equality isn t a 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 2 on 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 data structure is basically just an easy way to store several informations on the same thing. For instance can you store informations on persons: person. name = Nicky ; person. age = 21; This can be exted 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 informations about the person. 1.2.2 Retrieving the information After you ve created your variable, you can of course retrieve the informations that you ve entered. If you re interested in everything in one variable, for instance the entire vector or the entire matrix, then you just write the name of the variable: 6

A This will now print out: A = 1 2 3 4 Notice that the semicolon at the of the previous statements silences the output, so when we above don t write the semicolon at the 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 the whole vectors/matrices. For instance if we have the vector b again then we can print out the first element by writing: b (1) Note that the first element is numbered 1 and not 0 as in most programming languages. We can 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. If you want the last value of an vector and don t know it s length, then you can use the command which will give you the last element, which we know is 4 in this case. Therefore the following will be true (Matlab returns the value 1) 1 7 == b( ) When exted 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 use some of Matlabs build in functions to create them. If you want a matrix with all elements equal 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 as you ll learn in section 1.3.1. When plotting or evaluating functions or doing for-loops (explained in chapter 1.5.3) it s often necessary to create an array, which starts at some value and then counts up or down to some value with some in-/decrement. This you do in the following way: 1 From now until chapter 1.5.1, Matlab should return 1 everytime we use the double equality ==. 7

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 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

1.3 Elementary operations Now as we have created the variables we should be able to work with them. There are basically two types of operations. Those who act on matrices and vectors, and those who act elementwise. 1.3.1 Matrix operations When dealing with matrices, it is basically just using the ordinary operators. So you can multiply 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 using the same Matlab session, you don t have to redefine it every time. If one of the matrices is a number, 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 number to 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 ways of 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 or many times, other ways are considerably faster. The typical way for normal sized matrices is to 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 or matrix, 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

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 do element-wise operations you have to tell Matlab to do so. This is for instance important when declaring a function; Here you either have to specify that it s always element-wise operations or to figure out whether it s possible for the function to have an array or a matrix as input. So the element-wise plus and minus is exactly the same, as when you add or subtract to vectors or matrices, it s always element by element. But when you want to multiply two numbers in a matrix or vector with another matrix or vector, it s no longer element-wise, so here you have to specify it. In MATLAB you specify element-wise operations by using a dot (.) in front of the operator (*). The following code will multiply 1 with 1 and 2 with 2 etc. and make a new matrix 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

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 a mathematical function. So if you have two values, you can simply use the command, otherwise you 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. Then we define a function, which deps on x 2, 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 two vectors 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 ext the above function definition to 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, such that if you plot something again it ll plot on top of what s already plotted in the figure. It ll continue 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 2 This is due to the @(x) in front of the expression. 11

This gives the following plot: 12

1.5 Control statements Control statements are exactly as the name suggests statements that control the code, which often leads to the execution of a piece of the code. There are different kinds of control statements, and the three frequently used will be discussed below. The first of them is to check whether you should execute a piece of the code, whereas the other two are to control how many times 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 the boolean 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 is larger 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 corresponds to 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 equal follows the same idea. The more interesting syntax is the result of checking the question: Is A equal B, because as we use the equality sign to assign values to variables, we can t use this alone, so the syntax here 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, this syntax 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 of comparing 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 boolean operations do not compare entire vectors or matrices, but elements. If you want to know if two vectors or matrices are in some relations to each other you can do the following: 13

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 the example 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 OR just require one of the statements to be true for it to return true. You can of course combine them 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 not equal to B. An example of using AND is that we can rewrite the vector check above to the one below. 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 with it. You can control which lines of code are being executed by using the if-statement. It simply checks if what you have written is true (equal to 1), and if it is then it executes the code. The syntax is the following if ( condition ) code Where condition is the condition that has to be true for the code to be executed. s the statement. A simple example could be: A=2 B=6 if A >0 & B >0 C=A+B As both A and B are larger than 0, 8 is assigned to C. We can ext this with the else statement. Else catches what doesn t in the if statement, so: A=2 B=-1 if A >0 & B >0 C=A+B 14

else C=A-B Now we won t access the if case because B is less than zero, so we enter the else case, and C now contains the value -1. To ext this further we can use elseif, which checks the first if case, if this isn t true, then it checks the elseif cases, and in the 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 following syntax for i = 1: n code This will repeat the code, n times. Each time we go through the loop, i will be the value corresponding 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 want to store the values at different places in an array. An example could be: for i = 1:6 A(i) = i ^2; Then the loop will return a vector A with 6 elements, and each element is equal to the index squared. In the for-loops i can also start with a different value than 1, by just changing the 1 to another 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; However, since we now have increments that are different from 1, we can no longer use i as index, 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 from the while loop. However the while-loop is often used when you don t know how many times the code should be repeated, but you want it repeated until some other property is fulfilled. The syntax is: while ( condition ) code 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; 15

This while loop is repeated until i > 6, so this piece of code does the same as the for-loop before. It can be much different, for instance: a=8 b=4 while (a ~=1 & b ~=1) a =0.5* a; b =2* b; ATimesB = b; Then ATimesB will contain the value 32 = 8 4 16

1.6 Important build-in functions This section will provide you with the most important functions build into Matlab. For all functions in MATLAB you can write: help function where function is substituted by the function you want to know more about without the quotation marks. Matlab will then provide you with different information on how to use the function. 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 e x 4. log(): Natural logarithm: x ln x The next functions work on arrays, so if you give the function a matrix, then it ll return an array 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

1.7 Create your own function You have now made it so far that you are ready to put everything you ve learned together into a MATLAB function. A function is a collection of all (or some of) the previous learned commands, where they will be executed in a chronologically way, which in general is from top to bottom. So this is important if you want to store your programs for later use, and for easy access if you made a mistake, then you don t have to retype everything again. Another benefit is that you can create a function which deps 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 each containing one method, so you get a structure of the program, which will make it easier to debug, when you make a mistake. First we need to create a file, which will eventually contain our function, these files are named as: nameoffile. m and the easiest way to create such file is to navigate to the folder, where you want to save your file, 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 to this. Now you have created the file, where you can write your function inside. Every function starts with: function [out1, out2,...] = nameoffile (in1, in2,...) Where out1, out2,... are the variables that the function returns, nameoffile is the name of the function, the first function inside a file, should have the same name as the file (without the.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 takes one input x and gives one output, namely res. 18

In this function we can use what s previously learned, so a simple function we can create is a function calculating the sum over i for i = 0 to i = x. So the function takes the length of the sum as input, in our program called x. Then we create an array containing the numbers from 0 to x. Then we have to sum them all up, for this we use the sum function, so now we have: 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 command window, and type the following: x = fib (10); This will call the function fib, give it the argument 10, then the function calculates the sum and returns it to the variable x, then you can print out x, and you get the following: 19

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 the things you ve just learned. So our suggestion, is that you read the problem description and try for yourself to create the function, if you get stuck, try to ask a fri. If you get completely stuck and are clueless about how to continue; look in the answer. Problem description: Fibonacci considers the growth of an idealized (biologically unrealistic) rabbit population, assuming that: a newly born pair of rabbits, one male, one female, are put in a field; rabbits are able to mate at the age of one month so that at the of its second month a female can produce another pair of rabbits; rabbits never die and a mating pair always produces one new pair (one male, one female) every month from the second month on. The puzzle that Fibonacci posed was: how many pairs will there be in one year? The answer to this question is given by the Fibonacci numbers. The Fibonacci numbers are a sequence of numbers given by the recursion formulae: F n = F n 1 + F n 2 ; Where F 0 = 0 and F 1 = 1 So the fast way is to either store all Fibonacci numbers, or at least store the previous two numbers, 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

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 ) % 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; % -----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); % Making the two arrays equally sized j = 1:n; % Plotting the numbers plot (j, fibnum ) 21

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