0% found this document useful (0 votes)
5 views36 pages

02-Scripts Flow Control and Data Structures

Lecture 2 of ENSC 180 covers essential MATLAB programming concepts including scripts, flow control, and data structures. It explains the advantages of using scripts over command lines, the use of loops and conditional statements, and introduces functions for automating tasks. Additionally, it discusses the importance of managing the current folder and search path in MATLAB for effective coding.

Uploaded by

David Cross
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views36 pages

02-Scripts Flow Control and Data Structures

Lecture 2 of ENSC 180 covers essential MATLAB programming concepts including scripts, flow control, and data structures. It explains the advantages of using scripts over command lines, the use of loops and conditional statements, and introduces functions for automating tasks. Additionally, it discusses the importance of managing the current folder and search path in MATLAB for effective coding.

Uploaded by

David Cross
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

ENSC 180 – Introduction to Engineering Analysis

Lecture 2: Scripts, Flow Control,


and Data Structures

Prof. Jie Liang


[email protected]
School of Engineering Science
Simon Fraser University

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

ENSC 180 – Introduction to Engineering Analysis Tools 2


addpath

SCRIPTS

• In Lecture 1, we only use MATLAB terminal to enter commands.

• For larger, more complicated tasks, we need to write all commands in a file.

• Matlab Script: A file with a .m extension, containing a series of MATLAB commands.

• Any MATLAB command can be placed in a script.

• 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.

ENSC 180 – Introduction to Engineering Analysis Tools 3


SCRIPTS

• Several advantages to using scripts over the command line include:


• User can automate tasks.
• Uses smart indentation to help read and write code more comfortably.
• Adds comments: starting with %
• Allows the use of breakpoints for debugging.
• Allows the use of the MATLAB profiler and tic/toc time functions to analyze
program performance.
• User can run individual pieces of code by highlighting a piece and pressing F9 (in
addition to breakpoints, this makes debugging very convenient and easy).

• 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.

ENSC 180 – Introduction to Engineering Analysis Tools 4


SCRIPTS

• Sample script file: • Running the script:

>> lec2

C =

30 24 18
84 69 54
138 114 90

ENSC 180 – Introduction to Engineering Analysis Tools 5


addpath

Current Folder

• Current folder can be changed from the Matlab UI, or


use the cd command

• cd command: Change directory command.

>> cd e:\courses\2024-1-ensc180\

• cd by itself prints the current directory, similar to pwd.

>> cd
E:\courses\2024-1-ensc180

• If folder name contains space, put it in quote:

>> cd e:\courses\’ensc 180’\

• pwd command: Print (display) current working directory.


>> pwd
ans =
'E:\courses\2024-1-ensc180'

ENSC 180 – Introduction to Engineering Analysis Tools 6


addpath

Search Path

• From the Home > Set Path menu to see the current search path:
• or use the path command to display

ENSC 180 – Introduction to Engineering Analysis Tools 7


addpath

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.

>> addpath e:\Jie\courses\2024-1-ensc180\

• 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

ENSC 180 – Introduction to Engineering Analysis Tools 8


Ellipsis: Line Continuation Operator

• 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:

mystring = ['Accelerating the pace of ' ...


'engineering and science’];

ENSC 180 – Introduction to Engineering Analysis Tools 9


CONDITIONAL STATEMENTS, and Indent Code

• 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.

ENSC 180 – Introduction to Engineering Analysis Tools 10


FOR LOOPS

• 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

ENSC 180 – Introduction to Engineering Analysis Tools 11


FOR LOOPS

• 2) index = initVal : step : endVal


• step can be negative.
A =
2
A = []; A =
for ii = 2 : 2 : 8 2 4
A = [A ii] A =
end 2 4 6
A =
2 4 6 8

• In this case, the index ii is incremented by a step size of 2 until it reaches 8.

• 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.

• Can use character indices as well, e.g. ii = 'a’ : 'z’

ENSC 180 – Introduction to Engineering Analysis Tools 12


FOR LOOPS

•3) index = valueArray

 Each column of the array valueArray is assigned to index in an iteration.

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
>>

ENSC 180 – Introduction to Engineering Analysis Tools 13


Use end to indicate the last array index

• The special name end can be used inside an array to indicate the last index of the array

• Can be more convenient than the length( ) function.

>> x = 1 : 10;

>> x(6 : end)


ans = 1×5

6 7 8 9 10

>> x(2 : 2 : end) = 2 * x(2 : 2 : end)

x =
1 4 3 8 5 12 7 16 9 20

ENSC 180 – Introduction to Engineering Analysis Tools 14


PRE-ALLOCATING SPACE TO VARIABLES

• Note that in the previous example, we pre-allocate the size of matrix A.


• This is much faster than dynamically resizing the matrix size.

• Use tic and toc functions to measure time:

• tic: Start the stopwatch timer.


• toc: Return the elapsed time since the stopwatch was started by the call to the tic
function.
tic tic
for ii = 1 : 2000 A = zeros(2000, 2000);
for jj = 1 : 2000 for ii = 1 : 2000
A(ii, jj) = ii + jj; for jj = 1 : 2000
end A(ii, jj) = ii + jj;
end end
toc end
toc

Elapsed time is 1.540708 seconds. Elapsed time is 0.021786 seconds.

(The speed depends on your computer)

ENSC 180 – Introduction to Engineering Analysis Tools 15


WHILE LOOPS

• A while loop repeats for as long as the expression remains true.


• Syntax:
while expression
statements
end
• Useful when we do not know the exact number of iterations in advance

• Example: Use a while loop to calculate factorial(n).


• n! = 1 x 2 x … x n.
n = 5;
f = n;
while n > 1
n = n - 1;
f = f * n;
end
disp(['n! = ' num2str(f)])

disp: Display value of variable.


n! = 120 num2str: Convert numbers to character array.

ENSC 180 – Introduction to Engineering Analysis Tools 16


Continue: Skip to the next loop iteration

• Continue: skips the current iteration in the for or while loop and moves to the next
iteration.

% Calculate sum of entries that are >= 0.5

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

How to do this in one line without using the loop?

sum(x(x >= 0.5))

ENSC 180 – Introduction to Engineering Analysis Tools 17


BREAK: Exit Loop Earlier

• 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.

• Can be useful in iterative methods where convergence is not guaranteed.

% Calculate running sum of a vector until an entry < 0.5


x = rand(1, 10);
s = 0;
for k = 1 : 10
if x(k) < 0.5
break;
end
s = s + x(k);
end

>> 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

ENSC 180 – Introduction to Engineering Analysis Tools 18


SWITCH STATEMENTS

• In a switch statement, the input is matched against several different values and a
different block of code is executed for each case:

• Syntax:

switch expression1 x = 't';


case expression2 switch x
statements case 2
case expression3 disp('x is 2')
statements case -1
... disp('x is -1')
otherwise case 't'
statements disp('x is the character t')
end otherwise
disp('x is not 2, -1, or t')
end

x is the character t

ENSC 180 – Introduction to Engineering Analysis Tools 19


TRY/CATCH STATEMENTS

• Attempts to evaluate an expression; if an error occurs, the statements inside the


catch block are executed.
• After the error is “caught”, the script continues after the end of the try statement.
a = 1 : 5; c =
b = 1 : 3; 2
for ii = 1:length(a)
try c =
c(ii) = a(ii) + b(ii) 2 4
catch
disp('b is too small') c =
end 2 4 6
end
b is too small
b is too small
• b only has 3 elements  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.

ENSC 180 – Introduction to Engineering Analysis Tools 20


SCRIPTS AND FUNCTIONS

There are two options in order to describe a sequence of MATLAB


commands in a file:

• Scripts do not accept input arguments or return output arguments. They


operate on data in the workspace. When you invoke a script, MATLAB
simply executes the commands found in the file.

• Functions can accept input arguments and return output arguments.


• Internal variables are strictly local to the function.
• When we call a function, MATLAB only executes the portion of the
function file related to the function and eventual sub-functions

• Function syntax:
• function [y1, ..., yN] = myfun(x1, ..., xM)

ENSC 180 – Introduction to Engineering Analysis Tools 21


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

• Note: element-wise product is used to allow matrix inputs.


• 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 define this task as a function:
function a = triarea(b, h)
a = 0.5 * (b .* h);
end

• The calculation can now be performed repeatedly without any modifications:

a1 = triarea(1, 5) a1 = 2.5000
a2 = triarea(2, 10) a2 = 10

ENSC 180 – Introduction to Engineering Analysis Tools 22


FUNCTION FILES

• Functions must be defined in an independent file.

• 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.

• It is also better to have only one function in each file.

ENSC 180 – Introduction to Engineering Analysis Tools 23


FUNCTIONS

• 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.

>> b = 99; >> b


>> a3 = triarea(2,4); b =
99

• 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

ENSC 180 – Introduction to Engineering Analysis Tools 24


FUNCTION HANDLES

• A function handle is a special data type (function_handle) that stores an


association (or address) to a function.
• Similar to pointer in C/C++.
• Since handle is a data type, we can store multiple function handles in an array,
and save and load them.
• We can pass a function handle as a variable to another function.
• Function handles can be created for both named and anonymous functions.

• Creating Function Handles: Precede the function name with an @ sign.


f = @myfunction;

• 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

ENSC 180 – Introduction to Engineering Analysis Tools 25


FUNCTION HANDLES

• 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

• Function handles are variables that can be passed to other functions.


>> f = @computeSquare;
>> q = integral(f, 0, 1);
q =
0.3333

ENSC 180 – Introduction to Engineering Analysis Tools 26


Anonymous Functions
• @ is usually used to define anonymous function.

• An anonymous function is a function that is NOT stored in a program file, but is


associated with a function handle.
• Note:
• Anonymous functions can only contain one-line expression.
• Anonymous functions can accept multiple inputs but only return one output.
• Useful for simple commands that need to be called multiple times within a file without
creating a separate file.

• 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

>> sqr = @(n) n.^2;


>> x = sqr(3)
x =
https://www.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html
9
ENSC 180 – Introduction to Engineering Analysis Tools 27
STRUCTURES

• 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:

name: 'John Doe'


id: '[email protected]'
number: 301073268
grade: [3×3 double]
Source www.mathworks.com

ENSC 180 – Introduction to Engineering Analysis Tools 28


STRUCTURE ARRAYS

• Records for additional students can be added by creating structure arrays.

• The index of structure array is specified by round brackets ( ), similar to regular


array index.
()
student(2).name = 'Ann Lane';
student(2).id = ‘[email protected]';
student(2).number = 301078853;
student(2).grade = [95, 95, 100; 100, 82, 85; 90, 97, 100];

>>student

student =

1x2 struct array


with fields:

name
id
number
grade

ENSC 180 – Introduction to Engineering Analysis Tools 29


CELL ARRAYS

• A cell array is a data structure with indexed elements called cells.

• 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
[].

>> A = {[1 2; 3 4], 27; 'Alice', {1, 2, 3}}


A = {}
2×2 cell array

[2x2 double] [ 27]


'Alice' {1x3 cell}

• In this example, A is a 2-by-2 cell array containing different types of arrays with different
sizes.

ENSC 180 – Introduction to Engineering Analysis Tools 30


CELL ARRAYS

•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 2; 3 4], 27; 'Alice', {1, 2, 3}}

>> 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

ENSC 180 – Introduction to Engineering Analysis Tools 31


CELL ARRAYS

•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

>> B{1}(2,1) % access matrix element


ans =
3

ENSC 180 – Introduction to Engineering Analysis Tools 32


CELL ARRAYS VS. STRUCTURES

• Choosing between cell arrays and structures is mostly a matter of personal


preference and code clarity.

• The containers of a cell array are referred to by their index, whereas the containers
of a structure are referred to by their names.

• We can implement the previous example using a cell array:

student_data(1,:) = {'John Doe', '[email protected]', 301073268, ...


[100, 75, 73; 95, 91, 85.5; 100, 98, 72]};
student_data(2,:) = {'Ann Lane', '[email protected]', 301078853, ...
[95, 100, 90; 95, 82, 97; 100, 85, 100]};
>> student_data
student_data =
2×4 cell array
{'John Doe'} {'[email protected]'} {[301073268]} {3×3 double}
{'Ann Lane'} {'[email protected]'} {[301078853]} {3×3 double}
>> student_data{2,3}
ans = Structure is easier to read in this case.
301078853

ENSC 180 – Introduction to Engineering Analysis Tools 33


MULTIDIMENSIONAL ARRAYS

• 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.

• A(i, j, k): The (i, j, k)-th entry of the array.

• Additional indices can be added (dim1, dim2, dim3, ..., dimN) for
N-dimensional matrices.

ENSC 180 – Introduction to Engineering Analysis Tools 34


MULTIDIMENSIONAL ARRAYS

• Example: a RGB color image can be represented as a 3D array.


>> A = imread('ngc6543a.jpg'); % read a built-in image in Matlab
>> size(A)
ans =
650 600 3
>> image(A)
• There are various ways of creating
multidimensional arrays.
• They can be generated using MATLAB
functions like randn, ones, zeros.

>> 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

ENSC 180 – Introduction to Engineering Analysis Tools 35


Matlab Debugging tools

• 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

• Matlab Programming Style Recommendations

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/

ENSC 180 – Introduction to Engineering Analysis Tools 36

You might also like