Professional Documents
Culture Documents
Course Overview
SESSION 1
03/09: Session 1 – Introduction to Matlab Fundamentals
10/09: Session 2 – Array Operations and Manipulations
17/09: Session 3 – Writing Functions and Scripts
24/09: Session 4 – Debugging Scripts
01/10: Session 5 – Data processing and Input/Output
08/10: Session 6 – Data Visualisation, Part 1
15/10: Session 7 – Data Visualisation, Part 2
22/10: Session 8 – Programming Techniques
29/10: Session 9 – Programming, House rules
05/11: Session 10 – Object Oriented Programming
12/11: Session 11 – Exam
19/11: Session 12 – Feedback Exam
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem
SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure
What is MATLAB?
MATLAB is short for MATrix LABoratory. It was invented in the late 1970s by Cleve Moler
at the University of New Mexico to give his students acces to state-of-the-art FORTRAN
libraries for matrix computation without them having to learn FORTRAN itself. In 1983,
an engineer named Jack Little recognized the commercial potential and helped Moler
and Bangert rewrite MATLAB in C. In 1984, they founded The Mathworks to continue its
development. A development that, even today, is still moving forward.
Key characteristics
• The tool of choice for high-productivity research, development and analysis
• A high-level language for technical computing, making it possible to carry out
computations without writing hundreds of lines of code
• A user-friendly, intuitive syntax that favors brevity and simplicity
• Easy extensibility, by the user or via packages (toolboxes)
• Powerful, easy-to-use graphics and visualisation capabilities
• A very vivid and active user community, with fora to share and dowload user-written
scripts (File Exchange) and ask or answer MATLAB-related questions
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem
SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure
WORKSPACE
EDITOR
COMMAND WINDOW
COMMAND HISTORY
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem
SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem
SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem
SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem
SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure
Array dimensions
• The smallest possible array is the 1x1-array, and contains one single element of any
datatype.
• Expanding this array over one dimension yields a nx1-array or a 1xm-array. The first
dimension of an array is always amount of rows, the second dimension is always the
amount of columns. Therefore, the former is usually called a column vector (n rows, 1
column) and the latter is a row vector (1 row, m columns)
• An nxm-array consists of n rows and m columns. This twodimensional array is
commonly referred to as a matrix
• An array with N dimensions is simply called an N-dimensional array. N can be as high
as you want, as arrays are certainly not restricted to the three dimensional world we are
used to. Just look at arrays as a way of storing information, with every dimension an
extra layer of information.
• The size and amount of dimensions of an array can grow at any time. However, scalar
arrays may only contain elements of one datatype, while each column, row or
dimension must have the same size. This restriction does not hold for cell arrays or
structures (cf. infra)
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem
SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure
Array declaration
Most modern calculators have the option to store one or more results, and even
functions, in memory for future use. This has an obvious time-saving advantage, as this
avoids repeating calculations. MATLAB can use the memory of your computer to that
same advantage. Without maybe realising it, you already created your first array when
performing operations in the command window. As no declaration occured, the result
was simply stored in the array ans, which is the default name for arrays.
The value of ans is overwritten when the next undeclared calculation occurs. In order to
keep results in memory, a name must be assigned to the array in which you want to
store the result. This is called array declaration, and is discussed for each datatype
separately.
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem
SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure
Numeric
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem
SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure
Declaration
SESSION
Try it yourself
1 and view the result by double-clicking the array in the workspace
Arrays are declared using an = sign. When the array dimension increases beyond a 1x1-array,
the use of square brackets is required. The elements of row vectors are seperated by spaces
or commas, a semicolon indicates a new row. Arrays can be used as elements of other
arrays, and – naturally – calculations are allowed when declaring array elements:
>> a = 3; b = 2E+09; c = [1 6] ; d = [3 ; -1.8]; A = [exp(5) 5*20 4/2; sqrt(25) a b];
Regular numeric series can be generated faster by using the colon operator. In this case, the
use of brackets can be omitted to declare row vectors, but not for matrices. The general
MATLAB command is ‘array = initial value : increment : final value’. When the increment
equals 1, it can be omitted:
>>e= 1 : 10; B = [0:2:20 ; 0:10:100];
A column vector can be produced by using the transpose command = single quote ‘. Note
the necessity of brackets - round brackets are allowed here – to transpose the column:
>> f = (6:10)’; g= [6:10]’; h = 6:10’;
Other useful functions are linspace(a,b,n) and logspace(a,b,n), which gerenate linearly/
logarithmically spaced row vectors of length n from a to b/10a to 10b, respectively:
>> i = linspace(3,15,5); j = logspace(0,3,4);
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem
SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem
SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem
SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure
A powerful application of logical arrays is Suppose you are given a model grid of
logical subscripting, also known as logical 10x10 cells. Cells with D<50m are land
indexing. Here, you use logical arrays as cells, cells with D>90 are considered
array subscripts, in which a true (1) selects outliers:
the element, and a false (0) does not. >> D=100*rand(10);
The logical operators (cf. pag. 6) can be
The initial water depth H= D-50m (land
used to introduce conditional statements
H=0m) and the roughness R=0.0011(land
into arrays. If the condition is met, a true is
R=0.0023) . Instead of creating these
generated, else the element is set to zero.
arrays manually (= a lot of work!), let us
By using &,| and ~, this conditional
create a logical mask instead:
statement can be as complicated as the
situation demands it to be. >>mask=logical(zeros(10)); (initialisation)
When used cleverly, logical subscripting can >>mask(D>=50 & D<=90)=1;
speed up your code significantly by e.g. Now we can use this mask to create our
circumventing the use of for-loops to check arrays:
conditional statements for every element
(cf. infra). >>H=zeros(10);H(mask)=D(mask)-50;
>>R=0.0023*ones(10);R(mask)=0.0011;
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem
SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure
Cell arrays
A cell is a datatype that may contain any kind of data: doubles, logicals, characters …
even other cells. A cell array is an array of cells. Thus, cell arrays are particularly useful
when you want to store different datatypes in one array. This is the first major difference
with the previously discussed arrays, which could only contain data of one datatype. A
second difference is that the elements in a cell array may differ in size and dimension , as
opposed to the strict ‘equal size’ limitation of other arrays.
A representation of a cell array is
pictured to the right.
This cell array is two-dimensional,
and contains six cells. Four cells
contain doubles, one contains a
character and one contains
another cell array. Although it is
not the case here, the dimensions
of the doubles and characters is
not limited to N=2.
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem
SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure
Cell subscripting
• Cell arrays can contain different levels, i.e. a cell array within a cell array etc.
• To enter a deeper level of the cell array, use {}:
cellarray{i,j} = contents inside cell {i,j}
• To select the element at a certain level, use ():
cellarray(i,j) = cell at (i,j)
cellarray{i,j}(i,j,…) = element at (i,j,…) in cell {i,j}
• The result of subscripting with curly brackets is always the complete array at the next
level
• Round brackets work as the subscripting you already know, and always result in one
element of the array at the current level. The amount of indices therefore needs to
correspond to the amount of dimensions of this array.
• You cannot use {} on non-cell array datatypes.
• The final level of a cell array always contains non-cell array datatypes
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem
SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure
Try it yourself
Datatype conversion(1)
• Converting a cell array into a numeric, logical or character array is done by issuing the
command cell2mat
array = cell2mat(cell (sub)array)
• The cells in the cell (sub)array you are converting must all contain the same datatype
• The elements in the cells must combine to form an array with rows and columns of
equal length. In other words: the contents of cells in the same column (row)must have
the same number of columns (rows), although they need not have the same number of
rows (columns).
1x1 1x3
1 2 3 4 1 2 3 4
A =cell2mat(C)
5 6 7 8 5 6 7 8
3x1 9 10 11 12 3x3 9 10 11 12
13 14 15 16 13 14 15 16
C = 2x2 cell array A = 4x4 array
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem
SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure
Datatype conversion(2)
• Converting a double, logical or character array into a cell array is done by issuing the
command mat2cell
cell array = mat2cell(array, dim1,…,dimN)
• dim 1 to dimN are numeric vectors that describe how to divide each dimension of the
array within the cell array
• If you only specify one dimension dim1, the result will be a dim1x1 cell array
1x1 1x3
1 2 3 4 1 2 3 4
9 10 11 12 3x1 9 10 11 12 3x3
13 14 15 16 13 14 15 16
A = 4x4 array C = 2x2 cell array
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem
SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure
Datatype conversion(3)
• Converting an array into a cell array can also be done by issuing the command
num2cell:
cell array = num2cell(array, dim)
• dim specifies which dimensions of A to include in each cell and can be a scalar or a
vector of dimensions. If dim is not specified, every element of the array is stored in a
different cell of the cell array
1 2 C=num2cell(A,1) 1 2 1 2 C=num2cell(A,1) 1 2
3 4 3 4 3 4 3 4
5 6 5 6 5 6 5 6
3x2 array A 1x2 cell array C 3x2 array A 1x1 cell array C
C=num2cell(A,2) 1 2 C=num2cell(A) 1 2
1 2 1 2
3 4 3 4 3 4 3 4
5 6 5 6 5 6 5 6
3x2 array A 3x1 cell array C 3x2 array A 3x2 cell array C
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem
SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure
Structures
Structures store data in a way that is very
reminiscent of folders in an operating
system. As with cells, data is stored on
different levels. Each level can have different
fields (folders) with their own fieldname
(foldername), which contain data or other
fields of their own. Each field can contain
any datatype, even structures.
In the example depicted to the right, the
structure array ‘patient’ contains three
fields: ‘name’, ‘billing’ and ‘test’. These
fields contain a string (the patient’s name),
a double and a double array, respectively.
As you can see, fieldnames can give a lot of
additional information about the data that
is stored in the structure. That is why
structures are very useful to present data in
a transparent, database-style way.
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem
SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure
• Structures are declared as follows: Create a structure of IMDC staff with the
s = struct(field1,value1,...,fieldN,valueN); following fields: Name, Sex, Age. Use your
• You can also create fields on the fly, even if own data:
that structure doesn’t exist yet: >> imdc.Name=‘Kevin Delecluyse’;
s.field = array; >> imdc.Sex=‘M’; imdc.Age=30;
• Another way of creating fields is by using a Note that the following has the same
(previously declared) string as a fieldname: result:
field = ‘fieldname’; >>imdc = struct(Name,’Kevin …
s.(field) = array; Delecluyse’,Sex,’M’,Age,30);
• To remove fields: Add a second name (cf. infra):
s=rmfield(s,{field,…,fieldN}); >>imdc(2,1).Name = ‘Vincent Kox’; As
• To check if a field exists in the structure: Notice that the 2x1-structure now
isfield(s,{field1,…,fieldN}); contains two 1x1 structures, which both
• Declaring a field for one element of the contain the three fields. The undeclared
array automatically creates the field in the age and sex in the second structure are [].
other elements. These fields have the value >>imdc(1,1).len=174;isfield(imdc,len)
[] until they are assigned another value. Now remove everything but the names:
>>imdc=rmfield(imdc,{age,sex,len})
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem
SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure
Every structure is a two-dimensional array, Let’s change the previous structure a bit:
with the following subscripting rules >>imdc.name.first =‘Kevi n’;
• Round brackets are used to select >>imdc.name.last= ‘Delecluyse’;
elements: Copy the structure to a second element:
s(i,j).field=… >>save=imdc;imdc(2)=imdc(1);
• Subscripting with only one index is also Notice that a row array is created
possible, but only useful for 1xm-arrays and automatically. In order to create a column
nx1-arrays: array:
s(2)=s(2,1) (column array) >>imdc=save;imdc(2,1)=imdc(1)
s(2)=s(1,2) (row array) New elements are added in the growing
• A structure element may contain another array dimension:
structure. In this case, simply apply >>imdc(3)=imdc(1);
subscripting to this structure as well: Now add an element to imdc(2,1).name:
s(i,j).field.subfield(p,q)=… >>imdc(2,1).name(2,1).first=‘Vincent’
>>imdc(2,1).name(2,1).last=‘cox’
Extract the full name of element (2,1):
>>fullname21=[imdc(2,1).name…
(2,1).first, ‘ ‘,imdc(2,1).name(2,1).last]
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem
SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure
Datatype conversion
As you’ve seen, both structures and cell arrays are fit to store arrays of different
datatypes, with different size. Which one you use depends on the application you have
in mind. You can convert a cell array to a structure array using cell2struct:
• The fields argument specifies field names for the structure array. This argument is an
array of strings or a cell array of strings.
• To create a structure array with fields derived from N rows of a cell array, specify N field
names in the fields argument, and the number 1 in the dim argument. To create a
structure array with fields derived from M columns of a cell array, specify M field names
in the fields argument and the number 2 in the dim argument.
• The structArray output is a structure array with N fields, where N is equal to the
number of fields in the fields input argument. The number of fields in the resulting
structure must equal the number of cells along dimension dim that you want to convert.
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem
SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem
SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure
• struct2cell(s) converts the n-by-m structure s (with p fields) into a p-by-n-by-m cell
array c. As such, it is the inverse function of cell2struct(c,fields,1), in which a p-by-n-by-
m cell is converted to a n-by-m structure. The inverse function of cell2struct(c,fields,2) is
simply the transposed version of cell2struct.
• Example: the 5x3 cell array C from the previous page can be converted from the 3x1
structure array S1 (with p=5 fields) by using C = struct2cell(S1), and from the 5x1
structure array S2 (with p=3 fields) by using C = struct2cell(S2)’.
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem
SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure
EXERCISES (1)
1. Assign the following matrices to a variable with the same name:
a. 10x10 matrix O containing only ones
b. b. 5x5 matrix Z containing only zeros
c. d. 5x10 matrix R containing random numbers between 0 and 1,
d. e. 10x10x2 array N, where N(:,:,1)=O and N(:,:,2)=[Z,O;R], using one statement.
e. Reassign matrix O and Z by using the function repmat
f. Use logical subscripting to assign a row vector V=[R(1,1) R(2,2) R(5,3)]
EXERCISES (2)
4. Create a 3x1-structure array S with fields X, Y, Z, T and H and the following data:
a. Series A (X = 10, Y = 50, Z = 20)
T = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
H = -5, -2.3, -3.1, -4, -6.1, -8, -2.9, -5.1, -3.2, -1
b. Series B (X = 1.5, Y = 42, Z=11.2)
T = 0.01, 0.1, 1, 10, 100, 1000, 10000
H = 2 0.2 1 3.4 2.1 10 0
c. Series C (X = 100, Y = 33, Z = -25)
T = 10, 20, 30, 40, 50
H = 1, 1, 1, 1, 1
5. Convert S into a 5x3 cell array C1 and a 3x5 cell array C2.
7. Change all of the H-values of series C into 0 and delete the observation series B.
MATLAB course 03/09/2013 Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem