CITS2401 Computer Analysis & Visualisation
SCHOOL OF COMPUTER SCIENCE AND SOFTWARE ENGINEERING
FACULTY OF ENGINEERING, COMPUTING AND MATHEMATICS
Topic 5Matlab Structures
Material from MATLAB for Engineers, Moore, Chapter 7,11Additional material by Peter Kovesi.
The University of Western Australia
Overview
Input and Output
Elementary data structures
Cell arrays
• Constructing cell arrays
• Cell arrays of strings
Structures
Arrays of structures
The University of Western Australia
User Defined Input To this point we have “hard coded” the values of variables into our M-file
programs The input function allows us to prompt the user to enter a value
The University of Western Australia
The input function is used in an M-file program to prompt the user to enter a value
The prompt is displayed in the command window
The University of Western Australia
The University of Western Australia
Input accepts a variety of data Scalars Matrices
• enter inside square brackets Character strings
• enter inside single quotes
• Or… specify string input with ‘s’
The University of Western Australia
Matrix input
Character input
Run this program twice more – once with numeric input and once with character input
The University of Western Australia
Indicates that the input should be interpreted as a string
The University of Western Australia
Output Options Enter the name of a variable Use the disp function Use the fprintf function Use the sprintf function
The University of Western Australia
disp The display (disp) function can be used to display the contents of a matrix without printing the matrix name
The disp function can also be used to display a string
The University of Western Australia
Strings are really arrays of character information
The result is a character array
The University of Western Australia
You can combine disp functions to create meaningful output from an M-file program, but the result of each disp function is on a separate line.
The University of Western Australia
Although these characters look like numbers, they are interpreted by the computer as part of a character array – they no longer have any numeric meaning
The University of Western Australia
This MATLAB program mimics a conversation, by using the input and disp functions.
Watch the interactions as it runs in the next slide
The University of Western Australia
The University of Western Australia
Formatted Output
fprintf gives you more control over your output than the disp function You can combine text and numbers You can control how many digits to display, and their position Arguments:
• format-string– includes place holders and formating information for numbers
• List of matrices
The University of Western Australia
Place holder for your variable value
Variable
8 total spaces2 after the decimal pointfloating point format
The University of Western Australia
You can also use exponential format
The University of Western Australia
X is a matrix
/n is a carriage return
The University of Western Australia
Despite the way it looks, the computer always considers a matrix as one big list, working down one column at a time
The University of Western Australia
Other ways of giving feedbackerror(msg)
• displays the specified error message msg and causes the function to exit. Used for "fatal" errors where there is no point (or way of) continuing. If msg is an empty string no action is taken.
warning(msg)
• displays the specified warning message msg, but allows the function to continue execution. Used for non-fatal errors.
isnumeric(V)
• returns True (1) if V is a numeric array, False (0) otherwise.
ischar(S)
• returns True (1) if S is a character array, False (0) otherwise.
The University of Western Australia
Checking function arguments
There are a number of functions that you can use to check arguments provided to a function: nargin
• returns the number of arguments that were supplied to the function. This is a function that takes no arguments.
nargout • returns the number of output arguments that the function
result is being assigned to in the calling program. This is a function that takes no arguments.
msg = nargchk(minArgNo, maxArgNo, actualArgNo) • returns an error message msg if a function is called with too
few or too many arguments (i.e. if actualArgNo is outside [minArgNo, maxArgNo]). If the number of arguments is within the range an empty string is returned.
The University of Western Australia
The all function
There is a function called all that checks if an array contains all ones.
all(V)
If V is a vector, all returns True if all the elements of V are nonzero. If V is a matrix, all operates on the columns of V, returning a vector.
For example:
>> all([3 4 5 6] == [3 1 5 4])
ans =
0
The University of Western Australia
An exampleLet's make the input to trianglearea "bullet proof":
% TRIANGLEAREA: A function to find the area of a triangle.
%% Usage: area = trianglearea(width, height)%% Arguments: width - The width of the triangle.% height - The height of the triangle.%% Returns: area - The area of the triangle.%% Author: Lecturers% Date: August 2010
function area = trianglearea(w, h)
The University of Western Australia
% Check for legal number of input arguments.msg = nargchk(2, 2, nargin);error(msg);
% If msg is not empty, this will print% out msg and stop the function.% If msg is empty, this command is ignored.
if ~isnumeric(w) | ~isnumeric(h) % Print an error message and return. error('Arguments must be numeric.');end
if ~all(size(w) == [1, 1]) | ~all(size(h) == [1, 1]) % Print an error message and return. error('Arguments must be scalar.');end
The University of Western Australia
if w < 0 | h < 0 % Print an error message and return.
error('Arguments must be non-negative.'); end
if w == 0 | h == 0 % Print a warning message, but do not stop % execution.
warning('width or height is zero.'); end
% If we get to this line, we can safely assume%the input is valid.
area = w*h/2;end % function trianglearea
The University of Western Australia
Elementary data structures
So far the only data structure we have seen is the array - a collection of identically typed data objects (typically numbers) stored sequentially in memory.
Often one wants to work with a collection of data objects that are of different types.
We may want to link character strings, numbers, or arrays of numbers together into data structures.
We may also want to use mechanisms other than arrays for handling collections of data objects.
The University of Western Australia
MATLAB’s arrays can store different types of data
Kinds of Data Stored in MATLAB Matrices
NumericCharacter LogicalSymbolic Objects - Symbolic Toolbox
Integer Floating Point
multiple signed integer types
multiple unsigned integer types
single precision
double precision
complex real
The University of Western Australia
Numeric Data Types
Numeric data is stored in numeric arrays The default data type is double precision floating
point Every time you enter a number into MATLAB,
the program assumes you’ve entered a double MATLAB conforms to the IEEE standards that
specify the meaning of the double data type
The University of Western Australia
When you define numeric values they default to doubles
Each value in a double array needs 8 bytes of memory to store
The University of Western Australia
Integers Integer arrays are new to MATLAB 7 Integers are stored in integer arrays
MATLAB Integer Types8-bit signed integer
int8 8-bit unsigned integer uint8
16-bit signed integer
int16 16-bit unsigned integer
uint16
32-bit signed integer
int32 32-bit unsigned integer
uint32
64-bit signed integer
int64 64-bit unsigned integer
uint64
Remember that 8 bits = 1 byte Each of these types require a different amount of storage
The University of Western Australia
You can determine the number of possible values allowed in the integer data type
Each of the integer types uses a different amount of storage, and can thus save different ranges of values
Determine the size range using
• intmax and intmin
The University of Western Australia
When do we use integers
Integer arrays can be used to store image information
These arrays are often very large, but there are a limited number of colors used in many of these images to create the picture.
Storing them as unsigned integer arrays reduces the storage requirement dramatically.
The University of Western Australia
Complex numbers
Default is double Twice as much storage is needed because the real and imaginary
components must be stored Could also be stored as a single or integer
The University of Western Australia
Character and String Data
Character arrays store character information A character array is produced from a string Any string represents a character array in MATLAB Each character requires 2 bytes of storage
The University of Western Australia
The fifth element of the H array is the letter y
The University of Western Australia
Cell Arrays (Text: Section 7.2.)
A cell array is a special kind of array in Matlab.
Instead of each location in the array holding a number, each element of a cell array is an address, or pointer, or reference, to another data structure.
These "pointed to" data structures can be of any type.
A cell array is like an address book that groups together information relevant to a problem.
The University of Western Australia
An Example The addresses are the addresses in memory where the relevant data
objects are stored. For example:
>> a = [1, 2 % A 2x2 matrix.
3, 4];
>> b = 'hello'; % A character string.
>> c = [7, 8, 9]; % A 1x3 matrix.
>> d = {a, b, c}; % d is a cell array that holds
% the addresses of, or “points
% to”, a, b, and c.
Notice curly brackets {}.
The University of Western Australia
Cell arrays vs. normal arrays The key difference between cell
arrays and normal arrays is that cell arrays contain pointers to data structures instead of data.
The University of Western Australia
Curly brackets
Cell arrays use curly brackets ({}) for selecting and displaying contents of cells.
Curly brackets indicate to Matlab that we want to refer to the data at the address stored in the cell array, rather than the address itself.
Curly brackets display the contents of the data structure contained at that position in the cell array.
>> d{1} % Access data stored at first address
% in d using curly brackets.
ans =
1 2 3 4
The University of Western Australia
Round brackets Round brackets display “what” is pointed to by the position in the
cell array. >> d(1) % d(1) tells you that the first address
% in d points to a 2x2 array of doubles.
% You never have access to the actual
% address itself.
ans =
[2x2 double]
But how the “what” is displayed depends on what it is! >> d{1} = 24
d(1) ans =
[24] % not [1x1 double]
The University of Western Australia
Curly vs. round brackets (cont.)>> d{2} % Access data at second address in d.
ans =
hello
>> d(2) % Display what is residing at the
% second address of the cell array d.
ans =
‘hello’
Matlab displays the data structures in each element of a cell array in a condensed form that limits each data structure to a single line. • If the entire data structure can be displayed on the single line, it is. • Otherwise, a summary is displayed.
The University of Western Australia
Constructing cell arrays You can build cell arrays in the same way you build ordinary
arrays, using curly brackets ({}) instead of square brackets ([]).
>> a = { [1 2], 'Jill'; [5 6 7; 8 9 10], 1 }
% Construct a 2x2 cell array containing four
% elements: a 1x2 array, a string, a 2x3 array,
% and a scalar.
a =
[1x2 double] 'Jill'
[2x3 double] [ 1]
>> a{2, 1} % Access data at cell{2, 1}
ans =
5 6 7
8 9 10
The University of Western Australia
Adding extra data to a cell array
If you add extra data, Matlab will automatically resize the cell array to accommodate it.
For example:
>> a{1, 3} = 'new data' % Add an element in % row 1, column 3.
a = [1x2 double] 'Jill' 'new data' [2x3 double] [ 1] []
To add the new string, Matlab needs to add a third column to the cell array. Cell arrays are themselves just arrays - they must remain rectangular. Note that the element {2, 3} in the cell array is set to the empty matrix.
The University of Western Australia
What happens if brackets are wrong?
If you use the wrong kind of addressing (the wrong kind of brackets), Matlab will warn you with a message like this:
>> a(1,3) = 'new data' % Attempt to set the address % stored in cell array
% element(1,3) to ‘new data’
??? Conversion to cell from char is not possible.
The University of Western Australia
Extract data from a cell array We can extract individual elements from data stored in a cell array by adding
the normal indexing commands to the cell indexing commands. >> c{1,1}(2) % Access element 2 of the matrix referred
% to by cell array element {1,1}.
ans =
2
>> c{2,1}(1:2, 2:3) % Access elements from the % matrix referred to by cell
% array element {2,1}.
ans =
6 7
9 10
The University of Western Australia
View the contents of a cell array You can view the contents of a cell array using the celldisp and
cellplot functions. For example:
>> celldisp(a) % Prints out the contents of % each cell in the cell array a.
a{1,1} =
1 2
a{2,1} =
5 6 7
8 9 10
a{1,2} =
Jill
a{2,2} =
1
etc...
The University of Western Australia
Graphical representation of the cell array
>> cellplot(a) % Displays a graphical representation
% of the cell array a.
The University of Western Australia
Memory pre-allocation for a cell array You can pre-allocate memory for a cell array with the cell
function.
>> c = cell(1, 5) % Allocates memory for a 1x5 % cell array.
Note that this call to cell only allocates space for the 5 addresses in memory - there is no data associated with these addresses yet (all we have is an empty address book with 5 blank entries).
c =
[] [] [] [] []
>> whos
Name Size Bytes Class
c 1x5 20 cell array
The cell array uses 20 bytes of memory - 4 bytes to store each address. This will be true on a 32 bit machine.
The University of Western Australia
Attach data to a cell array Having allocated space for a cell array, we can "attach" data to
the array as we wish.
For example:
>> c{4} = 'hello’;
>> d = [11 12 13 14]; % Construct a 1x4 matrix.
>> c{1} = d % Attach the new matrix to c{1}.
c =
[1x4 double] [] [] 'hello' []
Actually it is a copy of d that is attached to c{1}.
If d is modified or even deleted, the contents of the data referenced by c{1} will be left intact (pass-by-value).
The University of Western Australia
Pros and Cons Advantage: eliminates the possibility of nasty side effects that
could inadvertently occur should the data that is attached to a cell array be modified - the cell array has its own private copy of the data.
Disadvantage: extra time and space to create and store copy. Note that similar "attaching" operations in Java or C only
result in the memory address being copied - not the whole data object.
In Java or C, because there is only one actual data object, a change in the array d will result in a change being seen in c{1}; d and c{1} are simply two names for the same thing.
The University of Western Australia
A copy of the data - *not* address>> c(2) = c(1) % What does this do?
c =
[1x4 double] [1x4 double] [] 'hello' []
>> c{1}(1) = 99; % Modify the first element in the % array referenced by cell 1
>> c{1} % Display data referenced by cell 1
ans =
99 12 13 14
>> c{2} % Display data referenced by cell 2
ans =
11 12 13 14
The University of Western Australia
A copy of the data - *not* address
If c{1} refers to the contents, and c(1) refers to the address (pointer, reference), what should
>> c(2) = c(1)
do? How should >> c{2} = c{1}
>> c(2) = c(1)
differ? Do they differ in Matlab? Matlab doesn’t let you access the address - it jumps in and
says (to quote Hal from 2001) “I’m sorry Dave, I’m afraid I can’t do that. I’ll let you have a copy of the contents”.
Need to remember c(2)=c(1) copies the data structure in c(2) to c(1), not the address (or pointer).
The University of Western Australia
Cell arrays of strings A major use of cell arrays is storing arrays of strings.
Why? Matlab does not have a special String type as such - it just stores
arrays of characters.>> ’CITS2401' == [‘C' ‘I' ‘T' ‘S' ‘2' ‘4' ‘0' ‘1']
ans = 1 1 1 1 1 1 1 1 1
>> [‘CITS’,’2401’]
ans = ‘CITS2401’
>> {‘CITS’,’2401’}
ans = ‘CITS’ ‘2401’
The University of Western Australia
The cell array in the switch statement You may recognise the cell array from the switch statement...
switch (str) % The variable str is the variable
% that controls the switching.
% str can be a scalar or a string,
% but not an array.
% If str matches one of these items
case {'dog', 'cat', -3}
% then this code block will be evaluated.
disp('A pet or -3');
case {1, 2, 3, 4, 5}
disp('An integer in the range 1 to 5');
end
The University of Western Australia
Structures
In an array, each element is only known (or accessed) by specifying the name of the array followed by the row and column number of the element.
For example: >> a(3, 2) = 6;
In the case of normal arrays, each element must be of the same type. Cell arrays are accessed similarly, but may hold data of different types:
>> a{3,2} = 6;>> a{3,3} = ‘Hill’
The University of Western Australia
What is a structure? A structure is a data type in which individual data elements are
accessed by specifying a field name of the data element to access. The collection of fields in a structure is like a 1D cell array except
that we use field names rather than indices to access data. Each field of a structure can refer to data of any type. We can access individual fields of a structure by specifying the
structure name followed by a period and then the field name of interest.
There are two ways of generating the structure.1. Adding one field at a time using assignment statements2. All at once using the struct function
The University of Western Australia
Adding a field to a structure We can add a field to the structure at any time. Matlab automatically accommodates this in the same way that arrays and cell
arrays can be extended at any time. For example, imagine creating a structure called beam with the fields length,
sectionarea, material and manufacturer.
>> beam.length = 10.4;
>> beam.sectionarea = 0.03;
>> beam.material = 'Carbon Fibre'
>> beam.manufacturer = 'GLC'
beam =
length: 10.4000
sectionarea: 0.0300
material: 'Carbon Fibre'
manufacturer: 'GLC'
The University of Western Australia
A diagram for the structure
student
‘John Smith’
‘1First Ave, Crawley’
20007564
[30,40,70]
address
marks
number
name
The University of Western Australia
Using the struct function The syntax of the struct function is:
struct('field1', value1, 'field2', value2, ...)
Each valueX parameter used can be a single value or a cell array of values.
>> beam = struct('length', 1.2, 'sectionarea', 0.05, ...
'material', 'steel', 'manufacturer', ... 'unknown')
beam = length: 1.2000 sectionarea: 0.0500 material: 'steel' manufacturer: 'unknown'
The University of Western Australia
Manipulate the fields The Matlab function fieldnames
• recovers all the field names associated with a structure. • returns a cell array of strings.
For example: >> fieldnames(beam)
ans =
'length'
'sectionarea'
'material'
'manufacturer'
Matlab function rmfield - removes fields from a structure.
The University of Western Australia
Arrays of structures Often we will want multiple instances of a single structure. We can build up an array of structures. We call this array a structure
array. Matlab allows a structure array to grow automatically.
>> beam(2).length = 5 % Beam is now a structure array. % Set the length field of the second % element of the structure array to 5.
beam =
1x2 struct array with fields:
length
sectionarea
material
manufacturer
The University of Western Australia
Access the elements of a structure array
The name beam is now used to refer to the entire array of structures.
We can access elements of a structure array as if it was a normal array
For example: >> beam(1)
ans = length: 10.4000 sectionarea: 0.0300 material: 'Carbon Fibre' manufacturer: 'GLC'
The University of Western Australia
Access the elements of a structure array Since we only specified the length field of beam(2), Matlab
initialises the remaining fields to empty arrays:
>> beam(2)
ans =
length: 5
sectionarea: []
material: []
manufacturer: []
We can then fill in extra details as required.
For example:
>> beam(2).material = 'Steel';
The University of Western Australia
Diagram of the example structure
The University of Western Australia
Accessing elements of an individual structure
We access elements of an individual structure in the array using
• an array index to find the array element and then • a field name to access the field of the structure.
For example: >> beam(2).length
ans =
5
The University of Western Australia
Structure arrays as data tables
A structure array can also be considered to take the role of a database table:
Id Length SectionArea Material Manufact-
urer1 10.4 0.03 `Carbon
Fibre’ `GLC’
2 1.2 0.05 `steel’ `unknown’
The University of Western Australia
Creating a structure array with the struct function
Recall the syntax of the struct function is: struct('field1', value1, 'field2', value2, ...)
Each valueX parameter used can be a single value or a cell array of values.
>> s = struct('type', {'big', 'little'},... 'colour', 'red', 'x', {3, 4})
s =
1x2 struct array with fields:
type
colour
x
The University of Western Australia
Preallocate memory for a structure array The struct function is used to preallocate memory for a structure array. In this case, each valueX parameter would be a call to the cell function
to create empty cell arrays of the desired size.
>> NBeams = 20;>> beam = struct('length', cell(1, NBeams), ...
'sectionarea', cell(1, NBeams), ...
'material', cell(1, NBeams), ...
'manufacturer', cell(1, NBeams))
beam =
1x20 struct array with fields:
length
sectionarea
material
manufacturer
The University of Western Australia
There are a variety of array types to store the data
MATLAB Array Types
Character Arrays
Floating Point
single precision
double precision
Logical Arrays
Numeric Arrays
Symbolic Arrays
Cell Arrays
Structure Arrays
Other types, including user defined and JAVA types
Cell and Structure arrays can store different types of data in the same array
Integer
multiple signed integer types
multiple unsigned integer types
Most of these arrays can only hold information of one data type