Week 4 Course Notes
Week 4 Course Notes
.1.
4 INPUTAND OUTPUTIN MATLAB......................................................................................................................4
4.2. INPUTINTO MA TLAB....................................................................................................................................5
4.2.1. The input()function...................................................................................................................5
4.2.2. ImportingdatafilesintoMATLAB....................................................................................................5
4.3. OU TPUTFROM MA TLAB................................................................................................................................8
4.3.1. Overviewof fprintffunction....................................................................................................8
4.3.2. Printingvariables............................................................................................................................8
4.3.3. Usingspecialcharacters..................................................................................................................9
4.3.4. Specifyingwidthandprecision......................................................................................................10
4.3.5. Printingmultiplevariables............................................................................................................11
4.3.6. fprintfwithmatrices.............................................................................................................11
4.3.7. Using fprintftowritetoafile.................................................................................................12
4.3.8. Overviewof sprintffunction...................................................................................................12
4.4. RE LATIONALAND LOGICAL OPERATORS............................................................................................................14
4.4.1. Logicals..........................................................................................................................................14
4.4.2. RelationalOperators.....................................................................................................................14
4.4.3. Usinglogicalsformorethanonecondition...................................................................................16
4.5. US INGLOGICALSTOFILTERDATA....................................................................................................................17
Programming practices
.6.
4 PLANNINGYOURCODE:FLOWCHARTSANDALGORITHMS.........................................................................................2
4.7. CODINGDOCUMENTATION:COMMENTINGYOURCODE.............................................................................................3
4.8. RE USABLECODEANDFUNCTIONS.....................................................................................................................6
4.9. FUNCTIONS...............................................................................................................................................8
4.9.1. Whentouseafunction...................................................................................................................8
4.9.2. Creatingandusingfunctions...........................................................................................................9
4.9.3. CallingFunctions...........................................................................................................................10
4.9.4. FunctionDocumentation...............................................................................................................10
4.9.5. FunctionNames............................................................................................................................11
4.9.6. Functionswithmultipleinputsandoutputs..................................................................................11
4.9.7. User-definedfunctions:checklist...................................................................................................12
4.9.8. Anonymousfunctions....................................................................................................................13
1
ENG1014Engineering Numerical AnalysisCourse Notes
Video Links
ideo Link 4.1: Importing data into MATLAB (14 minutes)
V 6
Video Link 4.2: Working with string variables (37 mins). 13
Video Link 4.3: Outputting into Files with MATLAB (9 mins) 13
Video Link 4.4: Outputting strings with MATLAB (12 mins) 13
Video Link 4.5: Relational and logical operators and filtering using logical operators (19 mins)
18
Video Link 4.6: More examples of filtering using logicals 18
Video Link 4.7: Good programming practice in Matlab. (5 mins) 9
Video Link 4.8: Further explanations and examples of how to create and use custom
functions in Matlab. (17 mins) 15
2
ENG1014Engineering Numerical AnalysisCourse Notes
Programming methods
ere we will introduce you to several useful methods that can be used to perform useful
H
tasks. We don’t expect you to be able to use every possible variation of these methods
straight away – you might need to refer back to these notes in later weeks
T o analyse kinetics and kinematics in real-world systems, we rely on sensors: these might
commonly include force sensors, position sensors (e.g. GPS), velocity sensors and
accelerometers. More generally, many engineering systems containssensorsthatgenerate
datafilesthatwewouldliketoanalyse.Thesefilescontainlargequantitiesofdata,generally
organised into rows and columns, that are ready-made for analysis by programs such as
those you can write in Matlab.
Figure 4.1: Phone accelerometer data is readily analysed using basic computing techniques.
Effective usage of input and output is an important part of good coding practices:
● W henever you print something to the command window, your printing should
include all of the details needed to understand your answer, for example the
meaning of the variable, and any units of measurement: compare reading the
statement“x=5”(whatdoesitactuallymean?)to“ Theball’sfinaldisplacementis5
cm”.
● Graphs and tables need to be labelled; using sprintf()isagoodwaytocreate
effective labels that can be generated automatically by the script, rather than
needing to be hard-coded.
● Exporting your data in a standard format thatisreadablebyanotherprogram(e.g.
.txt or .csv) is also important in many situations.
3
ENG1014Engineering Numerical AnalysisCourse Notes
● B eingabletoimportdataintoyourscriptwhileitrunsavoidshavingto“hard-code”
that data into your script. This means that someone can reuse yourscriptwithout
needing to edit it, which avoids accidental changes being made. It also allows
non-programmers to use your work.
T he input function is an alternative way to enter data into Matlab, albeit a much more
manual process. It is typically used to create programs that allow users to input small
amounts of data while the program is running. For example:
hen the command above is used inside a script, the program will print the request and
W
height
then wait for the user to input the answer. This will then be saved to the variable
for use later in the script.
s a part of good practice, you should always include an instruction to the person who runs
A
your code, telling them what they should do, as the argument for the input()function.
Y oucananalysedatafromanysupportedfileformatsinMATLABbyimportingthedataand
definingvariablestosavesectionsofthedata.Thesearethenusedtoperformanyrequired
MATLAB operation. There are two main methods used for importing data into Matlab.
T hesecondmethodusesthe importdatafunctiontoimportdata.Itisveryeasytouse,
and will be commonly used throughout ENG1014. This method is also demonstrated in
Video Link 4.1. Data files in several formats including TXT, CSV, XLS, and XLSX can be
imported into MATLAB. Use the importdata function to load files containing a lot of data
with the following syntax:
all_data
= importdata('filename').
T he importdata command loads in all the data in the file, but it cannot write to files. It
imports the data in as a structure. A structure can be comprised of data, text data and
column headers. Data from structures can be accessed via:
content = <structure_name>.<content_type>
4
ENG1014Engineering Numerical AnalysisCourse Notes
ideo Link 4.1 shows worked examples of how to import data files into Matlab using both of
V
the above methods.
F or Example:Assume you have a file named [Link]that has height, time and velocity
data in the three columns and a number of rows of the data.
You can use the importdata to import the file and define as ‘X’.
ften it is very useful to separate data into variables after you have imported it, which can
O
be done as follows:
5
ENG1014Engineering Numerical AnalysisCourse Notes
6
ENG1014Engineering Numerical AnalysisCourse Notes
fprintffunction
4.3.1. Overview of
T hename fprintfisshortfor“formattedprintfunction”.Itallowsyoutoprintyourdata
toafileinTXTorsimilarfiletypes,thatcanbeimportedintoothercomputerprograms.The
functionallowsyouto"format"howthedataisprintedinsuchamannerastomakeiteasy
to read.
T hefprintffunctionalsoallowsyouto"write"informationtothescreenfortheusertoview
– in fact this is now its most common use. Displaying informationonthescreenbecomes
very important when user interaction is involved. The following sub-sections will discuss
different important features of the fprintf function.
S yntax:
fprintf('format', var1, var2, var3, …)
%var1,var2
etc optional
simple example:
A
fprintf('Hello World');
%prints “Hello World” to the
screen.
S ymbol escription
D
%d Prints a “decimal” number (i.e in the base-10 number system). If the
numberisaninteger,itwilldisplayasaninteger,otherwiseitwilldisplay
decimal places.
%f Prints a “floating point” number (i.e. a number with decimal places).
Decimal places are always shown.
T hesesymbolsareplaceholdersthatareincludedinthe 'format'partofthesyntax,and
instruct Matlab to insert data fromthevariablesthatarelistedlaterinthesyntax(
var1,
var2,…
). Placeholders are denoted with a percentage symbol (%) and are coupled with
specifiers. The variables for your placeholders followthelistofvariablesastheyappearin
the order written.
Note that when used in this way, the % is not the comment character.
7
ENG1014Engineering Numerical AnalysisCourse Notes
Example:
fprintfsample code to print one variable.When the code on the left is run,
F igure 4.2:
the output on the right is printed to the command window.
A more extensive list of formatting options can be found within theMatlab documentation.
8
ENG1014Engineering Numerical AnalysisCourse Notes
Examples:
ariables can also be printed with specified width and precision. Using a proper width
V
allocates number of spaces used for printing to ensure enough space between the words.
fprintf also allows you to control the number of decimal places of a printed variable.
%<width>.<precision><specifier>
Syntax:
9
ENG1014Engineering Numerical AnalysisCourse Notes
Try the following in MATLAB and see the width and decimal places it prints.
fprintf('%f\n', pi)
fprintf('%.2f\n', pi)
fprintf('%20.2f\n', pi)
fprintf('%20.2e\n', pi)
4.3.6.
fprintfwith matrices
printfworks with vectors/matrices and prints eachelement. For a vector, printing starts
f
with first element to last element. In 2D matrices, printing starts with each element in first
column, then to next column, and so forth.
10
ENG1014Engineering Numerical AnalysisCourse Notes
T he fprintf function can be used to print to a file. There are three important steps to this
process:Opening the file, printing the data, andthen closing the file.
'r'
pen file for reading.
O
Open or create new file for writing. Discard existing contents, if
'w'
any.
Open or create new file for writing. Append data to the end of the
'a'
file.
'r+'
Open file for reading and writing.
Open or create new file for reading and writing. Discard existing
'w+'
contents, if any.
Open or create new file for reading and writing. Append data to
'a+'
the end of the file.
E xample syntax:
filename = fopen("[Link]
", 'r')
2. U
se the filename variable as the first input in your call to fprintf(). For example:
fprintf(filename,'format', var1, var2, var3, …)
● part from including the file handle variable, this usage is identical to before.
A
● “ The screen” is the default file that is printed to, so it is used whenever another
file handle isn’t specified.
3. U fclose(filename)at the end of your script toclose the file and free up
se
memory
sprintffunction
4.3.8. Overview of
11
ENG1014Engineering Numerical AnalysisCourse Notes
T he sprintf()function works similarly to fprintf() , except that it prints to a new
“string” variable instead of a file. A string is a word, sentence or set of characters. The
syntax used with sprintf()is the same as fprintf() .
T he
sprintf()function is particularly useful for things like automatic plot titles, as is
demonstrated in Figure 4.6.
Figure 4.6: Example code for sprintf() used to print the plot title.
fprintfand
F urther details on the sprintffunctionswith example can be found in
Video Links 4.1, 4.2 and 4.3.
12
ENG1014Engineering Numerical AnalysisCourse Notes
13
ENG1014Engineering Numerical AnalysisCourse Notes
4.4.1. Logicals
L ogicals are a new type of variable that can only take two different values: TRUE or FALSE.
The logical function converts numeric values to logicals. Numerically,non-zero is TRUE
(logical 1), andzero is FALSE (logical 0),whichcan be seen from the example in Figure 4.7.
14
ENG1014Engineering Numerical AnalysisCourse Notes
These operators work on both scalar and vector variables, as seen in Figure 4.8.
elational operators can also compare values within matrices if the matrices are the same
R
size, as seen in Figure 4.9.
hile using relational operator '==', do not confuse with '='. The = operator assigns values,
W
and the == compares values. Figure 4.10 shows the differing results of "A = B" compared to
"A == B".
15
ENG1014Engineering Numerical AnalysisCourse Notes
E ach relational operator will compare exactly two variables. However, logicals can also be
used with more than one condition, via the use of logical operators. There are 3
fundamental logical operators: AND, OR and NOT. Their function is to combine two logicals
into a single, overall logical result. Logical operators are also often known as “Booleans” or
“Boolean operators”.
F or example, think of sorting out values between 20 and 30 from a 100 x 100 matrix. We can
use logicals to quickly sort out the desired values, as shown in Figure 18.
Figure 4.12: Example on using logicals for more than one condition.
E xtension:Other truth tables can be made by combiningthe three basic logical operators:
for examples, a NAND (NOT AND) relationship is made using ~(A&B), and gives a result of
16
ENG1014Engineering Numerical AnalysisCourse Notes
unless both of the inputs are TRUE. A XOR relationship (exclusive OR) is even more
1
advanced (and unlikely to be needed in ENG1014); it gives a result of 1 if either of the
inputs are TRUE, but not if they are both TRUE. This could be implemented as
(A|B)&(~(A&B)).
17
ENG1014Engineering Numerical AnalysisCourse Notes
L ogicals can be used to easily filter data according to whether the logical test is true. This is
done by using the logical matrix as an index. For example, you can sort out the positive
values from the speed vector and the corresponding time using logical indexing, as shown in
Figure 4.13.
F igure 4.13: Use of logicals as indices. In this case, we can filter both the speed and time
vectors to include only those times when speed > 0.
T his is a very useful technique, as it allows you to extract out sections of data to work with,
without actually changing (overwriting) the original data, which is generally not good
practice. Note that, as shown in Figure 4.13, the logical can also be used as an index on a
different matrix to the one which was used to create the logical.
18
ENG1014Engineering Numerical AnalysisCourse Notes
Video Link 4.5: Relational and logical operators and filtering using logical operators (19 mins)
F iltering using logicals can be a challenging concept at first, but is an important concept
that is highly useful in data analysis – data often contains noisy readings that need to be
excluded from the analysis.
19
ENG1014Engineering Numerical AnalysisCourse Notes
● P lanning the algorithm for your code out fully before you start to write the code
itself.
● Documenting your code well enough that anyone can understand the general
process that it uses.
● Writing code that can be reused or adapted easily.
● Using functions where appropriate to make your code modular and hide complexity.
● Designingyourcodetointeractwiththeuserviainputsandoutput,sothattheuser
does not need to examine the code itself.
simple way to save yourself time when coding is, before you even start to write your code,
A
to write a plan of how your code will work. For the simple scripts that we are writing now,
you can get away without doing this (although it’s still highly recommended). However, next
week we will start to work on longer, more complex codes. Figure 4.14 shows an example of
a flowchart for a simple program.
1
ENG1014Engineering Numerical AnalysisCourse Notes
ell-written code should be easy to read and understand. This allows other people
W
(including membersofanyteamsyouarepartof)touse/adaptyourcodewithoutneeding
tospendgreateffortstudyinghowitworks.Thissectionwilldescribesomecommonfactors
we generally consider when discussing the documentation of a script file.
hen writing any script, you must consider organising the script so that any user or other
W
programmers can conveniently read through the script and understand the purpose and
application of the code. Examine Figure 4.14 and ask yourself how much of the code you can
understand, and what features help/hinder your understanding:
ommentsareafeatureofallprogramminglanguages.Commentsarerepresentedasgreen
C
text in MATLABanddeclaredwithapercentagesymbol–youhaveseensomeexamplesin
earliersectionsofthenotes.CommentlinesarenotexecutedbyMATLABwhenyourunthe
code.
omments should be written to explain the overall purpose of the code, rather than the
C
mechanics of how it works. You can add comments to provide reference informationthat
2
ENG1014Engineering Numerical AnalysisCourse Notes
y ou woulduseinyourcode.Commentsarealsoanexcellentoptiontodescribelimitations
and mention needed improvements of any script version. For complicated programs,
commentscanbejustascriticalasthecodeitself–especiallywhenworkingwithinateam
or when the code must be checked by others.
T his section provides some guidelines on using the comment feature of MATLAB to provide
proper documentation of your code.
● C omment your code as you write it (or even before you write it, to help with
planning).
● Use plain English and keep the comments concise.
● Avoid redundant comments. For example, the following are not useful:
o x = y + 1% x is y plus one
o temperature = 30% the temperature is set to 30
● You do not need to comment on every single line of your script. Provide comments
on different blocks of the scripts, such as:
o When defining variables
o When calculating using equations
o Explain the loops in the code
o the parameters/results/variables are you plotting, etc.
● Include some general information at the first line of the code:
o Yournameand studentID number.
o Thedateyou created or last modified the m-file.
o A short descriptionof what the m-file does.
T he practice of adding sections in MATLAB is also useful for longer scripts. This makes it
convenientforthewritertorunandchecktheresultsofanysection.Addingasectioninany
scriptalsomakesitconvenientforotheruserstofollowhowthecodeapproachesdifferent
segments of the problem.
Figure 4.15 shows the Run and Run section tabs on MATLAB.
3
ENG1014Engineering Numerical AnalysisCourse Notes
Figure 4.16 provides an improved example of the code shown in Figure 4.14.
4
ENG1014Engineering Numerical AnalysisCourse Notes
4.8.Reusable code
hile writing scripts, you should always make the code versatile, so that the code can be
W
used to solve similar problems with only minor changes. Some points to keep in mind
regarding the reusability of code:
A
● void using numerical values in equations and other MATLAB operations (e.g., plots).
● Define the given numerical values of parameters in the question by decla variables
and use the variables to calculate any equations or functions and plots.
● You can create functions for an equation or process that must be used several times
(Functions are discussed in Section 4.1).
𝑥
“ The exponential function𝑒 can be approximatedusing a Taylor/Maclaurin series
𝑥
alculate the approximation of𝑒 using the firstsix terms of the series. i.e.,𝑛= 0 to𝑛= 5 for
C
x = 1, 5, 25, 60.”
Consider the following MATLAB codes, all of which solve the above problem:
T he code above has very poor reusability. If we want to calculate an approximation for ex for
any other values of x, we need to change the number multiple times.
T his code has defined the parameters used in the problem, and then performed the
calculation using a variable, which is a good start. However it still does not provide good
adaptability. If the question asked to use𝑛= 0to𝑛= 100, it needs to be typed to 100th term.
5
ENG1014Engineering Numerical AnalysisCourse Notes
T he following code defines the number of the terms as a variable, which can be changed for
any number of terms. This would be considered a good-practice approach to solving this
problem.
S ome examples of good practice in using comments and creating easily editable and
reusable code can be found in Video Link 4.7.
6
ENG1014Engineering Numerical AnalysisCourse Notes
4.9.Functions
function is a group of statements that together perform a task. In MATLAB, therearea
A
range of built-in functions that come with the package, including sin(), cos(),
sqrt(),
plot(), pause(), log ()
etc. Matlab also allows user-defined functions
tobecreated.Functionsaremodularastheycanreuseapatternofcodeondifferentinput
values. This section will describe how to create and use custom functions in your code.
If you need to perform a certain set of calculations many times throughout a script, e.g.
calculate sin(x)*cos(x)*tan(x ,withoutwritingafunction,youwouldhavetotypeit
out every time as needed in the script.
7
ENG1014Engineering Numerical AnalysisCourse Notes
ser-defined functionsallowyoutocreatecustomisedfunctionsbasedonusers'demands.
U
Likethebuilt-inMATLABfunctions,user-definedfunctionscanhaveoneormoreinputsand
outputs.
● N otethatiffunction_nameisthefunctionheader,thefunctionm-filenamemustbe
function_name.m.InFigure4.17,noticethefunctionfilenameandfunctionheader
name. Be aware that names are case-sensitive.
● Writethecodeforyourfunction.Thisfunctionacceptsoneinput(x)andreturnsone
𝑥
output (ex_approx), which is the approximated value of𝑒 .
✔
Do notuse fprintf, disp or plot (put these in yourmain script)
✔ Do notask for an input prompt.
✔ Do notuse clear all; close all; clc; commands.
✔ Do notoverwrite existing MATLAB functions – picka name that is not in use.
✔ Dosuppress all your outputs using the semi-colon.
✔ Dodocument your code appropriately.
✔
For our sin*cos*tan example, the “sct” function below will calculate the desired output.
8
ENG1014Engineering Numerical AnalysisCourse Notes
We can now call the "sct" function, in a similar way to how we call a Matlab inbuilt function:
ote that user-defined functions must be stored in the same directory as the main script.
N
They can only be called from current directories, unlike the built-in MATLAB functions which
are always available. For example, the sct.m function file and the m-file where the function
is called upon must be in the same folder.
N
● ame, ID, and date the function was last modified.
● Description of what the function does.
● Description of the input argument and outputs.
F igure 4.18 shows an example of what to include for function documentation for the sct.m
function discussed in the previous sections.
9
ENG1014Engineering Numerical AnalysisCourse Notes
nce the function is created, you can also see the function details by typing help in the
O
command window. For the sct function, you can type" elp sct"on the command
h
window. This will retrieve the information shown in Figure 4.19.
● F unction names should be self-documenting. For example, naming the exp_taylor
function in Figure 4.17 as log_exp would be misleading.
● You must use the same name for the function and the m-file that has the function
script. For example, the exp_taylor function must be saved as exp_taylor.m
● Avoid using function names that collide with built-in MATLAB functions (e.g., sin, sqrt
, plot, etc.). If needed, you can use any suitable prefix or suffix to avoid collisions (e.g.
MySin, MySqrt, plot_custom, etc.)
F unctions can have multiple inputs and outputs. Let's write a function for the following
question,
hereris the radius of the base of the cone andhis the height of the cone. Write afunction
w
that accepts𝑟and𝑉as input arguments and computesℎand𝐴.”
10
ENG1014Engineering Numerical AnalysisCourse Notes
ere we know the function inputs are𝑟and𝑉and need to calculateℎand𝐴. We can create
H
a function "SA_calc", referring to surface area calculation. Inside the function, we need to
provide the equation to calculateℎand𝐴. The functionscript can be shown as in Figure 4.20
F igure 4.21: Example of function (including function documentation) for a function with
multiple inputs and outputs.
● Y ou cannot directly run function’s m-file.
● Functions should be called by separate m-files.
● Ensure that the current directory contains the function being called.
● Just like built-in functions, all input arguments must be specified when calling a
function.
Include a function name that is descriptive and doesn’t clash with existing names.
●
● Include a list of inputs and outputs in the function documentation (including the
order in which they are listed), and check this when you are planning to call the
function.
11
ENG1014Engineering Numerical AnalysisCourse Notes
F orshortfunctionssuchasour“sct”example,writingupadedicatedfunctionfiletocreatea
standard user-defined function is somewhat inefficient. Anonymous functions canaddress
this.Anonymous functions provides flexibility to create a function "on-the-fly" without a
function file.
ideo Link 4.8: Further explanations and examples of how to create and use custom
V
functions in Matlab. (17 mins)
12