Matlab practicals manual

35 downloads 135 Views 763KB Size Report
Each chapter of this manual corresponds to one of the 4-hour MAT- ... First practical How to use the main features of Matlab (manipula- .... M. Tissier, 8-8- 2012.
MSc course Fluvial systems (GEO4-4436):

MATLAB MANUAL Marion Tissier Maarten Kleinhans August 30, 2014

Contents 1 Scripts, matrices and syntax 1.1 Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.1.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.1.2 Creating you own work-directory . . . . . . . . . . . . . . . . . . . . 1.1.3 Introductory exercises . . . . . . . . . . . . . . . . . . . . . . . . . . 1.2 Script files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.3 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.3.1 Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.3.2 Manipulating arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.3.3 Operations on arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.3.4 Matlab built-in functions for arrays . . . . . . . . . . . . . . . . . . . 1.4 Visualising data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.5 Final assignment : Analysis of the Rhine flow discharge measured at Lobith 2 Tests, loops and functions 2.1 Relational and logical operators

. . . . . . . . . . . .

5 5 5 6 6 10 13 13 14 17 19 23 29

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

33 33

1

. . . . . . . . . . . –

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . part I

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

2.2

. . . . . .

37 37 39 44 47 50

3 Numerical modelling 3.1 A very simple morphodynamic model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.2 Flow computation: backwater equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.3 Morphodynamic model with flow computation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

55 55 58 60

4 Creative Matlab exercise

65

2.3 2.4

Flow control . . . . . . . . . . . . . . . 2.2.1 if-statements . . . . . . . . . . 2.2.2 for-loops . . . . . . . . . . . . . 2.2.3 while-loops . . . . . . . . . . . User-defined functions . . . . . . . . . . Final assignment : Analysis of the Rhine

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . flow discharge measured at Lobith

2

. . . . . –

. . . . . . . . . . . . . . . . . . . . part II

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

Begin at the beginning • Each chapter of this manual corresponds to one of the 4-hour MATLAB practicals. Below you can find a short description of their content. First practical How to use the main features of Matlab (manipulation of arrays of data and use of script files). First data analysis and visualisation. Second practical How to write more complex programs using tests, loops. How to create your own functions and use them in a script file to analyse data. Third practical Introduction to the modelling of physical processes. During this practical you will build a simple morphodynamic model. Fourth practical Creative assignment, where you should be able to answer a research question using Matlab. • During the practicals, you will have to work in couples. Change partner every practical. • The Matlab assignments should be handed in before Friday 4:00 pm in the week that the computer practical took place. The different files (Matlab code and answers to the questions) should be combined in a zip-file and sent to [email protected]. The answers to the questions should be written as comments in the script files or (if specified) in a separate word document. 3

The evaluation of the codes will be based on three main criteria : - does the program run? - does it do the right thing? - can we read/understand it easily? (= is it commented enough?) • You will often get error messages while running your Matlab programs. Do not panic and carefully read the displayed messages. Solving them without help is part of the learning process! The devil is in the details: most errors are in syntax. To understand what is going wrong with the larger code and data matrices, it may help to play with very small and simple matrices first.

4

Chapter 1

Scripts, matrices and syntax 1.1

Getting started

To start MATLAB, navigate into the program list and click on ”Matlab.exe”.

1.1.1

Overview

Your Matlab window should roughly look as in Figure 1.1. If it does not, click on ”View” in the menu bar and select ”Desktop layout”, ”Default”. Four main divisions appear in the window : - ”Current folder” : displays the content of the current work-directory, - ”Workspace” : lists the variables assigned by the user, - ”Command history” : shows the last commands used,

5

- ”Command window” : where the commands are typed and the outputs displayed. In the following, we will mainly work in the ”Command window”, highlighted in Figure 1.1.

1.1.2

Creating you own work-directory

The current directory is displayed on the top part of the Matlab window (see Fig. 1.1). We advise you to start every new practical with creating a new work-directory. To do that, click the ”browse for folder” button (see Fig. 1.1) right to the ”Current directory” drop-down list on the Matlab button-bar. You can then browse through the directories and create a new folder at the desired location using the ”New directory” button. For instance, create a first folder called Matlab_practicals. In this folder create a folder called Practical1 in which your will be working on today. You can also use this button to move to an already existing directory.

1.1.3

Introductory exercises

We will perform in this section some introductory exercises where Matlab is basically used as an ”advanced” calculator. • Type in the command window a = 32.8 and then press ”enter”. The following lines appear: >> a = 32.8 a = 32.8000 With this command, we defined a new variable a and assigned the value 32.8 to it. • Now let’s type: >> b = 3*a^2 and then press ”enter”. We defined a new variable, b, equal to 3 times the value of a squared. Its value is displayed in the command window. The basic operations and their symbols are presented in Table 1.1. 6

Figure 1.1: Organisation of the Matlab window

7

Operation Addition Substraction Multiplication Division Exponentiation

Symbol + − ∗ / ˆ(e.g. 2ˆ3 = 8)

Table 1.1: Basic operations and associated symbols • Type now: >> whos and then press ”enter”. The following lines are displayed in the Matlab command window: Name Size Bytes Class a 1x1 8 double b 1x1 8 double This command displays the different variables which have been previously defined (a and b), and gives their main characteristics (see presentation of arrays, §1.3, for more explanations). These variables are now listed in the ”Workspace” sub-window, and can be visualised by double-clicking on them. • Use the command clear, and then the command whos again. What is displayed? Any interpretation? NB: To get more information about the function clear, type help clear and press ”enter” in the command window. • Type now: >> c=a*30/200 and then press ”enter”. We are defining a new variable c, as function of a, which has been deleted previously (clear). The command cannot be executed since a is not defined anymore. An error message, in red, appears in the command window. 8

Function sin(), cos(), tan() asin(), acos(), atan() abs() sqrt() round() ceil() (or floor()) log(), log10() exp()

Description sine, cosine and tangent (arguments in radians) inverse sine, cosine and tangent absolute value root square (equivalent to ˆ(0.5)) round towards nearest integer round towards plus (or minus) infinity natural logarithm, logarithm base 10 exponential

Table 1.2: List of some mathematical functions • Type: >> a =-4, c=a*30/200 and then press ”enter”. Two commands are written in the same line, separated by a comma. They are executed successively by Matlab. a is first defined and then used in the calculation of c. • Type now the same command, but replace the comma by a semicolon. What is the difference? And if you add a semicolon at the end of the line? • Type now: >> c_bis =abs(c) In this command, we applied the Matlab function abs() to the variable c. The result of this operation is a second variable, c_bis, which is the absolute value of c. c is called input argument of the function abs. c_bis is the output argument. Numerous elementary mathematical functions are already implemented in Matlab. The table 1.2 presents a selection of the most commonly-used elementary functions. Type help elfun in the command window for an extensive list of these functions.

9

Remarks - To obtain help in Matlab: help function name displays information about the function directly in the command window; doc function name opens a separate window where a more detailed help is displayed. The explanations usually include a few examples, which are worth studying carefully; lookfor keyword looks for all the Matlab functions related to the keyword; - The commands you’ve recently entered can be retrieved by pressing the up-arrow key; They are also displayed in the ”Command history” window. - Variable names must start by a letter, and can be followed by character chain, including letters, numbers and any symbols except those used as mathematical operators by Matlab (+,-,*,...) or punctuation signs. Variable names can contain up to 31 characters; When no variable name is specified, a temporary variable name, ans, is generated by default. - Try to use the name of a function to name one of your variables.

1.2

Script files

A script, also called program, is a succession of Matlab commands written in a separate text file. Using script files allows you to organize and save series of commands. These scripts can be edited/extended/corrected anytime you want, and executed several times. Writing the commands into a script is necessary when you perform advanced data analysis, since it allows you to check/improve your methodology, but also to be sure to perform the exact same data processing for several datasets for instance. The scripts are user-created text files which can be written using Matlab editor. Type: >> edit 10

The Matlab editor window opens. In this window, you can write series of commands and save them. The resulting script is saved as *.m file. The ”new script” button (see Fig. 1.1) can also be used to open the editor. It is important to add comment lines to your scripts to make them easier to understand. This is particularly useful when scripts are re-used long after they have been created. In a script file, anything written to the right of a percentage symbol is considered as a comment and will be ignored during the execution. In the Matlab editor, the comments appear in a different color (green by default). It is recommended to always give a similar structure to the script files. An example of structure for a ”classic” script file is given below: % Header Describe the script in a few words (objective, date of creation, author) % Initialization Clear your workspace using the command clear Close all the figure windows (close all) Define the main variables, load data files used in the script % Calculations Execute the calculations % Output and visualisation Commands to display the results, plot graphics, save variables A simple example of script can be find below:

11

% Example of a very simple Matlab script % M. Tissier, 8-8-2012 % Initialization clear displacement = 12; time = 10;

% displacement (m) % duration (s)

% Calculation v = displacement/time;

% migration speed (m/s)

% Output disp([’The migration speed is ’ num2str(v) ’m/s’]) Once the script has been saved, you can run it by typing its name (without the ”.m” extension) in the ”Command window” and then press ”enter”. When a script file is executed, Matlab execute the commands in the order they are written. EXERCISE 1 The aim is to calculate flow velocity and water depth in a river from known variables and parameters. (Find out through a web search what the difference is between ”variable” and ”parameter”.) Use the law of Chezy (see Kleinhans (2005) paper for equations). The flow resistance parameter for this river is C = 44 m0.5 /s, the bankful discharge Qbf = 2500 m3 /s, the channel width W = 500 m and the channel gradient S = 1.6 × 10−4 m/m. The commands will be written/organised in a small script file called Exercise1.m, saved in your current directory. Do not forget to comment the file, and give meaningful names to the variables. HINT: 1.6 × 10−4 can be written in Matlab as 1.6e-4.

12

1.3 1.3.1

Arrays Definition

The array is the fundamental form that Matlab uses to store and manipulate data. This way of storing data allows for efficient calculations and analysis over entire datasets. An array is basically a list of elements (numbers or characters, see below) organised in rows and/or columns. Different types of arrays can be defined: - The simplest array, or scalar, contains only one value (1 row, 1 column). - The vector is a one-dimensional array which is basically a row or column of values. - Two-dimensional arrays are also called matrices, and are characterized by their amount of rows and columns. - Multi-dimensional arrays (with 3 or more dimensions) can also be defined. These arrays can contain different type of data, for instance: - Integers : whole numbers (-10 -4 1 0 3 12) - Floating numbers : fractional numbers (3.271 -2345.17...) - Characters : text ASCII character (a b z / ] ?) In the two first cases, they are called double arrays, and in the third, character array. In this section, we will learn how to create arrays in Matlab, extract the relevant information from one of them, and perform calculations with these arrays.

13

1.3.2

Manipulating arrays

Creating vectors and matrices • Type: >> M = [1 2 5 10; 3 4 -2 7] and then press ”enter”. A 2-by-4 matrix, called M, has been created and is now displayed in the command window. When defining an array other than a scalar, brackets [ ] should be used. The elements belonging to a same row are separated by a ”space” (or a comma), while semicolons are used to skip to the next line of the array. • Use the whos command, and check the information concerning the new variable M. The size of the array is displayed. It gives 2 × 4, which means that M has 2 rows and 4 columns. This information can also be retrived using the function size(): >> size(M) which returns a 1 × 2 array containing the number of rows and columns of M. • Type now >> u=[2; 4; 6; 3] What kind of array do you obtain? Type now [n_r n_c]=size(u); and check the values of n_r and n_c. What do they contain? • Vectors can also be created in the following way. Type >> k = [1:1:6], l = [1:2:6], m=[12:-3:0] and analyse the outputs. Here vectors are defined in the following form: [begin:interval:end], where interval can be any positive or negative number. Remark: When interval is equal to 1, it does not need to be specified. 1:6 returns the same vector as 1:1:6. • Similar commands can be applied to create matrices. Type: >> Z = [1:9; 3:11] and then press ”enter”.

14

• Type now >> Z = [1:8; 3:11] Why does it produce an error? Concatenation It can be useful to combine several related arrays in one unique array, for instance when two datasets are related and should be treated together. This can be done thanks to the operation of concatenation (=joining the arrays one after the other). • Type for instance: >> a = [1:3] >> b = [4:6] >> c = [a b] The space is used in this case to concatenate the arrays horizontally (alternatively, you can use the function horzcat(), e.g. c = horzcat(a,b)). • Type now >> d=[a ; b] In this case the arrays have been concatenated vertically (see also vertcat()). • Concatenation can be used to add an extra column (or line) to a matrix. Type >> e = [10;20] >> f = [d e] and analyse the outputs. • Vertical (horizontal) concatenations can only be performed if the arrays have the same number of columns (rows). Type: >> [f; a] Do you understand the error message?

15

Manipulating arrays by their subscripts Elements of arrays are usually identified by their position (row and column numbers), also called subscripts. The following table shows how the different elements of a 3 × 2 matrix can be identified using their subscripts: (1,1) (2,1) (3,1)

(1,2) (2,2) (3,2)

• Type for instance >> M(2,4) It returns the element located at the 2nd line, 4th column. Type now >> M(3,4) Do you understand the error message? • This notation can be used to alter a value of an array. Type for instance: >> M(1,2)=0 • Several elements can be selected using a vector instead of a scalar subscript. Type for instance >> M(2,[1 3]) The first and third elements of the second row of the matrix M are displayed. • To create a vector containing the entire row, type for instance: >> vectM = M(2,:) Similarly M(:,2) would refer to the second column of M. • Replace the elements of the first column of M by 10. Manipulating arrays by their indices

16

• For a vector, it is easier to define the position of an element using only one number, called its index, which is its position in the row or the column. For instance, vectM(2) is equivalent to vectM(1,2). Several elements of vectM can also be selected using a vector containing the relevant indices. Execute for instance: >> vectM([1:3]) • Similar conventions can be used for matrices. The elements are then numbered column by column, starting from the top left element and progressing downward. For a matrix of dimension 3 × 2 (note that the index of a given element will depend on the size of the matrix), we have: (1) (2) (3)

(4) (5) (6)

Type the following commands and compare the output: >> M(5) >> M(1,3) • How would you call the element M(1,4) using indices?

1.3.3

Operations on arrays

Operations between a scalar and an array • Multiplication by a scalar: All the elements of the array are multiplied by the scalar. Type for instance : >> 2*M and check the output. Remark: 2*M is equivalent to M*2.

17

• Addition (subtraction) with a scalar: Type >> M-2 The scalar is added (subtracted) from each element of M. Operations between two matrices • Addition (subtraction) of two matrices. These operations can only be applied to matrices of identical size. The resulting matrix is obtained by adding (subtracting) their corresponding elements. Example: >> M-f • Multiplication of two matrices. This operation is executed according to the rules of linear algebra. Let’s define two matrices A and B such as:     1 3 1 0 2 A= and B =  4 1  . 5 10 7 2 2 The element (i, j) of the matrix C = A ∗ B is defined as : C(i, j) =

n X

A(i, k) ∗ B(k, j),

k=1

where n is the number of columns of A (=number if rows of B). C is therefore equal to:     1∗1+0∗4+2∗2 1∗3+0∗1+2∗2 5 7 C= = 5 ∗ 1 + 10 ∗ 4 + 7 ∗ 2 5 ∗ 3 + 10 ∗ 1 + 7 ∗ 2 59 39

18

Operation between two matrices Addition

Matlab expression A+B

Multiplication

A*B

Element-by-element multiplication Element-by-element division

Condition size of A = size of B number of columns of A = number of rows of B

A.*B

size of A = size of B

A./B

size of A = size of B

Table 1.3: Summary of the main operations between two matrices A and B. The requirements in term of matrix size are also indicated. Element-by-element operations • To perform a multiplication element-by-element, it is necessary to use the operator ”.*” instead of ”*”. Type for instance >> M.*f and examine the result. Type now the same command but without the dot. Do you understand the error message? (see conditions in Table 1.3). Similarly, element-by-element division is obtained using the operator ”./”, and element-by-element exponentiation using ”.^”. • These operations can be combined. Type for instance: >> MM = vectM.^2 + vectM

1.3.4

Matlab built-in functions for arrays

Elementary mathematical functions The functions defined in Table 1.2 can also be applied to arrays. In this case, the function is applied to each matrix element individually, and returns an array of the same size as the input 19

argument. Compare the outputs of the two following commands: >> M/3 >> round(M/3) Transposition Enter the following command >> v = transpose(u) and compare v to u. Now look at transpose(M) and compare it with M. Do you understand how the transposition function works? transpose() changes the rows of the matrix into columns, and vice versa. As a consequence, a matrix of size n × m will turn into a matrix of size m × n containing the same elements organised in a different way. This operation can also be performed using the symbol ’ just after the name of the array. u’ is therefore equivalent to transpose(u). Creation of arrays The functions zeros() and ones() can be used to create a matrix. Type for instance: >> C = ones(3,5) Do you understand the meaning of the arguments of this function? As expected, the function zeros() is similar to ones() but returns a matrix filled with zeros. • With the help of the functions introduced previously , create a matrix of size 20 × 30 containing only 5s. Data analysis The main Matlab functions available to perform data analysis are summarized in Table 1.4. Some examples of the use of these functions are given below. • Type the following commands: >> mean(vectM), median(vectM), sum(vectM) Each of these functions, applied to the vector vectM, returns a scalar, which is equal to (respectively) the averaged value of the vector , its median value and to the sum of its elements. • Type: >> vmax =max(vectM) 20

vmax is the largest value of the vector vectM. In some practical cases, it is important to know when the maximum value has been reached, that is to say what is the position of the largest value in the original vector. In order to get this information, the function max (or min) can be used with two output arguments. Type >> [vmax ind]=max(vectM) The second argument (ind) is the index of the maximum value in the vector. The function min works in a similar way. • Type now: >> s = sort(vectM) Compare s and vectM. • These functions can also be applied to matrices. In this case, they handle each column separately. The output is therefore a vector of length the amount of columns. Type for instance: >> mean(M) and analyse the result. When M is a matrix, mean(M) is a row vector containing the mean value of each column. • It is generally possible to specify the direction along which the computations have to be performed as an additional input argument. Type for instance: >> mean(M,1) >> mean(M,2) and compare the results. Do you understand the meaning of the second input argument? The functions median, min, max and sum work in a similar way. You can check the Matlab help to find out how to choose the direction of computation for these functions. • An alternative approach is to apply the functions after transposition of the matrix. Type for instance: >> mean(M’) and compare with mean(M,2).

21

max mean median min std var prctile sum sort

Maximum value Average or mean value Median value Smallest value Standard deviation Variance Percentile values (the percent of interest should be specified) Sum of the elements Arrange the elements in ascending order

Table 1.4: Some important Matlab functions for data analysis EXERCISE 2 Make a new file called Exercise2.m in your work-directory, where the commands needed to solve the following assignment will be written. 1. Create the following matrix: 

16  5 A=  9 4

3 10 6 15

 2 13 11 8   7 12  14 1

2. Define a vector A1 containing the first row of A. Define a scalar, sumA1, equal to the sum of its elements. 3. Create now a vector sumRows P4 where each element contains the sum of the elements of one of the row of A. For instance, sumRows(1) = k=1 A(k, 1). Can you do it in only one line of command? 4. Create a vector containing the sum of the column of A. What do you notice?

22

1.4

Visualising data

How to make a simple 2D-plot : example • Define the following vectors: x = -pi:.1:pi; y = sin(x); y2 = cos(x); • Type figure,plot(x,y) The first command, figure, opens a new figure window, called Figure 1 by default since no other figure has been opened previously. The plot command is then executed in the newly created figure. • Type now plot(x,y2) The new plot has replaced the previous one in the figure window. To display the second graph on top of the first one, the command hold on should to used. Type: figure,plot(x,y) hold on,plot(x,y2,’r’) A new figure, called Figure 2 by default, is created, and contains the two plots on top of each other. For the second plot, the line color is specified using the additional argument ’r’, with r standing for red. • Title, labels on the x- and y-axis and legends can now be defined. Type the following commands one by one and analyse their effects on the figure: title(’Example plot’); xlabel(’Radians’); ylabel(’Function Value’); legend(’sine’,’cosine’);

23

• To specify the limits of the x- and y-axis, type: for instance axis([-pi pi -2 2]) Do you understand the meaning of these 4 numbers? • The figure command can also be used with an input argument which is a positive integer, as for instance figure(1). The number corresponds to the number of the corresponding figure window. If the Figure 1 does not exist yet, this command will create it. If this figure already exists, it becomes the active figure window. This means that new plot commands will be executed in this figure. Type for instance: figure(1), hold on, plot(x,-y,’.’) Because of the argument ’.’, the vectors are plotted as a cloud of points. • plot can also be used without specifying the x argument. Type: figure,plot(y) The elements are now plotted as a function of their position in the vector: y(1) at x = 1, y(2) at x = 2, etc. • Multiple plots can also be displayed in one figure. This can be done using the command subplot(a,b,c) where a, b and c are integers, and c is less than or equal to the product a*b. This command divides the figure in a*b sub-figures, organized in a rows and b columns. To obtain 2 figures on top of each other, the following lines should be used: figure subplot(2,1,1);plot(x,y) subplot(2,1,2);plot(x,y2,’g’) • It is possible to display on the figure the coordinates of a given data point using the ”data cursor” button presented in Figure 1.2. Select this button and click on a data point. • You can now close all the figures using the command: close all The function plot is the basic Matlab function for 2D plots. Numerous options are available to customize your plots. Some examples are given below: 24

- plot(x,y,’r’): red solid line - plot(x,y,’--r’): red dashed line - plot(x,y,’--r’,’linewidth’,2): thick red dashed line - plot(x,y,’*g’): the points are marked with green asterisks (no line) - plot(x,y,’+-r’): solid red line with points marked with a plus sign. The tables below show some of the colors and markers available. We advise you to look at the Matlab help (type doc plot for instance) for a more extensive description of the plotting options. You can also navigate in the help window to learn more about the numerous ways to visualise data in Matlab.

red green

r g

plus sign asterisk

Color specifiers blue b black k cyan c yellow y

+ *

Marker specifiers square s triangles v, < or >

magenta white circle cross

m w

o x

EXERCISE 3 This exercise is based on the dataset contained in the file MPMtransportdata.xls. Meyer-Peter and Mueller (1948) (abbreviated MPM) graphically report gravel transport data and derive their famous empirical bedload transport predictor from this dataset. Wong and Parker (2006) recovered the original data and re-analysed it to find that the original fit by MPM was wrong. Here you will plot the data in nondimensional form and calculate a predicted transport. The Kleinhans 2005 paper contains all the equations necessary to solve this exercise. Remark: We assume that the density of the water is 1000 kg/m3 .

25

Figure 1.2: Figure window

Remarks : • It is recommended to test parts of your script regularly. An easy way to do it is to copy-paste these parts into the command window and then press ”enter”. Alternatively, you can select the part of the text you want to run and then press ”F9”. • Always terminate the command by a semicolon if you do not want the result to be displayed in your command window. This is important when working with large datasets. 1. Make a new script file called Exercise3.m in which the series of commands necessary to solve this assignment will be written. Do not forget to clear your workspace and close the figures at the beginning of your script. 2. Download the file MPMtransportdata.xls and save it in your current work-directory. You can now load the data using the following line: 26

dataMPM = xlsread(’MPMtransportdata.xls’); Thanks to the function xlsread(), Excel sheets can be read and loaded in your workspace. The output of the function is an array called dataMPM which contains the same information as the Excel sheet, but without the description of the data (only numbers). Check its number of rows and columns and compare a few values with the initial Excel sheet. 3. Define vectors containing the channel width W, the depth h, the slope S, the median grain size D50, the specific gravity of the sediment s and the sediment transport rate qs. 4. From these vectors, calculate the total shear stress. The result will be a new vector, called tau for instance. 5. Calculate the Shields parameter using the shear stress previously defined. 6. Calculate the Einstein parameter. 7. Plot the sediment transport rate (y-axis) as a function of the shear stress (x-axis). Plot the data in log-scales for both the x- and y- axis. To do that, the function plot() can be replaced by loglog(). loglog is basically the same as the plot function, but with logarithmic axis, and can be used with the same input arguments (see Matlab help for more details). Give an appropriate title to the plot, as well as names to the x- and y-axis. HINT: To write Greek letters in the text of a Matlab figure (axis labels, title, legend, etc.), use the following characters: α β

\alpha \beta

τ Φ

 θ

\tau \Phi

\epsilon \theta

φ λ

\phi \lambda

To write subscripts or superscripts, use the symbols _ and ^. For example, to display qs (m2 /s), you should write q_s (m^2/s), and to display D50 (2 characters as subscript), use D_{50}.

27

8. Plot in a new figure the data in a nondimensional form, i.e. the Einstein parameter (y-axis) as a function of the Shields parameter (x-axis). Give an appropriate title to the plot, as well as names to axis. Compare with the previous figure : does the adimensionalization seem efficient? 9. Plot the MPM prediction as a additional red line in the second figure. To plot this line, first define two vectors x and y such as x contains a range of values reachable by the Shields parameter (θ) and y = 8(x − θcr )1.5 (see eq. (30) in Kleinhans 2005). We use θcr = 0.047. 10. In the same figure, plot a vertical line corresponding to x = θcr . 11. To further analyse the data, we will now remake the figures of the questions 7 and 8 using the function scatter(). scatter is a function which allows you to plot the data as circles of different sizes and colors depending on their characteristics. Check the Matlab help to understand how to use the function scatter() and what are its input arguments. The lines below are an example of use of the function: figure; scatter(tau,qs,10,s,’filled’); set(gca,’xscale’,’log’,’yscale’,’log’); colorbar; Execute these lines one-by-one and analyse the outputs. How many colors are displayed in the figure and why? do you understand why the size of the circles does not vary? 12. Create a new figure, which will be divided in two subplots. - In the top subplot of the figure, plot sediment transport (y-axis) as a function of shear stress (x-axis), with colors depending on the grain size D∗ (Bonnefille number). - On the bottom part, plot the same figure but in its nondimensional form. Add colorbars to both plots. For a better distribution of the colors, it is recommended to use the logarithm of the Bonnefille number as the ”color vector” argument of the function scatter. 13. Look at the data plotted in non dimensional form. One set of points seems to follow a different trend than the others. To which range of D∗ does it correspond? 28

1.5

Final assignment : Analysis of the Rhine flow discharge measured at Lobith – part I

In this exercise, we will perform some analysis on a dataset containing the flow discharge of the Rhine measured at Lobith (where the Rhine enters the Netherlands) for the period 1901-2000 AD. The dataset is given in the text-file Qlobith19012000.txt as an array. Each element of this array is the discharge in m3 /s for 1 day, and each column corresponds to one year (first column = 1901, last column = 2000).

Preliminary analysis 1. Create a new script file called Lobith1.m in which the assignments of the exercise below are executed. Start the script by clearing your workspace and closing the windows. 2. Load the new dataset. As the data are stored as a text (ASCII) file, the following command should be used: Q=load(’Qlobith19012000.txt’); Check the size of the array Q. Do you understand how it is organised? 3. The data corresponding to the 29th of February are included for each year, leading to a number of lines of 366. Display the 20 first elements of the row corresponding to the 29th of February. What do you notice? Remark: NaN stands for ”not a number”. It is often used to represent missing values in datasets. 4. To obtain an overview of the dataset, use the following command: figure,plot(Q) In this command, the function plot is applied to a matrix instead of a vector. plot handles each column (and therefore each year of data) separately. As a result, each line appearing in the figure corresponds to the evolution of the discharge for a given year. Give a title to the figure and names to the x- and y-axis. 5. Zoom on the figure around the 29th of February (you can use the ”zoom” buttons presented in Figure 1.2 or redefine the x-axis limits using xlim()). How are the NaN-values handled by the function plot? 29

6. Create a vector called year containing the years when the data were collected, as well as a vector days containing the day numbers (1=first of January). Analysis of one year of data 7. Create a new vector called Lobith1916 containing the flow measured at Lobith in 1916. 8. Determine the mean and median discharges for this year. Compute also the maximum and minimum values of the discharge. When were these values reached? 9. Compute the mean discharge for the following year (1917). What do you obtain? To understand better what is happening, check the results of the following operations: >> NaN + 10 >> 20 * NaN This explains why we cannot compute directly the mean value for a year without 29th of February. 10. To ignore the NaN values in the computations, alternative functions can be used, such as nanmean, nansum, etc. Use the Matlab help for a description of these functions and compute the mean discharge in 1917. Statistics over the entire data set 11. Build a vector of size 1 × 366, where each element is the discharge for a given day averaged over 100 years. 12. Plot this vector as a function of the time. When are the highest mean discharges occurring (which month?)? Plot in the same figure the maximum et minimum values for each day (use different type of lines to differentiate the curves). Add names to the axis and a legend to the graph. 13. Create a vector containing the annual flood discharges for the 100 years of data. 14. Compute the mean annual flood discharge over the entire period.

30

15. Compute the median value of the annual flood data as well as the 75th, 90th, 95th percentiles (see http://en.wikipedia.org/wik for definition). 16. We will now use the annual flood discharge data to build a flood-frequency curve, which is a graph showing the relationship between flood magnitude and their recurrence interval for a specified site. The recurrence interval (T r) of a flood is a statistical measure of how often a flood of a given magnitude (QT r ) is likely to be equalled or exceeded. For instance, the ”fifty-year flood” (Q50 ) is one which will, on the average, be equalled or exceeded once in any fifty-year period. Follow the following procedure to compute the recurrence interval: - Create a vector QT r containing the annual flood discharges sorted in ascending order. - Define a vector R of same length as QT r containing the ”ranks” of the discharges. The largest discharge of QT r should have a rank equal to 1, and the smallest a rank equal to N, where N is the number of years for which we have flood data. - The recurrence interval T r (in years) can then be computed using the formula: T r = (N + 1)/R. You can now plot QT r versus T r : this is the flood-frequency curve. Use logarithmic axis for a better display of the data. Add a title and labels to the axis. 17. Read in the figure what is the magnitude of the fifty-year flood (use the data cursor button indicated Fig. 1.2 to help you). What about the 100-year flood? (the answers should be written as a comment in your script file). Remark Numerous Matlab functions are available to study the distribution of data and the occurrence of a given event. Histograms can be built using the function hist, the distribution of the data can be compared with different probability distribution with the help of probplot, etc.

31

PRODUCTS TO HAND IN Exercises 1 to 3 and final assignment (Section 1.5). Please note that only the relevant information should be displayed while running the scripts ⇒ use semicolons to avoid the display of endless lists of numbers!

32

Chapter 2

Tests, loops and functions 2.1

Relational and logical operators

Relational operators A relational operator (see Table 2.1) compares two numbers (or arrays) to determine if a comparison statement (e.g., a < b) is true or false. • If the comparison statement is false, it returns a zero. Type for instance: >> 3> 3> A = [1:2:10;10:-2:1] 33

and then type >> E = (A> B = [3 7 1 8 3; 1 45 0 2 9] >> F = (A> G=(A==B) Do you understand the output? • Arrays such as E, F and G, resulting from relational and logical operations, are called ”boolean” or ”logical” arrays. They can be used to select elements from another array. Type: >> a = A(E) A new vector, a, is defined, and contains the elements of A corresponding to the locations where the ”logical” matrix E was equal to one. It therefore contains the elements of A smaller than 5. The matrix E can be used to extract elements from any other matrix, as long as all the matrices have the same size. Type for instance: >> b = B(E) and interpret the result.

34

Description Less than More than Less than or equal to More than or equal to Equal to Not equal to

Symbol < > = == ∼=

Table 2.1: Description of the different relational operators and their symbols in Matlab Of note, it would have been possible to write directly (without defining separately the logical array E): >> a = A(A> b = B(A> H=(B>2)&(B> u=[32 6 4 9 -6 14] >> v=(u>7) >> ind = find(v) find returns a vector, ind, containing the indices of the non-zeros values in v, that is to say the indices of the elements of u larger than 7. Again, the two last lines could have been written in one time as: >> ind = find(u>7) • Type now: >> ind2 = find(A