MATLAB-ELEC 2103

ELEC 2103
Simulation and Numerical Methods in
Engineering
Dr Mahyar Shirvanimoghaddam
[email protected]
School of Electrical and Information Engineering
The University of Sydney, Australia
Lecture 2 — Programming in MATLAB
COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969
WARNING
This material has been reproduced and communicated to you
by or on behalf of the University of Sydney pursuant to Part
VB of the Copyright Act 1968 (the Act).
The material in this communication may be subject to
copyright under the Act. Any further reproduction or
communication of this material by you may be the subject of
copyright protection under the Act. Do not remove this notice.
Lecture outline
Programming in MATLAB:
I Structured programming
I Scripts and m-files (Moore Ch 2.4.)
I Functions and sub-functions (Moore Ch 6.)
I Boolean operators, flow control using if, elseif, else and
switch, case (Moore Ch 8)
I Loops using for, while, break, return… (Moore Ch 9)
I Application: Taylor series approximation
I Structured arrays struct and cell arrays cell (Moore Ch 11)
I C, Java, Python, MS Excel, etc.
Structured programming
I Any program can be created by breaking large programs into
smaller modules and imposing control structures on their
interaction.
I Typically implemented using a top-down approach, where
complex programming blocks are broken down into smaller
blocks: divide and conquer.
I Moreover, algorithms (formally defined) have control
structures that are comprised of only three categories of
operations:
I Sequential operations,
I Conditional operations, and
I Iterative operations (loops).
I Each of an algorithm’s modules has a single entry point and a
single exit point.
Structured programming
MATLAB is designed to encourage structured programming
through the use of m-files, which contain individual modules.
I Make use of variables that are kept local to each block:
MATLAB functions have restricted variable scope.
I Minimise the exchange of information between blocks:
MATLAB functions encourage the use of weakly coupled
modules.
I The use of global variables is discouraged.
I File structure can be exploited to organise code and reuse
modules at different point in the program.
Scripts (Moore, Ch 2.4)
I Typing in each command repeatedly is inefficient and
error-prone.
I A better option is to save these commands in a file.
I Scripts contain a list of operations to execute.
I Open the MATLAB editor by typing edit into the command
window, or choosing New-Script from the menu.
I MATLAB recognises files with extension ’.m’, called m-files.
% script1.m
% Plot two sinusoids
t = linspace(0,10,11);
v1 = sin(t);
v2 = cos((t/2 pi));
plot(t,v1)
hold on
plot(t,v2)
% script2.m
% Plot a sinusoid plus …
noise
t = linspace(0,10,11);
v1 = sin(t);
% add white noise
figure(2)
plot(t,v2)
hold on
plot(t,v1)
Scripts (Moore, Ch 2.4)
I Typing in each command repeatedly is inefficient and
error-prone.
I A better option is to save these commands in a file.
I Scripts contain a list of operations to execute.
I Open the MATLAB editor by typing edit into the command
window, or choosing New-Script from the menu.
I MATLAB recognises files with extension ’.m’, called m-files.
% script1.m
% Plot two sinusoids
t = linspace(0,10,11);
v1 = sin(t);
v2 = cos((t/2 pi));
plot(t,v1)
hold on
plot(t,v2)
% script2.m
% Plot a sinusoid plus …
noise
t = linspace(0,10,11);
v1 = sin(t);
v2 = v1 + randn(size(v1));
figure(2)
plot(t,v2)
hold on
plot(t,v1)
The editor window and output
Functions (Moore Ch 6)
I Even more powerful are functions (often called ’methods’ in
other languages), which take arguments and return values.
I Functions start with the function keyword.
I Both scripts and functions are saved as m-files.
I They differ in the way they handle access to variables:
Variables defined within functions and not explicitly returned
are destroyed once the function is executed – i.e. limited scope.
Functions vs scripts
function v = …
fxn1(a,omega, ,T)
% Generate a sinusoid
t = linspace(0,T,T/10+1);
v = a*sin(omega*t+ );
% script3.m
% Plot two sinusoids
v = fxn1(2,1/4,0,10);
figure(3)
plot(v)
hold on
plot(fxn1(1,1,pi/2,10))
Where is variable t
Where do these files live
Anonymous functions (Moore Ch 6.3)
I Functions can be defined in scripts – these are anonymous
functions.
I Anonymous functions are stored in the workspace, much like a
variable.
I Use the @ symbol to tell MATLAB that you are defining a
function.
I LHS assignemnt is a function handle used to evaluate the
function.
cos50 = @(t) cos(2*pi*50*t)
x = 0:0.001:1 ;
figure(4)
plot(x,cos50(x))
Function functions (Moore Ch 6.4)
I Function functions take are functions that take functions as
arguments.
I Not as confusing as they first seem!
figure(4)
fplot(cos50,[0,0.015])
fzero(cos50,0.006)
Sub-functions (Moore Ch 6.5)
I Sub-function are called by a function within the same m-file.
I Like variables defined within a function, they also have
restricted scope – only accessible within the primary function.
function [] = plot50hz(startT,endT, )
% Plot sinusoids at 50hz with phase difference
x = startT:0.001:endT;
plot(x,cos50(x, ))
end % Need to explicitly end main fxn using subfxns
%% subfunctions
function y = cos50(t, )
y = cos(2*pi*50*t+ ) % Assume 50hz frequency
end
Code documentation
When building a program, it is imperative that you document
modules’ functionality as you write it or even better, before you
begin coding.
MATLAB has a few handy features to support this:
I In MATLAB, the first contiguous comment block after a
function keyword call is automatically interpreted as
function documentation.
I The function precis on first line is displayed in the Current
Folder Window under the function file name.
I The full comment block is displayed when you call
help.
Code commenting
Similarly, each step of a module can be commented, to explain the
operations being undertaken.
I Not every line needs to be commented, but it is good practise
to explain every logical step.
I Write your comments as you go, or even better, before you
begin coding.
Quiz time!
I Week 2 Quiz is available via MATLAB Grader.
I Please make sure to register into the MATLAB Grader course
created for this un

💡 Buy the answer for only $12 Get it now →

it. You have already received the invitation
email.
Boolean logic and relational operators
I MATLAB comes armed with many relational operators, so
Boolean logic can be easily incorporated.
I Relations >, ≥, ==, ≤ and < have the usual meaning. I All of these operator apply element-wise on vectors and matrices. I Additional operators for arrays include any and all I String equivalence is tested with strcmp (same as C). I Compound expressions use & (AND) and — (OR). I Output is a Boolean variable ∈ {0, 1} — not a double. I However, when applying algebraic operations to Booleans, MATLAB automatically recasts them as doubles. Conditional operations – if blocks The syntax for if blocks is: if expr1 statements1 elseif expr2 statements2 else statements3 end I expr is a relational test (like on the previous slide). I If expr1 is true, statements1 is executed. I If expr1 is false, expr2 is tested. I Any number of elseif tests can be included. I else is optional, but can only occur once at the end of the block. Iterative operations – for loops The syntax of the for loop is: for = expr statements end I The columns of expr are stored one at a time in the and then the statementsare executed. I Commonly, expr is a row vector and variable is scalar. I E.g. variable is n = 1:10 NOTE: Don’t use these to iterate over vectors and arrays when an equivalent algebraic operation is available – loops are much slower than vectorised operations in MATLAB. Iterative operations – while loops The syntax of the while loop is: while expr statements end I For the while loop to complete, statements must change a value in expr I These loops are best used when you don’t know how many iterations a process will take to complete. Verification and unit testing It is essential that you verify that your code does what is intended. I Unit testing is a method for testing if code is fit for use. I Unit test should be carried out in isolation of the rest of the program’s modules. I A simple approach is to make use of mock cases, which you can independently test by hand or otherwise know the solution to (e.g. by inputing extreme values). I For a more complicated function, a useful method is to build a test harness, which explores the behaviour of a module in a systematic and predictable way. More flow control: break, return, continue and switch, cases blocks I break, return, continue are used to interrupt the normal flow of for and while loops. I switch, cases blocks are used for complicated conditional code execution, such as using numerical and string identifiers. I You will see these in the labs. Debugging MATLAB is very good at accepting poorly specified code. This is why unit testing is vital — identify problems before they disappear from your view. I Use breakpoints to check your code step by step. I Print variables to the screen to check the computational trace. I Make use of its full range of visualisation features. I Rely on your engineering judgement to ascertain if your code is doing what you want. Always remember, the computer doesn’t care, so there is no use getting angry at it! Steps to developing large programs 1. State the problem concisely. 2. Specify the data to be used by the program: this is the ”input”. 3. Specify the data generated by the program: this is the ”output”. 4. By hand, work through the steps used to calculate the output given the input. 5. Break the program into modules, where each executes an important step, or related set of operations, in the algorithm. 6. Repeat steps 2 and 3 for each module. 7. Document the functionality of each module in the preamble of a corresponding m-file. 8. Code the details of each module, commenting as you write. 9. Independently verify each module (i.e. build unit testing scripts). 10. Verify the operation of the entire program. Quiz time! Taylor series approximation Series expansions are used to calculate the value of many trigonometric functions. For example, the value of cos(x) near 0 can be expressed as a Maclaurin series: cos(x) = x0 0! x 2 2! + x4 4! · · · = ∞∑ n=0 ( 1)n (2n)! x2n In practice, these functions’ values are approximated by truncating the corresponding series at an appropriate level of accuracy. Please go to MATLAB Grader to answer the Quiz question. Cell arrays: cell (Moore Ch 11.4) Cell arrays can store different types of data in the same container: A = 'Archie Chapman' ; B = 1:5; C = B'*B; % Curly braces construct cell arrays, or cell(r,c) myCellarray = {A, B, C} myCellarray = ’Archie Chapman’ [1x5 double] [5x5 double] Cell arrays: different ways to access contents myCellarray(2) % Returns contents as a cell array ans = [1x5 double] myCellarray{2} % Returns contents as their type ans = 1 2 3 4 5 myCellarray{3}(4,3) % Round and curly braces ans = 12 Applying functions to cell array contents We often use cell arrays to store several data sets. There are two main reasons for this: I the datasets have different dimensions, or I it is quicker to access cell array contents for large set of data. Sometimes, we may wish to apply the same function to all data entries in the cell array, e.g. to compute the max of several data sets. For this, use cellfun C = {1:10, [2; 4; 6], []}; maximums = cellfun(@max, C) ans = 10 6 NaN Q: What do we call a function like cellfun Structure arrays: struct (Moore Ch 11.5) Structure arrays can store different types of data in fields: myStruct.name = A ; % Dot notation contructs structures myStruct.vec = B ; myStruct.mat = C ; myStruct myStruct = name: ’Archie Chapman’ myStruct = vec: [1 2 3 4 5] myStruct = mat: [5x5 double] Can also use syntax: struc('field1',value1,...) to add more entries to the fields: myStruct(2) = struct('name','Joe Bloggs', ... 'vec', 1:4, ... 'mat', [1,2;3,4] ) Advanced MATLAB programming tips For your information only — The following functionality is available through MATLAB: I Object-oriented programming, classes and objects. I Calling external functions, such as C, Java and Python. I MATLAB API for calling MATLAB from other languages. I Communicate with web services, e.g. scrape data and download files. I Source control integration, e.g. git. I And so on...

💡 Buy the answer for only $12 Get it now →