02-Scripts Flow Control and Data Structures
02-Scripts Flow Control and Data Structures
1
addpath
Outline
• Script
• Folder
• Search path
• Ellipsis
• Conditional statement
• For loops
• While loops
• Continue, Break
• Switch
• Try, Catch
• Function, function handle, anonymous function
• Structure
• Cell
• Multidimensional arrays
SCRIPTS
• For larger, more complicated tasks, we need to write all commands in a file.
• A Matlab script file can be executed from the Matlab command window. All the commands
within it will be performed sequentially, just like any C/C++ program.
• Folders (or Directories): We can setup folders to keep scripts and functions organized.
• To run a script, the script should be in the current folder in MATLAB, or its folder should be
added to Matlab’s search path.
• clear all: To remove previous variables from the workspace, you may wish to
place the command clear all at the beginning of your script.
• close all: To close previously opened figures. Usually used at the beginning of a
script too.
• Surpress unwanted output: use semicolon ; at the end of commands in scripts.
• 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 finishing and regain control, press Ctrl+C.
>> lec2
C =
30 24 18
84 69 54
138 114 90
Current Folder
>> cd e:\courses\2024-1-ensc180\
>> cd
E:\courses\2024-1-ensc180
Search Path
• From the Home > Set Path menu to see the current search path:
• or use the path command to display
Search Path
• The order of folders on the search path is important. When files with the same name
appear in multiple folders on the search path, MATLAB uses the folder nearest to the top
of the search path.
• addpath FOLDERNAME: Prepends the specified folder to the current search path.
• After this, the new folder is added at the beginning of the search path (first priority)
https://www.mathworks.com/help/matlab/matlab_env/what-is-the-matlab-search-path.html
• Continue MATLAB command by placing an ellipsis (three dots) at the end of the
line to be continued:
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:
• 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.
• Indent Code: Make functions and statements such as loops easier to read.
• Can be done using tabs or spaces.
• In many cases, Matlab automatically inserts the indent.
• A for loop uses a counter to repeatedly execute the block of code within it.
• Syntax:
for index = values
statements
end
• Loops can be nested:
• The values part can take three forms:
A = zeros(2, 2);
• 1) index = initVal : endVal for r = 1 : 2
for c = 1 : 2
A(r, c) = r + c;
A = zeros(1, 3);
end
for x = 1 : 3 end
A(x) = x^2;
end
>> A
A =
>> A
2 3
A =
3 4
1 4 9
• A is initialized as an empty matrix and its size is updated dynamically during each
iteration of the loop
• This approach is very slow. Try NOT to use it.
jj =
1
5
A = zeros(1, 3); A =
B = [1 2 3; ... 6 0 0
5 6 7]; jj =
k = 1; 2
for jj = B 6
A(k) = jj(1) + jj(2); A =
k = k + 1; 6 8 0
jj jj =
A 3
end 7
A =
6 8 10
>>
• The special name end can be used inside an array to indicate the last index of the array
>> x = 1 : 10;
6 7 8 9 10
x =
1 4 3 8 5 12 7 16 9 20
• Continue: skips the current iteration in the for or while loop and moves to the next
iteration.
x = rand(1, 10);
s = 0;
for k = 1 : 10
if x(k) < 0.5 >> x =
continue; 0.6787 0.7577 0.7431 0.3922 0.6555
end 0.1712 0.7060 0.0318 0.2769 0.0462
>> s
s = s + x(k); s =
end 3.5411
• The command break terminates the execution of the entire for or while loops earlier.
• Control passes to the statement after the end of that loop.
>> x =
0.6787 0.7577 0.7431 0.3922 0.6555
0.1712 0.7060 0.0318 0.2769 0.0462
>> s
s =
2.1796
• In a switch statement, the input is matched against several different values and a
different block of code is executed for each case:
• Syntax:
x is the character t
• Function syntax:
• function [y1, ..., yN] = myfun(x1, ..., xM)
• 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
a1 = triarea(1, 5) a1 = 2.5000
a2 = triarea(2, 10) a2 = 10
• 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. They are only visible to
other functions in the same file.
• Local functions can occur in any order, as long as the main function appears first.
Each function begins with its own function definition line.
• To avoid mistake, it is a good practice for the file name and the first function to have
the same name.
• Functions have their own independent workspaces and everything that occurs
inside is hidden from the main workspace.
• From the previous example, if our 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 hep info: Lines after the function name beginning with % will serve as the
help text. Will be displayed by the help command.
function a = triarea(b, h)
% Calculate area of a triangle.
>> help triarea
% a = triarea(b, h):
Calculate area of a triangle.
% INPUTS: b: base, h: height
a = triarea(b, h):
% OUTPUTS: a: area
INPUTS: b: base, h: height
a = 0.5 * (b .* h);
OUTPUTS: a: area
end
• We can call a function using a handle the same way we call the function directly.
function y = computeSquare(x) f = @computeSquare;
y = x.^2; a = 4;
end b = f(a)
b =
16
• If the function does not require any inputs, then we can call the function with empty
parentheses, such as
>> h = @ones;
>> a = h()
a =
1
• Note: Without the parentheses, a = h assigns the handle h itself to a new handle a (not
the returned value of the function pointed by the handle h)
>> a = h
a =
function_handle with value:
@ones
• Syntax:
• h = @(arglist) anonymous_function_expression
• h: a function handle. The function is called by using the handle.
• arglist: comma-separated list of input arguments to the anonymous function
• In an array, each element contains a single value and all elements in the array have the
same type, e.g. double, char, logical etc.
• A structure is composed of data containers called fields.
• Different fields can have different types.
• Syntax: structName.fieldname student.name = 'John Doe';
student.id = '[email protected]';
• Example: store student grades in a structure: student.number = 301073268;
student.grade = [100, 75, 73; ...
95, 91, 85.5; ...
100, 98, 72];
>> student
student =
struct with fields:
>>student
student =
name
id
number
grade
• Different cells can store different types of data and can vary in size, similar to structure.
• Cell arrays are created similar to matrix, using curly brackets {} instead of square brackets
[].
• In this example, A is a 2-by-2 cell array containing different types of arrays with different
sizes.
•To retrieve the contents of a cell, use indexing with curly brackets, {}
instead of using the dot and field name as in structure.
>> A{1,1}
ans =
1 2
3 4
>> A{1,:} >> A{2,:}
ans =
ans =
1 2 'Alice'
ans =
3 4 1×3 cell array
ans = {[1]} {[2]} {[3]}
27
•To retrieve a set of cells (return a cell array, not the content directly), use indexing
with round brackets ( ).
>> B = A(1, :)
()
>> A(1) B =
ans = 1×2 cell array
{2×2 double} {[27]}
1×1 cell array
{2×2 double}
Can access content of B using {},
as in the previous page:
>> A(1, :)
ans = >> B{1} % return a matrix
1×2 cell array ans =
{2×2 double} {[27]} 1 2
3 4
>> B{2}
ans =
27
• The containers of a cell array are referred to by their index, whereas the containers
of a structure are referred to by their names.
• A normal 2D data structure, such as a matrix or cell array, has rows as the 1st
dimension and columns as the 2nd.
• We may add a 3rd dimension, sometimes called a page, by adding another index.
• Additional indices can be added (dim1, dim2, dim3, ..., dimN) for
N-dimensional matrices.
>> A = zeros(2, 2, 3)
A(:,:,1) =
0 0
0 0
A(:,:,2) =
0 0
0 0
A(:,:,3) =
0 0
0 0 A NASA Hubble Space Telescope image
• Debugging Tools:
Please read/watch the following links to learn how to use the Matlab debug tools to
debug your code.
https://www.mathworks.com/help/matlab/matlab_prog/debugging-process-and-
features.html
https://www.youtube.com/watch?v=VEqevFAZIQo
Some basic good practices to ensure readability should be used in your codes (such
as author information, help information at the beginning of each file, necessary
comments in the codes, and indentation). Note that Readability of Code can take up to
10% of the grading in this course.
Please read the following Matlab programming style recommendations, which is not
mandatory but recommended for this course, although you do not have to follow all
recommendations in the document.
https://sites.google.com/site/matlabstyleguidelines/