Professional Documents
Culture Documents
DATA STRUCTURES
Programming with Matlab
CALENDAR
Unit What
1 Introduction to MATLAB
2 Flow control & Data Structures
3 Plotting
4 Strings & File IO
5 Complex Numbers
6 Combinatorics
7 Linear Algebra
8 Statistics & Data Analysis
9 Polynomial Approximation,
Curve Fitting
10 Root Finding, Numerical
Differentiation
11 Numerical Integration
12 MATLAB GUI
2
SCRIPTS
3
ALGORITHM
• Get input(s)
• Calculate the result(s)
• Display the output(s)
4
SCRIPTS
• To remove previous variables from the workspace, you may wish to place the
command clear all at the beginning of your script.
• The close all command may also be placed at the beginning if closing all
figures is desired prior to running the script.
• It is good practice to use ; at the end of commands when writing scripts to inhibt
unwanted output
• When a script is running the >> symbol at the terminal will disappear until it
finishes, preventing any commands from being input.
• To terminate the script before conclusion and regain control, press Ctrl+C.
5
ELLIPSIS
• Word wrap for comments is automatically enabled in scripts so that each line fits in
the viewable window to prevent the need for horizontal scrolling.
• Making use of ellipsis (...) can help make scripts more readable when there are
long statements of code:
A = [1 2 3 4 5 6; ...
6 5 4 3 2 1];
• This can also be used to make long character strings by concatenating two shorter
strings together:
6
CONDITIONAL STATEMENTS
• Scripts can be made more effective when you are able to control which blocks of
code are executed.
• MATLAB is capable of flow control just like any other language.
• The most basic flow control element is the if statement.
a = 6;
if a > 10
b = 0;
elseif a < 3
b = 1;
else
b = 2;
end
• The statements are evaluated only when the logical expressions are true.
• The elseif and else are optional.
7
FOR LOOPS
• A for loop uses a counter to repeatedly execute the block of code within it.
• It follows the syntax: for index=values, statements, end.
• The values portion of the syntax can take several forms, one of which is:
A = []; ii = 2 A = 2
for ii = 2:2:8 ii = 4 A = 2 4
A = [A ii] ii = 6 A = 2 4 6
end ii = 8 A = 2 4 6 8
• In this case, the index ii is incremented by an optional step size until it reaches 8.
• A is initialized as an empty matrix and its size is constantly updated as we add to it
during each iteration of the loop.
• Note that the name of the index variable is ii rather than the traditional i,
commonly used in C/C++. Recall that i is reserved for the complex unit.
• Can create character indices as well, e.g. ii = 'a':'z'.
• The value of the index should never be modified by the statements inside the loop.
8
FOR LOOPS
• values can also be defined without the use of the colon operator:
9
PRE-ALLOCATING SPACE TO VARIABLES
• Note that in the previous example, we pre-allocated space to matrix A rather than
letting MATLAB resize it on every iteration. Use functions like length and size
along with the colon operator to determine loop indices after pre-allocating space.
A B
tic tic
for ii = 1:2000 A = zeros(2000, 2000);
for jj = 1:2000 for ii = 1:size(A,1)
A(ii,jj) = ii + jj; for jj = 1:size(A,2)
end A(ii,jj) = ii + jj;
end end
toc end
toc
10
PRE-ALLOCATING SPACE TO VARIABLES
• Note that in the previous example, we pre-allocated space to matrix A rather than
letting MATLAB resize it on every iteration (computationally expensive).
• For very large loops, it is good practice to always pre-allocate space:
A B
tic tic
for ii = 1:2000 A = zeros(2000, 2000);
for jj = 1:2000 for ii = 1:size(A,1)
A(ii,jj) = ii + jj; for jj = 1:size(A,2)
end A(ii,jj) = ii + jj;
end end
toc end
toc
• Use functions like length and size along with the colon operator to determine
loop indices after pre-allocating space.
11
WHILE LOOPS
x = 2;
k = 0;
error = inf; >> x
errorThreshold = 1e-32; x =
while error > errorThreshold 3.141592653589793
x = x - sin(x)/cos(x);
error = abs(x - pi); >> k
k = k + 1; k =
end 6
• We see that it takes 6 iterations to achieve our desired precision using an initial
estimate of x = 2.
12
BREAK
13
SWITCH STATEMENTS
• In a switch statement, the input is matched against several different values and a
block of code is executed for the case where the match is correct:
x = 't';
switch x
case 2
disp('x is 2')
case -1
disp('x is -1')
case 't'
disp('x is the character t')
otherwise
disp('x is not 2, -1, or t')
end
x is the character t
14
TRY/CATCH STATEMENTS
• In this example, b only has 3 elements so an error occurs when the script
attempts to access the 4th and 5th element.
• By using try/catch, MATLAB no longer terminates the script at this error.
15
SCRIPTS AND FUNCTIONS
16
FUNCTIONS
• Functions are useful for automating frequently used tasks and subroutines.
e.g we can write a script to calculate the area of a triangle:
b = 5;
h = 3; a =
a = 0.5*(b.* h) 7.5000
• To perform this calculation again for a different triangle, we would have to modify
the values of b and h in the script and re-run it. Rather than doing this, we can
simply convert this task into a function [1].
function a = TriArea(b, h)
a = 0.5*(b.* h);
end
a1 = TriArea(1,5) a1 = 2.5000
a2 = TriArea(2,10) a2 = 10
17
FUNCTION FILES
• Functions must be defined in an independent file, that must be saved in the work folder
• MATLAB files can contain code for more than one function.
• The first function in the file (the main function) is visible to functions in other files, or
you can call it from the command line.
• Additional functions within the file are called local functions. Local functions are only
visible to other functions in the same file. They are equivalent to subroutines in other
programming languages, and are sometimes called subfunctions.
• Local functions can occur in any order, as long as the main function appears first. Each
function begins with its own function definition line.
18
FUNCTIONS
• Functions have their own independent workspaces and everything that occurs
inside is hidden from the main workspace.
• From the previous example, if my main workspace has a variable b already
defined, calling Triarea will not interfere with this variable even though we use a
variable also called b inside of it.
function a = TriArea(b, h)
% This function calculates
% the area of a triangle. >> help TriArea
% INPUTS: b - base, h - height This function calculates
% OUTPUTS: a – area the area of a triangle.
a = 0.5*(b.* h); INPUTS: b - base, h - height
end OUTPUTS: a - area
19
FUNCTIONS
b = 5;
h = 3; a =
a = 0.5*(b.* h) 7.5000
function a = TriArea(b, h)
a = 0.5*(b.* h);
end
a1 = Triarea(5,3) a1 = 7.5000
20
FUNCTIONS
b = 5;
h = 3; a =
a = 0.5*(b.* h) 7.5000
function a = TriArea(b, h)
a = 0.5*(b.* h);
end
a1 = TriArea(5,3) a1 = 7.5000
The first solution is faster as it does not involve seeking the file system for the function and
calling it (control overhead). Functions are useful for code readability and efficiency, but do
not speed up computation; on the contrary, they involve a little overhead
21
FUNCTION HANDLES
• Function handles provide a way to create anonymous functions, i.e., one line
expression functions that do not have to be defined in .m files.
• A function handle is a MATLAB data type and can therefore be passed into other
functions to be called indirectly.
22
CELL ARRAYS
• In a matrix, each element contains a single value and all elements in the matrix
must be of a single type, e.g. double, char, logical, etc.
• A cell array is a data structure with indexed containers (like the elements of a
matrix) called cells.
• Each cell can store any type of data and can vary in size.
• Cell arrays can be created using the same syntax as a matrix, except that curly
brackets {} are used instead of square brackets [].
• In this example, A is a 2-by-2 cell array containing different types of arrays with
different sizes.
23
CELL ARRAYS
•To retrieve the contents of a cell, use indexing with curly brackets.
>> C = A(1,:)
C =
[2x2 double] [27]
24
STRUCTURES
student =
25
STRUCTURES
• Records for additional students can be added by including an index after the name
of the structure:
student =
name
id
number
grade
26
CELL ARRAYS VS. STRUCTURES
27
MULTIDIMENSIONAL ARRAYS
• A normal 2D data structure, such as a matrix or cell array, has rows as the 1 st
dimension and columns as the 2nd.
• We may add a 3rd dimension, sometimes called a page, by adding another index.
[2]
28
MULTIDIMENSIONAL ARRAYS
>> A = [1 2; 3 4];
>> A(:,:,2) = [9 8; 7 6]
A(:,:,1) = A(:,:,2) =
1 2 9 8
3 4 7 6
• If we assign a scalar to a new page, MATLAB fills the entire dimension with that scalar:
>> A(:,:,3) = 5
29
MULTIDIMENSIONAL ARRAYS
• They can also be generated using MATLAB functions like randn and zeros, e.g.,
to create a 4x5x2 array of zeros: A = zeros(4,5,2).
• The repmat function can be used to replicate a matrix across multiple dimensions.
• For example, to copy a matrix A across 4 pages in the 3rd dimension:
>> A = [1 2; 3 4];
>> B = repmat(A, [1 1 4])
B(:,:,1) = B(:,:,2) =
1 2 1 2
3 4 3 4
B(:,:,3) = B(:,:,4) =
1 2 1 2
3 4 3 4
30
MULTIDIMENSIONAL ARRAYS
• Sets of matrices can be concatenated along any dimension using the cat function
C = cat(dim, A, B)
31
MULTIDIMENSIONAL ARRAYS
• Sets of matrices can be concatenated along any dimension using the cat function
C = cat(dim, A, B)
>> A1 = [0 2; 4 6];
>> A2 = [1 3; 5 9];
>> B = cat(3, A1, A2)
B(:,:,1) = B(:,:,2) =
0 2 1 3
4 6 5 9
>> C = cat(4, B, B)
C(:,:,1,1) = C(:,:,2,1) =
0 2 1 3
4 6 5 9
C(:,:,1,2) = C(:,:,2,2) =
0 2 1 3
4 6 5 9
32