0% found this document useful (0 votes)
58 views

Port and Harbour Engineering Tutorial: 20 February 2019

This document provides an introduction and overview of MATLAB for port and harbour engineering. It discusses basic MATLAB operations with matrices and arrays, plots, programming, and functions. It also covers data analysis tutorials on spectral analysis and significant wave height. Key MATLAB topics include scalar arithmetic, matrices, arrays, indexing, relational operators, commonly used mathematical functions, plot elements, performing operations interactively and in script files, and the basics of programming in MATLAB with algorithms, sequential operations, conditional operations, and iterative operations.

Uploaded by

Zuhair Nadeem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

Port and Harbour Engineering Tutorial: 20 February 2019

This document provides an introduction and overview of MATLAB for port and harbour engineering. It discusses basic MATLAB operations with matrices and arrays, plots, programming, and functions. It also covers data analysis tutorials on spectral analysis and significant wave height. Key MATLAB topics include scalar arithmetic, matrices, arrays, indexing, relational operators, commonly used mathematical functions, plot elements, performing operations interactively and in script files, and the basics of programming in MATLAB with algorithms, sequential operations, conditional operations, and iterative operations.

Uploaded by

Zuhair Nadeem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Port and Harbour Engineering tutorial

20 February 2019

Part 1
-
MATLAB Introduction

PhD student Alberto Meucci


[email protected]
Contents
https://www.mathworks.com/examples/matlab

1. Matlab introduction
a. Basic operations with matrices and arrays
b. Plots
c. Programming
d. Functions
2. Data analysis tutorial
a. Spectral analysis
b. Significant Wave Height (Hs)
Default MATLAB desktop
Entering Commands and Expressions

● MATLAB retains your previous keystrokes.


● Use the up-arrow key to scroll back through the
commands.
● Press the key once to see the previous entry, and
so on.
● Use the down-arrow key to scroll forward. Edit a
line using the left- and right-arrow keys the
Backspace key, and the Delete key.
● Press the Enter key to execute the command
>> 8/10

Example session ans =


0.8000
>> 5*ans
ans =
4
>> r=8/10
r =
0.8000
>> r
r =
0.8000
>> s=20*r
s =
16
Scalar arithmetic operations

Symbol Operation MATLAB form


The assignment operator
Typing x = 3 assigns the value 3 to the variable x.

We can then type x = x + 2. This assigns the value 3 + 2 = 5 to x. But in


algebra this implies that 0 = 2.

In algebra we can write x + 2 = 20, but in MATLAB we cannot.

In MATLAB the left side of the = operator must be a single variable.

The right side must be a computable value.


Commands to manage the work session...

clc Clears the Command window.

clear Removes all variables from memory.

clear v1 v2 Removes the variables v1 and v2 from memory

exist(‘var’) Determines if a file or variable exists having the name


‘var’
quit Stops MATLAB.
...
who Lists the variables currently in memory

whos Lists the current variables and sizes, and indicates if they have

imaginary parts

: Colon: generates an array having regularly spaced elements.

, Comma: separates elements of an array.

; Semicolon: suppresses screen printing; also denotes a new row in

an array

... Ellipsis; continues a line


Special variables and constants

ans Temporary variable containing the most recent answer


eps Specifies the accuracy of floating point precision

i,j The imaginary unit √-1

Inf Infinity

NaN Indicates an undefined numerical result

pi The number π = 3.14159265...


MATLAB : MATrix LABoratory
Matrices
a matrix is a two-dimensional array of real or complex numbers

2x2 Matrix 4x2 Matrix

3x3 Matrix

2x4 Matrix
Matrices (continued...)
E(i,j) means a single number – the element on intersection
of the i-th row and the j-th column
Not to be confused with i and j used here as counters of rows
and column with i and j used in mathematics to denote the
imaginary unit

D(1,2) = 2

D(2,1) = 3

D(2,2) = 4

D(3,3) – doesn’t exist


Creating Matrices
If the matrix is small you can type it row by row, separating the
elements in a given row with spaces or commas and separating the
rows with semicolons. For example, typing:

>>A = [2,4,10;16,3,7];

creates the following matrix:

A =

2 4 10

16 3 7

Remember, spaces or commas separate elements in different


columns, whereas semicolons separate elements in different rows.
Arrays
mathematical operations with matrices are studied in Linear (or
Vector) Algebra

In Matlab, they use both matrices and what they call arrays

- the concept of the array is the same as in Linear Algebra

- mathematical operations are different

- we will mostly use the arrays


Basic operations with arrays in MATLAB
Addition of arrays:

Subtraction of arrays: Array division:

Array multiplication: D.’ is the array transpose of D


Basic operations with arrays in MATLAB
Arrays must have the same dimension, it is not
possible to add, subtract, multiply or divide arrays A
and D, or arrays D and D.’

Operations of addition and subtraction are the


same both for matrices and arrays, therefore simply
‘+’ and ‘-’ characters are used

Operations of multiplication, subtraction and


transposition are different, therefore the period-
character pairs ‘.*’, ‘./’ and ‘.’’ are used for arrays
Arrays
The numbers 0, 0.1, 0.2, …, 10 can be assigned to the variable u by
typing:

u = [0:0.1:10];

To compute w = 5 sin u for u = 0, 0.1, 0.2, …, 10, the session is:

>>u = [0:0.1:10];

>>w = 5*sin(u);

The single line, w = 5*sin(u), computed the formula w = 5*sin u

101 times.
Arrays indexing
>>u(7)
ans =
0.6000
>>w(7)
ans =
2.8232

Use the length function to determine how many values are in an array

>>m = length(w)
m =
101
Commonly used mathematical functions

ex exp(x) √x sqrt(x) ln x log(x)


log10 x log10(x) cos x cos(x) sin x sin(x)
tan x tan(x) cos-1 x acos(x) sin-1 x asin(x)
tan-1 x atan(x)

MATLAB trigonometric
functions use radian measure
Relational operators
Relational operators examples
>> x = [6,3,9]; y = [14,2,9];
>> z = (x < y)
z =
1 0 0
>>z = ( x > y)
z =
0 1 0
>>z = (x ~= y)
z =
1 1 0
>>z = ( x == y)
z =
0 0 1
Some additional array functions
[u,v,w] = find(A) Computes the arrays u and v, containing the row
and column indices of the nonzero elements of
the matrix A, and the array w, containing the
values of the nonzero elements. The array w may
be omitted.

max(A) Returns the algebraically largest element in A if A


is a vector.

Returns a row vector containing the largest


elements in each column if A is a matrix.

If any of the elements are complex, max(A)


returns the elements that have the largest
magnitudes.
Some additional array functions

size(A) Returns a row vector [m n] containing the sizes of


the m x n array A

sort(A) Sorts each column of the array A in ascending


order and returns an array the same size as A

sum(A) Sums the elements in each column of the array A


and returns a row vector containing the sums.
Plot
Plot elements
Plot (plot_ex.m in LMS)

plot(x,y) Generates a plot of the array y versus the


array x on rectilinear axes

title(’text’) Puts text in a title at the top of the plot

xlabel(’text’) Adds a text label to the horizontal axis (the


abscissa)

ylabel(’text’) Adds a text label to the vertical axis (the


ordinate)
Three-dimensional plot
contour(x,y,z) Creates a contour plot.
mesh(x,y,z) Creates a 3D mesh surface plot.
meshc(x,y,z) Same as mesh but draws contours under the
surface.
Same as mesh but draws vertical reference lines
meshz(x,y,z)
under the surface.
surf(x,y,z) Creates a shaded 3D mesh surface plot.
surfc(x,y,z) Same as surf but draws contours under the
surface.

[X,Y] = meshgrid(x,y) Creates the matrices X and Y from the vectors x


and y to define a rectangular grid.
Same as mesh but draws mesh lines in one
waterfall(x,y,z) direction only.
Performing operations in MATLAB
You can perform operations in MATLAB in two ways:

1. In the interactive mode, in which all commands are entered directly


in the Command window
2. By running a MATLAB program stored in Script file.

This type of file contains MATLAB commands, so running it is equivalent


to typing all the commands—one at a time—at the Command window
prompt.

You can run the file by typing its name at the Command window prompt.
Command window and Editor
Keep in mind when using script files

1. The name of a script file must begin with a letter, and may include
digits and the underscore character, up to 31 characters.

2. Do not give a script file the same name as a variable.

3. Do not give a script file the same name as a MATLAB command or


function. You can check to see if a command, function or file name
already exists by using the exist command.
When you type problem1,
1. MATLAB first checks to see if problem1 is a variable and if so,
displays its value.

2. If not, MATLAB then checks to see if problem1 is one of its own


commands, and executes it if it is.

3. If not, MATLAB then looks in the current directory for a file named
problem1.m and executes problem1 if it finds it.

4. If not, MATLAB then searches the directories in its search path, in


order, for problem1.m and then executes it if found.
Programming in MATLAB
Algorithm: an ordered sequence of precisely defined instructions
that performs some task in a finite amount of time. Ordered means
that the instructions can be numbered, but an algorithm must have
the ability to alter the order of its instructions using a control
structure.

There are three categories of algorithmic operations:

Sequential operations: Instructions executed in order.

Conditional operations: Control structures that first ask a


question to be answered with a true/false answer and then select the
next instruction based on the answer.

Iterative operations (loops): Control structures that repeat the


Programming: Debugging script files

Program errors usually fall into one of the following categories.

1. Syntax errors: such as omitting a parenthesis or comma, or


spelling a command name incorrectly. MATLAB usually detects the
more obvious errors and displays a message describing the error
and its location.

2. Runtime errors: errors due to an incorrect mathematical


procedure, called. Their occurrence often depends on the particular
input data. A common example is division by zero.
Programming: Comments
The comment symbol may be put anywhere in the line. MATLAB
ignores everything to the right of the % symbol. For example,

>>% This is a comment.

>>x = 2+3 % So is this.

x =

Note that the portion of the line before the % sign is executed to
compute x.
Programming Style
1. Comments section:

a. The name of the program and any key words in the first line.

b. The date created, and the creators' names in the second line.

c. The definitions of the variable names for every input and output.

d. The name of every user-defined function called by the program.

2. Input section: Include input data and/or the input functions and
comments for documentation
3. Calculation section
4. Output section: This section might contain functions for displaying
the output on the screen.
Help center
User-defined functions

The first line in a function file must begin with a function definition
line that has a list of inputs and outputs. This line distinguishes a
function M-file from a script M-file. Its syntax is as follows:

function [output variables] = name(input variables)

Note that the output variables are enclosed in square brackets, while
the input variables must be enclosed with parentheses. The function
name (here, name) should be the same as the file name in which it is
saved (with the .m extension).
Example

function z = fun(x,y)

u = 3*x;

z = u + 6*y.^2;

Note the use of a semicolon at the end of the lines. This prevents the
values of u and z from being displayed.

Note also the use of the array exponentiation operator (.^). This
enables the function to accept y as an array.
Functions definition line examples
1. One input, one output:

function [area_square] = square(side)

2. Brackets are optional for one input, one output:

function area_square = square(side)

3. Two inputs, one output:

function [volume_box] = box(height,width,length)

4. One input, two outputs:

function [area_circle,circumf] = circle(radius)

5. No named output: function sqplot(side)


Function example
function [dist,vel] = drop(g,vO,t);
% Computes the distance travelled and the
% velocity of a dropped object,
% as functions of g,
% the initial velocity vO, and
% the time t.

vel = g*t + vO;


dist = 0.5*g*t.^2 + vO*t;

You might also like