You are on page 1of 36

IMDC MATLAB COURSE 2013

SESSION 1 - Introduction to Matlab fundamentals

Lecturers: Vincent Kox, Kevin Delecluyse, Alexander Breugem


SESSION 1 Course overview Introduction MATLAB = Calculator Arrays
Double Logical Character Cell Structure

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

The Graphical User Interface (GUI)


CURRENT FOLDER PATH OF CURRENT FOLDER

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

The Graphical User Interface (GUI)


• Current folder: displays the contents of the folder to which the folder path points
• Workspace: contains the variables, arrays, objects, … created during the current Matlab
sessions that are still in memory. The worlspace can be (partially) cleared manually, or by
using specific commands (i.e. clear varname, clear all, clear)
• Command window: this is where the user interacts with MATLAB. By typing
commands, various tasks are carried out, such as creating and manipulating variables
and arrays, writing code on the fly, umporting and exporting data, visualising data etc.
The command window may also display the outcome of calculations and any warnings
or (error) messages resulting from the command inputs.
• Command history: Contains the history of every command that appeared in the
command window .
• Editor: allows the user to open, edit and save scripts and functions (i.e. a number of
subsequent lines of code with the intention of executing and repeating specific tasks) as
they would in a regular text editor. These scripts (format filename = script.m) can be
executed in the command window with one command.

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 as a calculator (1) Try it yourself

• Arithmetic operators: >> 2^4+4^2


 a+b, a-b, a*b, a/b, a^b, sqrt(a), () Brackets have priority:
 operator spacing purely esthetic
>> 2 * (20 + 25);
 the decimal sign = .
 3x10³ = 3E3 = 3E+3 = 3E+03 = 3E+003 With suppresed output (semicolon
• Logical operators operator), no result is shown in the
 <, >, <=, >=, ==, ~=, ~, &, | command window. However, the result is
 Results in variable of type logical (cf. still stored in the variable ans (check the
infra): 1 (true) or 0 (false) workspace):
• Trigonometric operators: >> sin(ans/180*pi)
 sin(a), cos(a), tan(a), atan(a), etc. >> sin(pi)^2+cos(pi)^2
 a is expressed in radials!
 pi is a built in variable Multiple line statements:
• Suppressing output: semicolon operator ; >> sin(pi/2) > cos(pi/2) && ans == 1 ||…
• Multiple line input: ellipsis operator … 3<=2
• Cycle through previous commands: arrow
up or down
• Last result stored in variable ans
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 as a calculator (2) Try it yourself

• Round off functions: >> round(-5.6)


 round: round towards nearest integer >> floor(-5.6)
 fix: round towards 0 >> fix(-5.6)
 floor: round towards minus infinity >> ceil(-5.6)
 ceil: round towards plus infinity Now try the same commands on +5.6. Do
 rem: remainder after division you understand the differences between
 mod: modulus after division these functions?
 abs: absolute value >> rem(-6,5)
 sign: signum function >> mod(-6,5)
Can you spot the difference between the
• Exponential functions: two? Tip: the answer lies in the difference
 exp: exponential between fix and floor.
 log: natural logarithm >> exp(1)
 log10: base 10 logarithm This gives you the Euler number e, which
is not baked into MATLAb as pi is.
>> log(ans)
>> log10(10)

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

Arrays: the keys to the MATLAB universe


Arrays are the building blocks of any MATLAB code. All of the datatypes (a.k.a classes)
that exist in MATLAB must be seen as arrays. Understanding what these arrays look like,
what types or arrays there are and how MATLAB works with them is one of the most
important objectives when taking a MATLAB course. Once you figure out this
fundamental lesson, you will hold the key to interpreting MATLAB code and creating
your own scripts. The remainder of this session is spent on explaining the ins and outs
of MATLAB arrays

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

Double = numeric arrays


If an array contains numeric values, it is called a double. All doubles are automatically
assigned as complex, double-precision arrays, so there is never any need for converting
numeric data from e.g. integer to real. Double arrays may also contain Inf (positive
infinity), -Inf (negative infinity) and NaN (not-a-number).

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

Subscripting Try it yourself

Array elements or sections can be selected Build a random 4x5-matrix


by using the command arrayname(i,j). >> A=rand(4,5)
Indices i and j are double vectors of Check the dimension number and size:
integers larger than zero or logical vectors .
>>a=size(A); b=length(size(A));
Both indices i (rows) and j (columns) start
counting at the upper-left corner of the Now, here are some ways to select row 4:
array. The number of indices must equal B=A(4,[1 2 3 4 5]);C=A(4,1:end);D=A(4,:);
the number of array dimensions, while the Notice the use of the colon operator to
indices must not exceed the number of select sequential elements and the word
elements along that dimension. The end to indicate the final element. The
following commands can be used to assess colon by itself selects all elements along a
dimensions and size: dimension.
• size(array,dim): gives the number of
elements in an array along the specified >> D=A([2 4],2:3); E=A(:,[3 1]);
dimension. If no dimension is specified, the For selecting non-sequential elements,
sizes of all dimensions are listed the use of vectors cannot be avoided.
• length(array): gives the number of Notice that the rows and columns can be
elements in a column or row vector switched!
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

Replacing or removing elements Try it yourself

Subscripting can be used to replace or Build a 5x5-matrix and a 3x3-matrix:


remove elements from an array. >> A=ones(5); B=magic(3);
Replace elements of A with B:
Replacing elements is very similar to
>>A(1:3,3:5)=B;
declaration:
arrayname(i,j) = array >>A([1 3 5],[2 5 4])=B([1 3 2],:);
Attention: always ensure the replacing As you can see, all the possibilities of
array has the same size as the (sub)array array subscripting apply.
being replaced. Now try removing array elements:
In order to remove elements, they are >>C=A;A(:,3)=[]; B([1 3],:) =[];
replaced by the empty matrix []: However,…
arrayname(i,j) = [] >>C(1:3,3:5)=[];
Attention: when removing elements from a
This delivers an error message. Why do
matrix, always ensure all rows (and
you think that is?
columns) are of equal length after removal.

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

Concatenation Try it yourself

Concatenation is the process of combining >> A=eye(2); B=magic(2); C=zeros(2,3);


small arrays to make bigger ones: Concatenate matrices:
newarray = [array1 array2; …
>>D=[A B]; E=[A;B]; F=[A,C];
array3, array4];
As always: make sure the dimensions of the However:
arrays you concatenate are compatible. >> G=[A;C];
Alternatively, let’s create the matrix
There exist a number of concatenation-
specific MATLAB commands: >> H=zeros(4,3)
• horzcat(A,B) = horizontal concatenation from C, using MATLAB commands:
• vertcat(A,B) = vertical concatenation >> I = vertcat(C,C);
• cat(dim,A,B) = concatenation along a
>> J = cat(1,C,C);
specified dimension. cat(2, A, B) is the
same as [A, B] or [A B], and cat(1, A, B) is >> K = repmat(C,[2 1]);
the same as [A; B].
• repmat(A,[m n p...]): replicate A m times
along dimension 1, n times along
dimension 2, p times …
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

N-dimensional arrays (1)


4-dimensional array
As stated before, the number of array A
A(1:2,1:2,1:3,1:2)
dimensions N is not limited to 2. Indeed, N
can be as high as you want. This might
seem odd at first, since we are used to
thinking of space in three dimensions and
possibly time as a fourth dimension, but
beyond that our minds hit the limits of
reality. However, MATLAB arrays are not A(:,:,1,1:2) A(:,:,2,1:2) A(:,:,3,1:2)

limited to these preconceptions, and their


dimensions must be seen as simply a ways
of storing information on different levels.
Imagine a box (level N= 2), that contains
three other boxes (level N=3). All of these A(:,:,1,1) A(:,:,2,1) A(:,:,1,1)
boxes contain two more boxes (level N=4).
Now imagine that these boxes are of equal
size. Having a hard time? The figure to the
right might help.
A(:,:,1,2) A(:,:,2,2) A(:,:,1,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

N-dimensional arrays (2)


SESSION 1 4-dimensional array
• N-dimensional arrays always consists of a A
A(1:2,1:2,1:3,1:4)
number of 2-dimensional subarrays
• The sizes of the first two dimensions
determine the number of rows and
columns in these subarrays
• The total number of subarrays is equal to:
#subarrays = P size(A,i)
with i=3:N A(:,:,1,1:4) A(:,:,2,1:4) A(:,:,3,1:4)

A(:,:,1,2) A(:,:,2,2) A(:,:,2,1) A(:,:,2,2) A(:,:,3,1) A(:,:,3,2)

A(:,:,1,3) A(:,:,2,4) A(:,:,2,3) A(:,:,2,4) A(:,:,3,3) A(:,:,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

N-dimensional arrays (3) Try it yourself

SESSION 1 of N-dimensional arrays is a bit


Declaration >>A=ones(2);A(:,:,2)=[1 2;3 4]; A(:,:,1)
more laborious, as there exist only Notice the promotion of previous A(:,:) to
separators for two dimensions the first subarray of dimension 3.
(spaces/commas, semicolons). For every
>> B = cat(3,ones(2),[1 2;3 4]);
other dimension, the subarray has to be
declared separately: As you can see: A=B. Similarly:
array(1:n,1:m,:,…,:,k)=subarray(1:n,1:m) >>C=A;A(:,1:2,3)=[5 6];A(:,1:2,4)=[5 6];
with k=1:size(array,N) >>D=cat(3,C,repmat([5 6;7 8],[1 1 2]));
Whenever a specific subarray is not
declared, it is declared as zeros(m,n) Replacing end removing elements works
automatically. for N-dimensional arrays as well.
Attention: when expanding an existing N- >>E=repmat(ones(4,4),[1 1 2 2]);
dimensional array to dimension N+1, the Replace all of the 2x2 cores by zeros and
subarrays of dimension N are automatically remove all the other elements:
promoted to the first subarrays of
>>E(2:3,2:3,:,:)=repmat(zeros(2),...
dimension N+1:
[1 1 2 4]);
array(:,:,1) = A  array(:,:,1,1) = A
>>E([1 4],:,:,:)=[];E(:,[1 4],:,:)=[];
array(:,:,2) = B  array(:,:,2,1) = B
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

Logical arrays Try it yourself

Logicals are arrays containing the elements >>D=magic(4);D([1 4],[1 4])=0;


true (1) and false (0). When involved in >>L=logical(D);
numerical operations, the ones and zeros
>>L(1,2)=0;L(2,2)=2; islogical(L)
are treated as doubles. However, sometimes
it is necessary to distinct doubles from Replacing elements with scalars yields
logicals. false when the scalar=0 and true when
Declaration of logical arrays is carried out the scalar >=1. The resulting array
using the function logical(array), which remains logical. However…
converts a double array into a logical array >>LL=L+L; islogical(LL)
and converts all nonzero elements to true, is not at logical array but a double array.
while all zero elements are converted to
false. Functions true() and false() are the >>T=true(2);A=magic(2);F=false(2);
logical equivalents of ones() and zeros(). >>M1=logical(T+A+F);M2=T|A|F;
To check if an array is logical, use the >>M3=logical(T.*A.*F);M4=T&A&F;
function islogical(array), which results in a
Compare the output. The sign .* indicates
logical scalar 1 (true) or 0 (false).
element-by-element multiplication (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

Logical subscripting Try it yourself

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

Character arrays Try it yourself

A character array is an array whose >>str1='Matlab'; str2='is'; str3='cool!';


elements are of the character class. Such >>str = [str1 str2 str3];
elements are used to create text. Spaces are inserted manually as part of
To declare a character, simply put its value the concatenation:
between single quotes: >>str=[str1 ' ' str2 ' ' str3];
char = 'a'; Attention: the space needs to be typed!
The function ischar checks whether an array This is not the same as the empty matrix
is a character array. sign.
A row vector of characters is called a string: >>Q='What''s cool? '; A=str(1:6)
string = 'abcd'; str = [‘a’ ‘b’ ‘c’ ‘d’]; Array elements can be replaced…
Special cases: >>Cooler = 'Samson';
• To use the quote mark ‘ as a character >>str(1:6)=Cooler; str
itself, type it twice Replacing strings is also possible using
• Do not confuse this with the empty string: strrep:
emptystr='' >>str=strrep(str, 'Samson','Matlab')
• To combine characters or strings into a and even removed:
new string, use concatenation. >>str(1:10)=[];
• Regular subscripting rules apply
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

N-dimensional character arrays Try it yourself

Character arrays can be N-dimenional. >>str1='Today''s Matlab instructors';


However, their use is mostly limited to N=2, >>l=length(str1);
which represents multiline text. >>str2='Vincent Kox';str2(l)=' ';
With the preceding array types, it was >>str3='Kevin Delecluyse' ;str3(l)=' ';
important that the number of elements on >>str=[str1;str2;str3];
every row and column was the same. With As you can see, non-declared elements
character arrays this translates to an equal are declared automatically as a space.
amount of characters on every line of text, >>Name1=str(2,1);Name2=str(3,1);
meaning spaced are added to the end of Now let’s see which instructor has the
every shorter string in the matrix to pad its longest name:
length. These spaces make the use of >>VIK=length(deblank(Name1))>…
character matrices impractical, expecially length(deblank(Name2))
when the length of the elements strongly >>KDL=length(deblank(Name1))<…
differs. Applying cells of strings (cf. infra) is length(deblank(Name2))
lot more convenient! However, there does
exist the deblank() command to delete the
trailing spaces in a text string, should the
need arise.
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

Declaration of cell arrays


Cell arrays are declared using curly brackets or braces {} instead of the square brackets []:
cellarray={array 1 array2; …};

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

First, we create a cell array:


>> C={'abcd' repmat(magic(2),[1 1 3]); true(3) {{'this';'is';'another';'cellarray'} ['this';'is
';'not '] ones(4)}};
The first level consists 4 cells. The second level of one 2D-character, one 3D-double, one 2D-
logical and one cell array. The third level consists of another cell array, a 2D-character and a
2D-double. Finally, the fourt level contains four 2D-characters. Now, let’s play around with
some subscripting!
Try and acces the character array ‘abcd’.
>> C(1,1);a=ischar(ans);C{1,1};b=ischar(ans)
As you can see, using round brackets yields the element at position (1,1), which is a cell (that
contains the character array). The curly brackets enter the cell at position {1,1} and yield its
contents, which is the character array ‘abcd’. Now, try and access element (2,2,3) of the
double array in the cell at position (1,2):
>>C{1,2}(2,2,3)
The matrix is at the second level, in the cell at position(1,2). So, you go inside this cell with
C{1,2}, after which you reach the double array. Then apply regular subscripting to this array.
Finally, try and access the substring ‘cell’ from the string‘cellarray’:
>> C{2,2}{1,1}{4,1}(1,1: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

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

5 6 7 8 C=mat2cell(A,[1 3],[3 3]) 5 6 7 8

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

Declaration Try it yourself

• 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

Structure subscripting Try it yourself

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:

structure array = cell2struct(cell array,fields, dim)

• 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

Datatype conversion (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

Datatype conversion (3)


• A structure array can be converted to a cell array using struct2cell:

cell array = struct2cell(structure array)

• 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)]

2. Assign the following text to a cell of strings C:

IMDC staff consists of about 50 highly skilled employees


Most of the employees have a Masters degree

3. Make the following changes to the text stored in cell array C:


a. Append ‘in engineering’ to the second sentence, while deleting ‘of the’
b. Change ’50’ to ‘100’ in the first sentence
c. Add a third line ‘The employees have a broad and thorough knowledge’
d. Delete the second sentence
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 (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.

6. From C1, create a 5x1 structure aray S2 with fields A, B and C.

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

You might also like