matlab practicals manual

67
MSc course Fluvial systems (GEO4-4436): MATLAB MANUAL Marion Tissier Maarten Kleinhans August 30, 2014

Upload: others

Post on 11-Feb-2022

16 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Matlab practicals manual

MSc course Fluvial systems (GEO4-4436):

MATLAB MANUAL

Marion TissierMaarten Kleinhans

August 30, 2014

Page 2: Matlab practicals manual

Contents

1 Scripts, matrices and syntax 51.1 Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

1.1.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.1.2 Creating you own work-directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61.1.3 Introductory exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

1.2 Script files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.3 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

1.3.1 Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131.3.2 Manipulating arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141.3.3 Operations on arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171.3.4 Matlab built-in functions for arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

1.4 Visualising data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231.5 Final assignment : Analysis of the Rhine flow discharge measured at Lobith – part I . . . . . . . . . . 29

2 Tests, loops and functions 332.1 Relational and logical operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

1

Page 3: Matlab practicals manual

2.2 Flow control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372.2.1 if-statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372.2.2 for-loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392.2.3 while-loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

2.3 User-defined functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472.4 Final assignment : Analysis of the Rhine flow discharge measured at Lobith – part II . . . . . . . . . . 50

3 Numerical modelling 553.1 A very simple morphodynamic model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553.2 Flow computation: backwater equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583.3 Morphodynamic model with flow computation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

4 Creative Matlab exercise 65

2

Page 4: Matlab practicals manual

Begin at the beginning

• Each chapter of this manual corresponds to one of the 4-hour MATLAB practicals. Below you can find a shortdescription 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 functionsand use them in a script file to analyse data.

Third practical Introduction to the modelling of physical processes. During this practical you will build asimple 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 practicaltook place. The different files (Matlab code and answers to the questions) should be combined in a zip-file andsent to [email protected]. The answers to the questions should be written as comments in the script files or (ifspecified) in a separate word document.

3

Page 5: Matlab practicals manual

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 thedisplayed messages. Solving them without help is part of the learning process! The devil is in the details: mosterrors are in syntax. To understand what is going wrong with the larger code and data matrices, it may help toplay with very small and simple matrices first.

4

Page 6: Matlab practicals manual

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

Page 7: Matlab practicals manual

- ”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 thenbrowse through the directories and create a new folder at the desired location using the ”New directory” button. Forinstance, create a first folder called Matlab_practicals. In this folder create a folder called Practical1 in whichyour 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.8000With this command, we defined a new variable a and assigned the value 32.8 to it.

• Now let’s type:

>> b = 3*a^2and then press ”enter”. We defined a new variable, b, equal to 3 times the value of a squared. Its value is displayedin the command window. The basic operations and their symbols are presented in Table 1.1.

6

Page 8: Matlab practicals manual

Figure 1.1: Organisation of the Matlab window

7

Page 9: Matlab practicals manual

Operation SymbolAddition +

Substraction −Multiplication ∗

Division /Exponentiation ˆ(e.g. 2ˆ3 = 8)

Table 1.1: Basic operations and associated symbols

• Type now:

>> whosand then press ”enter”. The following lines are displayed in the Matlab command window:

Name Size Bytes Class

a 1x1 8 double

b 1x1 8 doubleThis command displays the different variables which have been previously defined (a and b), and gives theirmain characteristics (see presentation of arrays, §1.3, for more explanations). These variables are now listed inthe ”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 commandwindow.

• Type now:

>> c=a*30/200and 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, appearsin the command window.

8

Page 10: Matlab practicals manual

Function Descriptionsin(), cos(), tan() sine, cosine and tangent (arguments in radians)

asin(), acos(), atan() inverse sine, cosine and tangentabs() absolute valuesqrt() root square (equivalent to ˆ(0.5))round() round towards nearest integer

ceil() (or floor()) round towards plus (or minus) infinitylog(), log10() natural logarithm, logarithm base 10

exp() 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 executedsuccessively 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 adda 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 secondvariable, c_bis, which is the absolute value of c. c is called input argument of the function abs. c_bis is theoutput argument.Numerous elementary mathematical functions are already implemented in Matlab. The table 1.2 presents aselection of the most commonly-used elementary functions. Type help elfun in the command window for anextensive list of these functions.

9

Page 11: Matlab practicals manual

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 usuallyinclude 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 displayedin the ”Command history” window.

- Variable names must start by a letter, and can be followed by character chain, including letters, numbers andany symbols except those used as mathematical operators by Matlab (+,-,*,...) or punctuation signs. Variablenames can contain up to 31 characters; When no variable name is specified, a temporary variable name, ans, isgenerated 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 filesallows you to organize and save series of commands. These scripts can be edited/extended/corrected anytime youwant, and executed several times. Writing the commands into a script is necessary when you perform advanced dataanalysis, since it allows you to check/improve your methodology, but also to be sure to perform the exact same dataprocessing for several datasets for instance.

The scripts are user-created text files which can be written using Matlab editor. Type:

>> edit

10

Page 12: Matlab practicals manual

The Matlab editor window opens. In this window, you can write series of commands and save them. The resultingscript 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 particularlyuseful when scripts are re-used long after they have been created. In a script file, anything written to the right of apercentage symbol is considered as a comment and will be ignored during the execution. In the Matlab editor, thecomments 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

Page 13: Matlab practicals manual

% Example of a very simple Matlab script

% M. Tissier, 8-8-2012

% Initialization

clear

displacement = 12; % displacement (m)

time = 10; % 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 ”Commandwindow” and then press ”enter”. When a script file is executed, Matlab execute the commands in the order they arewritten.

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 isC = 44 m0.5/s, the bankful discharge Qbf = 2500 m3/s, the channel width W = 500 m and the channel gradientS = 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

Page 14: Matlab practicals manual

1.3 Arrays

1.3.1 Definition

The array is the fundamental form that Matlab uses to store and manipulate data. This way of storing data allowsfor 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

Page 15: Matlab practicals manual

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 win-dow. When defining an array other than a scalar, brackets [ ] should be used. The elements belonging to a samerow 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 isdisplayed. It gives 2× 4, which means that M has 2 rows and 4 columns. This information can also be retrivedusing 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. Whatdo 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], whereinterval 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

Page 16: Matlab practicals manual

• 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 datasetsare related and should be treated together. This can be done thanks to the operation of concatenation (=joining thearrays 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 functionhorzcat(), 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

Page 17: Matlab practicals manual

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

(1,1) (1,2)

(2,1) (2,2)

(3,1) (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

Page 18: Matlab practicals manual

• For a vector, it is easier to define the position of an element using only one number, called its index, which isits position in the row or the column. For instance, vectM(2) is equivalent to vectM(1,2). Several elements ofvectM 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 fromthe top left element and progressing downward. For a matrix of dimension 3× 2 (note that the index of a givenelement will depend on the size of the matrix), we have:

(1) (4)

(2) (5)

(3) (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*Mand check the output. Remark: 2*M is equivalent to M*2.

17

Page 19: Matlab practicals manual

• Addition (subtraction) with a scalar:

Type

>> M-2The 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. Theresulting 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 definetwo matrices A and B such as:

A =

(1 0 25 10 7

)and B =

1 34 12 2

.

The element (i, j) of the matrix C = A ∗B is defined as :

C(i, j) =

n∑k=1

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

where n is the number of columns of A (=number if rows of B). C is therefore equal to:

C =

(1 ∗ 1 + 0 ∗ 4 + 2 ∗ 2 1 ∗ 3 + 0 ∗ 1 + 2 ∗ 25 ∗ 1 + 10 ∗ 4 + 7 ∗ 2 5 ∗ 3 + 10 ∗ 1 + 7 ∗ 2

)=

(5 759 39

)

18

Page 20: Matlab practicals manual

Operation betweentwo matrices

Matlab ex-pression

Condition

Addition A+B size of A = size of B

Multiplication A*Bnumber of columns of A = num-ber of rows of B

Element-by-element mul-tiplication

A.*B size of A = size of B

Element-by-element divi-sion

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 sizeare also indicated.

Element-by-element operations

• To perform a multiplication element-by-element, it is necessary to use the operator ”.*” instead of ”*”. Typefor instance

>> M.*fand examine the result. Type now the same command but without the dot. Do you understand the error mes-sage? (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 thiscase, the function is applied to each matrix element individually, and returns an array of the same size as the input

19

Page 21: Matlab practicals manual

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 transpositionfunction works?transpose() changes the rows of the matrix into columns, and vice versa. As a consequence, a matrix of size n×mwill turn into a matrix of size m × n containing the same elements organised in a different way. This operation canalso 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 toones() 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. Someexamples 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 averagedvalue of the vector , its median value and to the sum of its elements.

• Type:

>> vmax =max(vectM)

20

Page 22: Matlab practicals manual

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 whatis the position of the largest value in the original vector. In order to get this information, the function max (ormin) 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 similarway.

• 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 outputis 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 addi-tional 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 howto 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

Page 23: Matlab practicals manual

max Maximum valuemean Average or mean valuemedian Median valuemin Smallest valuestd Standard deviationvar Variance

prctilePercentile values (the percent of inter-est should be specified)

sum Sum of the elements

sortArrange the elements in ascending or-der

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 solvethe following assignment will be written.

1. Create the following matrix:

A =

16 3 2 135 10 11 89 6 7 124 15 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 where each element contains the sum of the elements of one of the row of A. Forinstance, sumRows(1) =

∑4k=1A(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

Page 24: Matlab practicals manual

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 hasbeen 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 thefirst 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 thesecond 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 andanalyse their effects on the figure:

title(’Example plot’);

xlabel(’Radians’);

ylabel(’Function Value’);

legend(’sine’,’cosine’);

23

Page 25: Matlab practicals manual

• 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 instancefigure(1). The number corresponds to the number of the corresponding figure window. If the Figure 1 doesnot exist yet, this command will create it. If this figure already exists, it becomes the active figure window. Thismeans 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) wherea, 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 linesshould 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” buttonpresented 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 yourplots. Some examples are given below:

24

Page 26: Matlab practicals manual

- 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 (typedoc plot for instance) for a more extensive description of the plotting options. You can also navigate in the helpwindow to learn more about the numerous ways to visualise data in Matlab.

Color specifiersred r blue b black k magenta m

green g cyan c yellow y white w

Marker specifiersplus sign + square s circle o

asterisk * triangles v, < or > cross x

EXERCISE 3 This exercise is based on the dataset contained in the file MPMtransportdata.xls. Meyer-Peterand Mueller (1948) (abbreviated MPM) graphically report gravel transport data and derive their famous empiricalbedload transport predictor from this dataset. Wong and Parker (2006) recovered the original data and re-analysedit to find that the original fit by MPM was wrong. Here you will plot the data in nondimensional form and calculatea 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

Page 27: Matlab practicals manual

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 intothe command window and then press ”enter”. Alternatively, you can select the part of the text you want to runand then press ”F9”.

• Always terminate the command by a semicolon if you do not want the result to be displayed in your commandwindow. 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 assignmentwill 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 thedata using the following line:

26

Page 28: Matlab practicals manual

dataMPM = xlsread(’MPMtransportdata.xls’);

Thanks to the function xlsread(), Excel sheets can be read and loaded in your workspace. The output of thefunction is an array called dataMPM which contains the same information as the Excel sheet, but without thedescription of the data (only numbers). Check its number of rows and columns and compare a few values withthe initial Excel sheet.

3. Define vectors containing the channel width W, the depth h, the slope S, the median grain size D50, the specificgravity 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 byloglog(). loglog is basically the same as the plot function, but with logarithmic axis, and can be used withthe same input arguments (see Matlab help for more details). Give an appropriate title to the plot, as well asnames 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 followingcharacters:

α \alpha τ \tau ε \epsilon φ \phi

β \beta Φ \Phi θ \theta λ \lambda

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

27

Page 29: Matlab practicals manual

8. Plot in a new figure the data in a nondimensional form, i.e. the Einstein parameter (y-axis) as a function of theShields parameter (x-axis). Give an appropriate title to the plot, as well as names to axis. Compare with theprevious 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 vectorsx and y such as x contains a range of values reachable by the Shields parameter (θ) and y = 8(x − θcr)1.5 (seeeq. (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 theircharacteristics. Check the Matlab help to understand how to use the function scatter() and what are its inputarguments. 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), withcolors 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 theothers. To which range of D∗ does it correspond?

28

Page 30: Matlab practicals manual

1.5 Final assignment : Analysis of the Rhine flow discharge measuredat Lobith – part I

In this exercise, we will perform some analysis on a dataset containing the flow discharge of the Rhine measured atLobith (where the Rhine enters the Netherlands) for the period 1901-2000 AD. The dataset is given in the text-fileQlobith19012000.txt as an array. Each element of this array is the discharge in m3/s for 1 day, and each columncorresponds 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 thescript 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 (andtherefore each year of data) separately. As a result, each line appearing in the figure corresponds to the evolutionof 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 orredefine the x-axis limits using xlim()). How are the NaN-values handled by the function plot?

29

Page 31: Matlab practicals manual

6. Create a vector called year containing the years when the data were collected, as well as a vector days containingthe 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 ofthe 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 * NaNThis 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 differentiatethe 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

Page 32: Matlab practicals manual

15. Compute the median value of the annual flood data as well as the 75th, 90th, 95th percentiles (see http://en.wikipedia.org/wiki/Percentilefor definition).

16. We will now use the annual flood discharge data to build a flood-frequency curve, which is a graph showing therelationship between flood magnitude and their recurrence interval for a specified site.

The recurrence interval (Tr) of a flood is a statistical measure of how often a flood of a given magnitude (QTr)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 QTr containing the annual flood discharges sorted in ascending order.

- Define a vector R of same length as QTr containing the ”ranks” of the discharges. The largest discharge ofQTr should have a rank equal to 1, and the smallest a rank equal to N, where N is the number of years forwhich we have flood data.

- The recurrence interval Tr (in years) can then be computed using the formula:

Tr = (N + 1)/R.

You can now plot QTr versus Tr : this is the flood-frequency curve. Use logarithmic axis for a better display ofthe 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.2to 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 givenevent. Histograms can be built using the function hist, the distribution of the data can be compared with differentprobability distribution with the help of probplot, etc.

31

Page 33: Matlab practicals manual

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

32

Page 34: Matlab practicals manual

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 acomparison statement (e.g., a < b) is true or false.

• If the comparison statement is false, it returns a zero. Type for instance:

>> 3<2If the statement is true, such as

>> 3<6it returns 1.

• Such comparisons are generally performed on arrays and can be very useful to analyse datasets. Define an arrayA such as:>> A = [1:2:10;10:-2:1]

33

Page 35: Matlab practicals manual

and then type

>> E = (A<5)This command returns an array E which has the same size as A, but contains only ones and zeros. Each elementof A is compared to 5, and, depending on the outcome of each comparison, the elements of E are filled with 1 or0.

• Use the function sum to determine how many elements of A are smaller than 5.This method can be very useful to characterize large datasets where it is not possible to count one-by-one theelements satisfying a certain condition.

• Relational operators can also be used to compare two arrays. Type:

>> B = [3 7 1 8 3; 1 45 0 2 9]

>> F = (A<B)

and analyse the result. The comparison between A and B is done element-by-element. The results are stored ina third array, F, which has the same size as A and B. Each element of F is equal to 1 if the comparison is true atthis location, and equal to 0 otherwise.

• These operations can be performed using any operator described in Table 2.1. Type for instance:

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

Page 36: Matlab practicals manual

Description SymbolLess than <More than >

Less than or equal to <=More than or equal to >=

Equal to ==Not equal to ∼=

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

>> b = B(A<5)

Logical operators Comparison statements can be combined using the logical operators AND and OR (see Table2.2).

• Type for instance:

>> H=(B>2)&(B<10)H contains ones only if the elements of B are larger than 2 and smaller than 10. The two comparison statementsshould be true at the same time to return a 1.

• When the operator OR is used, the output is true if either one, or both, comparison statements are true. Replacethe & in the previous command by the OR symbol |. Did you expect the output?

• A third logical operator, NOT, can be used. Applied to a logical array, it returns its opposite. Type for instance:∼ H, and compare with H.

35

Page 37: Matlab practicals manual

Description SymbolOR |

AND &NOT ∼

Table 2.2: Logical operators

Use of the function find The function find looks for the non-zeros elements of an array, and returns their indices.If no elements are found, it returns an empty matrix.

• Type the following commands:

>> 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 theelements 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<5)We obtain the indices of the elements of A smaller than 5 (see definitions of indices for matrices page 16). Com-pute now A(ind2) and compare it with A(E). Do you understand the result?

EXERCISE 1 Open a new script file where the following assignments will be solved. The matrix A should be definedat the beginning of the script.

1. Compute the average value of the elements of A larger than 2 and smaller than 6.

2. Replace the elements of A smaller than 3 by 0.

36

Page 38: Matlab practicals manual

3. Replace the elements of A larger or equal to 9 by 2 times their value.

2.2 Flow control

In a simple program, the commands are executed one after the other, independently from the output of the previousone. However, it is sometimes necessary to include some sort of decision making in the program. For instance, we candecide to compute the sediment transport using different predictors depending on the sediment characteristics andflow conditions. The program should therefore be able to choose the appropriate calculation and skip the others. Itcan also be needed to repeat a sequence of commands several times, until a certain condition is reached for instance.

The order in which the commands or group of commands are executed, also called the flow of the program, can becontrolled in several ways in Matlab. In this section, the three basic flow control methods will be presented.

2.2.1 if-statements

Purpose if-statements are used when a decision must be taken depending on the outcome of a comparison state-ment (also called conditional expression). If the comparison is true, then the group of commands are executed, and ifit is not, it is skipped.

Format The most simple if-statement is the if-end construction, as in the following example:x=2;

if x<5

disp(’x is less than 5’)

end

• Execute this small program and interpret the result.

• Replace x=2 by x=5 and re-run the program.

37

Page 39: Matlab practicals manual

When the program has to choose between two alternatives, a if-else-end-constructions can be used. Read carefullythe piece of code presented below (please note that in this example Theta is a scalar):

if Theta<Theta_cr

%no sediment transport

Phi = 0;

else

%sediment transport computation

Phi = 8*(Theta - Theta_cr)^1.5;

endBased on the outcome of the comparison statement Theta<Theta_cr, either the commands between the if and else

or the commands between else and end are executed. This small program is therefore simply expressing the factthat if the Shields parameter Theta is below a critical value, there is no sediment transport, and that otherwise thesediment transport is calculated using the MPM predictor.

The general structure of the if-statement is presented below:

38

Page 40: Matlab practicals manual

if expression1

group of commands evaluatedif expression1 is true

elseif expression2

group of commands evaluatedif expression2 is true

elseif expression3

group of commands evaluatedif expression3 is true. . .

else

group of commands evaluated if noneof the previous expressions is true

end

Only the commands associated with the first true expression are evaluated, the others are skipped. The conditionalexpressions can be defined using the operators presented in §2.1.

2.2.2 for-loops

Purpose for-loops are used to repeat a command or a group of commands for a fixed (predetermined) number oftimes.

Format The general structure of a for-loop is presented below:

for index = start:increment:end

commands to be executed in the for-loopend

39

Page 41: Matlab practicals manual

Examples

• Let’s start with a simple example to understand how these loops are working. Run the following lines andinterpret the results:for j=1:8

disp(’Hello’);

endIf necessary, check the Matlab help to learn more about the disp function.

• Loops can be for instance used to define arrays. Run now the following script and examine carefully its results:clear

for j=1:9

s(j) = j^2;

end

sThe loop is executed for each element of j, which starts at one and increases by 1 until it reaches 9. At eachstep, the square j is computed and stored in jth element of the s. In other words, this small script computesthe squares of the numbers from 1 to 9.

• Note that this for-loop could be replaced by the following lines:clear

j=[1:9];

s=j.^2

These two ways of solving the problem are equivalent. However, to reduce the computational time it is recom-mended to avoid loops when it is possible.

• Loops can also be nested, as in the following example, where we define a new matrix B and fill it in element-by-element:

40

Page 42: Matlab practicals manual

clear

B=zeros(2,3);

for i=1:2

for j=1:3

B(i,j) = i*j

end

endIn this case, every time i increases by one, the nested loop is executed 4 times (from j = 1 to j = 4). Run thisscript to check in which order the matrix is filled in. Do you understand why?

Remark In the previous example, we first defined B as a 2 × 3 matrix of zeros, and then filled it in withinthe loop. This initialising step is not compulsory in Matlab (comment the second line and re-run the script),but it makes your program more efficient. Indeed, it is a way to pre-allocate memory: Matlab ”knows” fromthe beginning the size of the matrix you are building up, and does not need to re-size it at each iteration. Theprogram runs faster (important when working with large arrays!).

• for-loops can be combined with if-statements, as in the following exampleclear

s = [2 1 -4 23 0];

for i=1:5

if s(i)>=2

s(i) = 3*s(i);

end

end

sRun this script and interpret the output.In this case, the combined use of the for-loop and if-statement could have been replaced by the use of relational

41

Page 43: Matlab practicals manual

operators. Do you understand how?

Some remarks about for-loops

- The first time through the loop, the variable is assigned the first value in the vector [start:increment:end].For the second time through, MATLAB automatically assigns to the variable the second value in the vector, etc.

- The number of times a loop is executed equals the number of values in the vector.

- After the loop is finished executing, the loop variable still exists in memory and its value is the last value usedinside the loop.

EXERCISE 2 This exercise deals with the computation of the evolution of Carbon 14 in a sample due to radioactivedecay. Each thousand of years a fraction α of C14 is lost. This means that, calling C0 the initial mass of C14, themass remaining in the sample will be:

- C1 = C0(1− α) in 1 thousand years,

- C2 = C1(1− α) in 2 thousand years,

- C3 = C2(1− α) in 3 thousand years, etc.

We want to calculate the quantity of C14 still in the sample after 25000 years. Write a script which creates a vectorC such as its first element C(1) is the initial amount of U238, C(2) the amount after 1 thousand years, etc. The lastelement of the vector should contain the amount of C14 after 25 thousand years. You can use the following scriptlines as a basis and complete them. Data: C0 = 0.5 kg; α = 0.117;

42

Page 44: Matlab practicals manual

% Initialization

???

???

% Calculation of the radioactive decay

for i=2:26

??? % Computation of the i^th element of the vector C

end

% Definition of a time vector in thousand years

t = (0:25);

% Visualisation

figure; plot(t,C/C(1));

ylabel(’C(t)/C(0)’); xlabel(’t (10^3 years)’);

EXERCISE 3 Let’s come back to exercise 3 of the last chapter (page 25) concerning the analysis of the datasetfrom Meyer-Peter and Mueller. We observed that part of the data was following a different trend than the others afternon-dimensionalisation. A close look at it shows that these data points correspond to experiments performed usinga very fine sediment (D50 = 0.3402 mm). In this case, bedforms probably developed, and the use of a grain-relatedshear stress instead of the total shear stress is more appropriate and might improve the prediction.

1. Copy the data file MPMtransportdata.xls in your current work directory and open a new script file.

2. Create a new vector tau2 containing the total shear stress for data such as D50 ≥ 1 mm and the grain-relatedshear stress otherwise (D50 < 1 mm). You can use parts of the script written during the first tutorial.Remarks:

- this question can be solved using if-statements and loops or relational/logical operators only. Choose the

43

Page 45: Matlab practicals manual

most convenient way for you!

- in Matlab, the function calculating the base-10 logarithm is log10(). log() is the natural logarithm.

3. Calculate the associated Shields parameters.

4. Plot the data (using the function scatter) as the Einstein parameter as a function of the newly computedShields parameter. Compare with the figure created during the previous tutorial.

5. Additional question for those who found the exercise easy. Now also remove wall friction and explain how you didit. See the Van Rijn fluid mechanics book or the paper by Wong and Parker 2006, J. of Hydraulic Engineering,doi 10.1061/(ASCE)0733-9429(2006)132:11(1159).

2.2.3 while-loops

Purpose while-loops are used to repeat a command, or a group of commands, an indefinite number of times untilthe condition specified by while is no longer satisfied.

Format The general structure for a while-loop is the following:

while expression

group of commands repeated as long asexpression is true

end

When the program reaches the first line of the block, the conditional expression is checked. If it is true, Matlabexecutes the group of commands. Then Matlab jumps back to the while command and check again the expression: ifit is still true, the commands are executed again. The looping process will stop when the expression becomes false.

44

Page 46: Matlab practicals manual

Examples

• Execute the following script and interpret the output:clear

x=1;

while x<14

x=x+4

endHow many times are the commands executed and why?

• Execute now:x=1;

while x<14

x=x-4

endDo you understand what is happening?

Remark: To terminate a computation, press Ctrl+C. This command can be very useful in case of programmingerrors leading to never-ending loops.

Some remarks on the use of while-loops

- The variables used in expression must be defined BEFORE the ’while’ loop, so you can use it to enter the loop

- At least one variable used in expression must change INSIDE the while loop, or you will never exit the loop.

- After the loop is finished executing, the loop variable(s) still exist in memory and its value is the last value thevariable had in the while loop.

45

Page 47: Matlab practicals manual

EXERCISE 4 In this exercise, we aim at characterizing the flow in typical experimental conditions. The channelis 0.3 m wide and has a slope of 0.006 m/m. The Nikuradse roughness length is 0.0013 m. We try to answer to thefollowing questions : how deep will the water be when the water flow is 1 × 10−3 m3/s? what will then be the flowvelocity?

This problem will be solved using an iteration process. We start with a first guess of the water depth, and correctit at each loop to make it more accurate. The looping process will stop when the desired accuracy has been reached.

• Create a new script where this problem will be solved. Some help concerning the structure of the program canbe found below:

Initialisation- Make a first inaccurate guess to define h (should be such as

0 < h < hmax, with hmax = 3 cm)- Define also htemp to allow for the first loop to start, e.g.

htemp = 0.9 ∗ h.

As long as the absolute value of (h−htemp) is larger than 1×10−6

- New guess for h : the ”real” depth should be contained betweenh and htemp. We try the value (h+htemp)/2 (other options are possible!).

- Computation of u- Computation of htemp

End of the loop

A good estimation of h has been found. Calculate the associate flowvelocity.

Some additional comments Each iteration starts with defining a new, presumably more accurate, value of theflow depth h. We then compute the flow velocity u associated to h using the Chezy equation. This flow velocityis then used to compute a second estimation of the water depth called htemp, based on the mass conservation

46

Page 48: Matlab practicals manual

equation. h and htemp are then compared. They should be nearly equal if our last estimation of h was goodenough.

• To check your code, run the script with different guesses for the initial water depth. If the while loop is correctlycoded, it should always return the same final value for the depth h.

2.3 User-defined functions

You have already encountered functions that are built in to MATLAB (see Tables 1.2 and 1.4 for instance). As youstart to write your own programs in MATLAB you will need to create your own functions that take one or more inputarguments, operate on them, and return the result (output).

Function files are simply text files with a *.m extension, and can be written, as script files, using Matlab editor.They are organized in the following way:

- The first line of a function m-file must always be of the following form:

function [ output variables ] = function name( input variables )

This line always starts with the word function. Following that, the output variables are enclosed in squarebrackets [ ]. Then, the characters function_name define the name which will be used to call the function. Theinput variables are finally specified into brackets.

NB: The function function_name should be saved in a file called function_name.m.

- The definition line of a function file must be followed by a block of comments, containing at least the followingfields: a short description of the function aim as well as definitions of the input and output variables (see examplebelow).

- The body of the function can then start. It is made of a succession of commands which ultimately defines theoutput variables.

47

Page 49: Matlab practicals manual

• Let’s start with an example of a simple function. Copy the following lines in a new m-file and save it in yourcurrent directory as cylinder_charact.m:

function [S,V] = cylinder_charact(R,h)

% [S,V] = cylinder_charact(R,h);

% Computation of the volume and surface area of a cylinder

% input R radius (m)

% h cylinder height (m)

% output

% S surface area (m2)

% V volume (m3)

a_lateral = 2*pi*R*h;

a_circles = 2*pi*R^2;

S = a_lateral + a_circles;

V = pi*R^2*h;

In this example, a function called cylinder_charact has been defined. The definition line is followed by a blockof comment lines, which are meant to provide information about the function and its arguments. These linesare important since they allow the function file to be referenced by the Matlab help.

• Type now in the command window>> help cylinder_charact

The block of comments following the definition line is displayed.

• Clear your workspace and type the following commands:

>> [S1,V1] = cylinder_charact(2,3);

The function cylinder_charact() is called with the input arguments 2 and 3. It returns the surface area andvolume of a cylinder of radius 2 m and height 3 m. These values are assigned to the variables S1 and V1.

• Type whos in the command window. The intermediate variables (=variables not defined as outputs), such as

48

Page 50: Matlab practicals manual

a_lateral, a_circles only exist within a function and do not appear in the workspace. The use of functionsis therefore important since it avoids to overload the workspace with variables which are not going to be usedlater.

• These functions can be used in a script file, as any built in function in Matlab. Modify the function file so as itallows for non-scalar input arguments. You should then be able to run the following script:

% Computation of the volume and surface area

% of cylinders of increasing radius

% M. Tissier, 3-09-12

% Initialisation

clear

h=3; % constant height of the cylinders (m)

r=(1:6); % increasing radius of the cylinders (m)

% Computation of the volumes S_tot and areas V_tot

% of the cylinders

[S_tot,V_tot] = cylinder_charact(r,h);

figure; plot(r,S_tot,’o-’);

xlabel(’radius (m)’);ylabel(’surface area (m^2)’)

Some (additional) reasons to use functions in your scripts

- Script files in which all the calculations are entered in one unique file can become too long and difficult tounderstand. By using functions files, you can organize better your program, and make it easier to read andunderstand.

- A function can be called several times within a script with different input arguments: you do not need to writesimilar calculations over and over again...

49

Page 51: Matlab practicals manual

EXERCISE 5 We now continue from exercise 3 of Chapter 1. Here, the objective is to compare the measuredsediment transport to the predictions given by the MPM and EH formulations, using several user-defined functions.

1. Create a function calculating the (total) Shields parameter. The input parameters should be the channel slope,the densities of the water and the density of the sediment, the water depth and the median grain diameter.

2. Create two functions which calculate the non-dimensional sediment transport according to MPM and Engelundand Hansen (EH) relations. The input arguments for MPM should be the Shields parameter and its criticalvalue. Choose the adequate arguments for EH.HINT: For the MPM predictor, do not forget to account for the fact that sediment is only transported if theShields parameter is higher than a critical value (θcr = 0.047).

3. Create a function converting the non-dimensional transport into the dimensional one (in m2/s).

4. Write a script which will call the functions defined above and ultimately plot the measured sediment transportagainst the predicted one for both MPM and EH equations. Add a line corresponding to x = y on the figure.Label the x- and y-axis and add a legend.

2.4 Final assignment : Analysis of the Rhine flow discharge measuredat Lobith – part II

Morphologically relevant statistics of the discharge dataset

1. Calculate the maximal and minimal daily discharge for the whole dataset.

2. Calculate the percentage of days of year 1916 where Q exceeds the mean annual flood discharge calculated inSection 1.5.

50

Page 52: Matlab practicals manual

3. Create a function which takes as an input argument a vector and returns its number of non-NaN elements (HINT:check Matlab help for isnan and length).

4. Compute the same percentage for each year of data and store the results in a vector. Remark: For some years,there is one day less than for others. Use the function defined in question 3 to take it into account whilecalculating the percentages.

5. Plot the percentage of days where Q exceeds the threshold value as a function of the year (give a title and namesto the axis).

6. Compute finally the same percentage but for the whole data set (over the 100 years of data).

Computation of the discharge in the channel during floods

7. We consider here that the bankfull discharge, Qbankfull, can be approximated by two times the mean value ofQ over the entire dataset. Calculate Qbankfull.

8. Calculate the number of days where the bankfull discharge has been exceeded over the 100 years of data.

When the total discharge Q gets larger than the bankfull discharge Qbf , the river floods. In this case, the dischargereally flowing in the channel and contributing to the channel bed shear stress is less than the total discharge Q:Qchannel = Qbankfull + Qoverbchannel (see Figure 2.1 for definitions). The following question aims at calculatingQchannel, which is the relevant discharge for sediment transport calculations.

9. Define a matrix Qchannel of the same size as Q. The elements of this matrix should be equal to those of Q ifQ < Qbf , and equal to Qbankfull +Qoverbchannel otherwise.To check your calculations, compare Qchannel and Q. Does it match your expectations?

HINT: Qoverbchannel can be expressed as a function Qoverbank, W and Wfp. To find this relation, relate thecross-sectional area Aoverbchannel to Aoverbank. As the depth-averaged flow velocity is considered to be constant

51

Page 53: Matlab practicals manual

Figure 2.1: Skematic view of the profile of the Rhine at Lobith during a flood event. Wfp is the total width of theflood plain, W the channel width defined earlier. The total discharge Q in the river is equal to Qbankfull +Qoverbank.The part of the overbank discharge flowing over the channel is called Qoverbchannel.

52

Page 54: Matlab practicals manual

over the cross-section, you can then obtain a relation between the discharges Qoverbchannel and Qoverbank.Data: W = 550 m; Wfp = 3000 m;

Sediment transport calculations

Additional data: Channel slope S = 1.5 × 10−4 m/m; Median diameter of the sediment D50 = 2 × 10−3 m; Densityof the sediment ρs = 2650 kg/m3; Water density ρw = 1000 kg/m3;

10. Calculate the water level from the discharge using the QH (stage discharge) relation given below:

H = (384.73 ln(Q)− 1949.3)/100.

H is the elevation in meters above mean sea level and Q the total discharge.

11. Calculate the water depth h knowing that the average bed elevation is 3 meters above sea level.

12. Apply the Engelund Hansen (1967) relation to compute the sediment transport rate associated to the channeldischarge Qchannel. Use the functions defined earlier to calculate the sediment transport.

13. Calculate the sediment discharge Qs in m3/s. Plot Qs as a function of Qchannel for the whole dataset. Choosethe best representation (logarithmic axis or not).

14. Calculate the average volume (m3) transported through Lobith per year. To do that, you should first computethe total volume of sediment transported through Lobith for each year of the dataset, and then average thesevalues.

15. Determine what value of flow discharge transports this same average sediment volume. This is a representativedischarge for the morphodynamics and could be used in a numerical model for long-term morphological predic-tion instead of the full hydrograph, which is computationally more expensive.

16. Compare this representative discharge to the mean flow discharge at Lobith (calculated over the entire periodcovered with the dataset).

53

Page 55: Matlab practicals manual

PRODUCTS TO HAND IN Exercises 1 to 5 and final assignment.

54

Page 56: Matlab practicals manual

Chapter 3

Numerical modelling

The answers to the questions of this practical should be organised in a short word document, in which you shouldinclude the relevant Matlab figures.Remark: To save a figure, use the Matlab function print or click on ”File” and then ”Save as” in the figure window(see Figure 1.2).

3.1 A very simple morphodynamic model

We consider in this section a one-dimensional river with an initial constant slope S0 = 1/10. We want to computethe evolution of the river bed in space and time using very basic physical laws. Similar approaches are used incellular automats of rivers and in so-called reduced-complexity models (try a search in Google Scholar to see debatesand controversies). In this model, we do not consider the influence of the water motion on sediment transport: thesediment transport rate qt is assumed to depend linearly on the local bed slope S. More precisely, we assume thatqt = SedProp S, with SedProp a proportionality coefficient.

55

Page 57: Matlab practicals manual

To solve this problem numerically, it needs to be discretized in space and in time. The reach of the river underconsideration, of length L, is divided into Nx sub-reaches of length dx = L/Nx. These sub-reaches are separated byNx + 1 nodes, of coordinates xi = (i− 1)dx, with i integer varying between 1 and Nx + 1. To each of these nodes areassociated a bed elevation and a sediment transport rate called ηi and qti (i is the node number). The bed elevationηni at time tn is then used to compute the bed elevation ηn+1

i at time tn+1 = tn + dt (concept of time discretization).This should be done in two main steps (see also Fig. 3.1):

- the sediment transport rate qt is first computed as a function of the local slope at each node (proportionalitycoefficient given in the Matlab script). HINT : the local slope, defined as minus the gradient of the bed elevation(S = − ∂η∂x ), can be computed using the built in function gradient (see Matlab help).

- to compute the bed evolution, the sediment conservation equation (also called Exner equation) is then used. Itcan be written as:

∂η

∂t= −∂qt

∂x,

that is to say, in a discretized form:ηn+1i − ηnidt

=

(∂qt∂x

)ni

,

and therefore

ηn+1i = ηni −

(∂qt∂x

)ni

dt.

The gradient of sediment transport should be calculated and then used to update the bed elevation.

• Download the script file very_simplified_model.m. It contains the structure of the model, and some commandsto visualise the results.

• Add in the initialisation part of the script the definition of the bed elevation vector eta at t=0. The initial bedelevation decreases linearly with a slope S0. The bed elevation at x = L (downstream boundary) should be zero.Data: L = 10 m and S0 = 1/10.

56

Page 58: Matlab practicals manual

Figure 3.1: Organization of our very simple morphodynamic model (no computation of the flow)

• Complete the time-loop using the explanations given above.

• Run the model and analyse the results.

• Let’s now modify the upstream boundary condition. We set the sediment transport rate qt to zero at theupstream boundary (node 1, x = 0). This means that there is no incoming sediment flux in our model. Run thecode and interpret the results.

• Create a vector which will contain the time-evolution of the bed elevation at the first node. This vector shouldbe filled element-by-element during the time loop. Plot this vector as a function of time. What kind of evolutiondo you obtain?

57

Page 59: Matlab practicals manual

3.2 Flow computation: backwater equations

To model the river in a more realistic way, it is necessary to compute the flow in the channel at each iteration, andthen use it to compute the sediment transport and the bed evolution (see Fig. 3.3). In this section, we present thebackwater equations, which will be used in Section 3.3 to compute the flow in a more complex morphodynamic model.

More precisely, the flow in the channel will be computed using the backwater formulation for steady, graduallyvaried flow under the constraint of constant water discharge per unit width qw and an imposed water elevation ξd atthe downstream boundary. Let H denote depth, ξ the water surface elevation, η the bed elevation (ξ = H + η, seealso Fig. 3.2), kc the composite roughness height and S the bed slope.

The backwater equation writes:dH

dx=S − CfFr2

1− Fr2(3.1)

where S is the local bed slope and Fr the Froude number defined as Fr2 = U2

gH with U = qwH . The bed friction

coefficient Cf is assumed to follow a Manning-Strickler resistance relation:

Cf−1/2 = αr

(H

kc

)1/6

(3.2)

with αr = 8.1.

How to solve this equation The backwater equation is first re-written in the discrete form (Hi being the waterdepth at the ith node):

Hi+1 −Hi

dx= Fback(H), (3.3)

with Fback a function defined as

Fback(H) =S − CfFr2

1− Fr2

58

Page 60: Matlab practicals manual

that is to say, using the definitions of Cf and Fr,

Fback(H) =

ηi+1−ηidx − 1

αr2

(Hkc

)−1/3q2wgH3

1− q2wgH3

. (3.4)

Rearranging equation (3.3), we get:Hi = Hi+1 − Fback(H)dx. (3.5)

In practice, the resolution is performed in two steps in the code using a predictor-corrector scheme:

- a first estimation of the water depth Hpred i is computed:

Hpred i = Hi+1 − Fback(Hi+1) dx

- Hpred i is then used to obtain a more precise prediction of the water depth (corrector step):

Hi = Hi+1 −1

2(Fback(Hpred i) + Fback(Hi+1)) .

The water depth Hi at the node i can be therefore computed using the water depth Hi+1 one node downstream.The equations are solved starting from the downstream boundary (node Nx + 1), where the water depth H(Nx + 1)is known:

H(Nx + 1) = ξ(Nx + 1)− η(Nx + 1) (3.6)

= ξd − η(Nx + 1), (3.7)

with ξd the water surface elevation imposed by the user.

• Download the Matlab program called backwater_equation.m as well as the function F_back.

59

Page 61: Matlab practicals manual

• Identify the different steps in the computation of the water depth. Why is the loop starting at Nx + 1 and notat 1 as usual?

• Run the script and analyse the output.

• The normal water depth Hn and critical depth Hc are computed at the beginning of the script (for explanationsabout these depths, look at the part relative to the backwater equations in the powerpoint presentation Chapter5 of Gary Parker’s e-book). Add on the figure two lines corresponding to H = Hc and H = Hn. Modify thelegend.

• Run the code for different values of ξd. Different behaviours can be observed depending on the value of Hd =ξd+η(Nx+1). Make a representative figure for each type of observed behaviour (to add to your word document)and comment on your findings. Discuss in particular what is happening for values less than the critical depth.

• Calculate now a second vector H2, which contains the values of water depth obtained without using a correctorstep. Plot the results with and without using a corrector on the figure and compare them. This comparisonshould be performed for a fine spatial grid (the one given initially for instance) and a very large one. Do youunderstand why predictor-corrector schemes are used?

3.3 Morphodynamic model with flow computation

The model studied in this section is based on the same formulation as the spreadsheet RTe-bookAdDegBW.xls fromGary Parker e-book. It allows to compute the variations of the bed level η in space and time for different upstreamand downstream conditions (variables in red in Fig. 3.2). This resolution is performed in 3 steps, summarized in Fig.3.3:

- the first part computes the water depth and flow velocity, based on the backwater equations presented in Section3.2,

- the sediment transport is then computed using the flow characteristics determined in the previous step,

60

Page 62: Matlab practicals manual

- finally, Exner equations are used to calculate the bed elevation from the sediment transport fluxes.

• The folder full model contains the different m-files needed for this assignment.

• A detailed description of the model is given in chapter 20 of the e-book (a word file, not the ppt).Download thisdocument and use it to identify the different parts of the script model.m. Look through the different functionscalled in this script and try to understand what is going on.

• Run the script. Why doesn’t the bed change?

• Implement the sediment transport block in the model. Change the definition of qt and remove the commandqt_u=0;, which sets the sediment transport at the upstream boundary to zero. Calculate the shear stress fromthe flow velocity and friction; not from the depth slope product.

• Run the script again, analyse the output. Where is sediment deposited and why?

• What is happening when you raise the sea water level while keeping the sediment input constant? Why?

• What is happening if you decrease the sediment input? Why?

• In the Rhine, both happened at the same time. What happens then?

• Play with the model!

61

Page 63: Matlab practicals manual

REMARK Your model might produce incorrect results for some values of grid size and time step. More precisely, ifthe hump on the bed migrates more than one grid step dx during one time step dt, the model becomes unstable. Thisgives the following stability condition (also known as the Courant-Friedrichs-Lewy (CFL) condition):

cdt

dx≤ 1,

where c is the characteristic celerity of a disturbance in bed level. In practice, it means that if you increase significantlydt (to decrease your computation time for instance) you may have to increase dx to keep the model stable. However,keep in mind that increasing dx decreases the spacial resolution of your model.

62

Page 64: Matlab practicals manual

Figure 3.2: Initial condition and variable definitions

63

Page 65: Matlab practicals manual

Figure 3.3: Organization of the morphodynamic model introduced in Section 3.3

64

Page 66: Matlab practicals manual

Chapter 4

Creative Matlab exercise

The last (creative) exercise gives you some freedom of subject and method and allows you to distinguish yourself (earnhigher grades). Furthermore, you can perhaps use the resulting code in the delta project later in this course. The ideais that you conceive your own researchable (quantitative) question, do the research using matlab, and present it in apowerpoint to the group.

Steps of the empirical research cycle, that you will go through and that you will include in the five minute powerpointpresentation, are:

1. a researchable question

2. hypothesis (based on literature, provide references)

3. method

4. results

65

Page 67: Matlab practicals manual

5. discussion (in view of hypothesis)

6. conclusions

7. new research questions (at least one).

Before you start on the research propose your research question to the supervisors early Monday afternoon (22September), or send your research question by email to [email protected] on Monday evening 22 September thelatest. Example research questions have been mentioned during class.

The creative exercise will be presented using powerpoint in max 5 minutes per person (see schedule in study guidefor date, time and location). Bring your powerpoint file on a USB stick.

You may do the exercise on your own or in student pairs. If you work in pairs there should be two (related) researchquestions and investigations, and two powerpoints of 5 minutes each because each should present his/her own work.Indicate in the code (as comments) the contribution of each partner.

The individual creative exercise is worth 20% and the other three exercises are worth 5% each of the final grade.Grades will be individual and will be based on the quality of all steps in the empirical cycle plus the presentationquality plus, very importantly, creativity! Grades for having all steps done well and the presentation itself can betroll (2), not yet good enough (4), just good enough (6), excellent (8) and outstanding (10) and the final grade is thenumeric average of these, where steps are whimsically weighed by staff. The Matlab code is graded on the same scaleseparately on three criteria: does it work, does it do what it is supposed to do, and can we, experienced yet mortaland impatient lecturers, understand it. Have fun!

66