0% found this document useful (0 votes)
3 views31 pages

Week 4 Course Notes

The ENG1014 course notes cover programming methods and practices in MATLAB, focusing on input and output techniques, including the use of functions like input() and fprintf. It emphasizes good coding practices such as proper documentation, reusable code, and effective data handling. Additionally, the notes provide video links for further learning on importing data and using functions in MATLAB.

Uploaded by

mouhidi216
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)
3 views31 pages

Week 4 Course Notes

The ENG1014 course notes cover programming methods and practices in MATLAB, focusing on input and output techniques, including the use of functions like input() and fprintf. It emphasizes good coding practices such as proper documentation, reusable code, and effective data handling. Additionally, the notes provide video links for further learning on importing data and using functions in MATLAB.

Uploaded by

mouhidi216
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

‭ENG1014Engineering Numerical AnalysisCourse Notes‬

‭ENG1014 Course notes‬


‭Week 4.‬ ‭Programming methods and practices‬
‭Programming methods‬

‭ .1.‬
4 ‭I‬‭NPUT‬‭AND‬ ‭O‬‭UTPUT‬‭IN‬ ‭M‬‭ATLAB‬‭......................................................................................................................‬‭4‬
‭4.2.‬ ‭I‬‭NPUT‬‭INTO‬ ‭M‭A‬ TLAB‬‭....................................................................................................................................‬‭5‬
‭4.2.1.‬ ‭The‬‭ input()‬‭function‬‭...................................................................................................................‬‭5‬
‭4.2.2.‬ ‭Importing‬‭datafiles‬‭into‬‭MATLAB‬‭....................................................................................................‬‭5‬
‭4.3.‬ ‭O‭U‬ TPUT‬‭FROM‬ ‭M‭A‬ TLAB‬‭................................................................................................................................‬‭8‬
‭4.3.1.‬ ‭Overview‬‭of‬‭ fprintf‬‭function‬‭....................................................................................................‬‭8‬
‭4.3.2.‬ ‭Printing‬‭variables‬‭............................................................................................................................‬‭8‬
‭4.3.3.‬ ‭Using‬‭special‬‭characters‬‭..................................................................................................................‬‭9‬
‭4.3.4.‬ ‭Specifying‬‭width‬‭and‬‭precision‬‭......................................................................................................‬‭10‬
‭4.3.5.‬ ‭Printing‬‭multiple‬‭variables‬‭............................................................................................................‬‭11‬
‭4.3.6.‬ ‭ fprintf‬‭with‬‭matrices‬‭.............................................................................................................‬‭11‬
‭4.3.7.‬ ‭Using‬‭ fprintf‬‭to‬‭write‬‭to‬‭a‬‭file‬‭.................................................................................................‬‭12‬
‭4.3.8.‬ ‭Overview‬‭of‬‭ sprintf‬‭function‬‭...................................................................................................‬‭12‬
‭4.4.‬ ‭R‭E‬ LATIONAL‬‭AND‬ ‭L‬‭OGICAL‬ ‭O‬‭PERATORS‬‭............................................................................................................‬‭14‬
‭4.4.1.‬ ‭Logicals‬‭..........................................................................................................................................‬‭14‬
‭4.4.2.‬ ‭Relational‬‭Operators‬‭.....................................................................................................................‬‭14‬
‭4.4.3.‬ ‭Using‬‭logicals‬‭for‬‭more‬‭than‬‭one‬‭condition‬‭...................................................................................‬‭16‬
‭4.5.‬ ‭U‭S‬ ING‬‭LOGICALS‬‭TO‬‭FILTER‬‭DATA‬‭....................................................................................................................‬‭17‬

‭Programming practices‬
‭ .6.‬
4 ‭P‬‭LANNING‬‭YOUR‬‭CODE‬‭:‬‭FLOW‬‭CHARTS‬‭AND‬‭ALGORITHMS‬‭.........................................................................................‬‭2‬
‭4.7.‬ ‭C‬‭ODING‬‭DOCUMENTATION‬‭:‬‭COMMENTING‬‭YOUR‬‭CODE‬‭.............................................................................................‬‭3‬
‭4.8.‬ ‭R‭E‬ USABLE‬‭CODE‬‭AND‬‭FUNCTIONS‬‭.....................................................................................................................‬‭6‬
‭4.9.‬ ‭F‬‭UNCTIONS‬‭...............................................................................................................................................‬‭8‬
‭4.9.1.‬ ‭When‬‭to‬‭use‬‭a‬‭function‬‭...................................................................................................................‬‭8‬
‭4.9.2.‬ ‭Creating‬‭and‬‭using‬‭functions‬‭...........................................................................................................‬‭9‬
‭4.9.3.‬ ‭Calling‬‭Functions‬‭...........................................................................................................................‬‭10‬
‭4.9.4.‬ ‭Function‬‭Documentation‬‭...............................................................................................................‬‭10‬
‭4.9.5.‬ ‭Function‬‭Names‬‭............................................................................................................................‬‭11‬
‭4.9.6.‬ ‭Functions‬‭with‬‭multiple‬‭inputs‬‭and‬‭outputs‬‭..................................................................................‬‭11‬
‭4.9.7.‬ ‭User-defined‬‭functions:‬‭checklist‬‭...................................................................................................‬‭12‬
‭4.9.8.‬ ‭Anonymous‬‭functions‬‭....................................................................................................................‬‭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‬

‭4.1.‬‭Input and Output Overview‬

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‬ ‭contains‬‭sensors‬‭that‬‭generate‬
‭data‬‭files‬‭that‬‭we‬‭would‬‭like‬‭to‬‭analyse.‬‭These‬‭files‬‭contain‬‭large‬‭quantities‬‭of‬‭data,‬‭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”‬‭(what‬‭does‬‭it‬‭actually‬‭mean?)‬‭to‬‭“ The‬‭ball’s‬‭final‬‭displacement‬‭is‬‭5‬
‭cm”.‬
‭●‬ ‭Graphs‬ ‭and‬ ‭tables‬ ‭need‬ ‭to‬ ‭be‬ ‭labelled;‬ ‭using‬ ‭ sprintf()‬‭is‬‭a‬‭good‬‭way‬‭to‬‭create‬
‭effective‬ ‭labels‬ ‭that‬ ‭can‬ ‭be‬ ‭generated‬ ‭automatically‬ ‭by‬ ‭the‬ ‭script,‬ ‭rather‬ ‭than‬
‭needing to be hard-coded.‬
‭●‬ ‭Exporting‬ ‭your‬ ‭data‬ ‭in‬ ‭a‬ ‭standard‬ ‭format‬ ‭that‬‭is‬‭readable‬‭by‬‭another‬‭program‬‭(e.g.‬
‭.txt or .csv) is also important in many situations.‬

‭3‬
‭ENG1014Engineering Numerical AnalysisCourse Notes‬

‭●‬ B‭ eing‬‭able‬‭to‬‭import‬‭data‬‭into‬‭your‬‭script‬‭while‬‭it‬‭runs‬‭avoids‬‭having‬‭to‬‭“hard-code”‬
‭that‬ ‭data‬ ‭into‬ ‭your‬ ‭script.‬ ‭This‬ ‭means‬ ‭that‬ ‭someone‬ ‭can‬ ‭reuse‬ ‭your‬‭script‬‭without‬
‭needing‬ ‭to‬ ‭edit‬ ‭it,‬ ‭which‬ ‭avoids‬ ‭accidental‬ ‭changes‬ ‭being‬ ‭made.‬ ‭It‬ ‭also‬ ‭allows‬
‭non-programmers to use your work.‬

‭4.2.‬‭Input into Matlab‬


input()‬‭function‬
‭4.2.1.‬ ‭The‬‭

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

height = input('Enter your height (in cm): ')‬


‭ 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.‬

‭4.2.2.‬ ‭Importing datafiles into MATLAB‬

Y‭ ou‬‭can‬‭analyse‬‭data‬‭from‬‭any‬‭supported‬‭file‬‭formats‬‭in‬‭MATLAB‬‭by‬‭importing‬‭the‬‭data‬‭and‬
‭defining‬‭variables‬‭to‬‭save‬‭sections‬‭of‬‭the‬‭data.‬‭These‬‭are‬‭then‬‭used‬‭to‬‭perform‬‭any‬‭required‬
‭MATLAB operation. There are two main methods used for importing data into Matlab.‬

T‭ he‬ ‭first‬ ‭method‬ ‭uses‬ ‭the‬ ‭


fgetl‬‭command‬‭to‬‭retrieve‬‭individual‬‭lines‬‭of‬‭data‬‭from‬‭a‬‭file.‬
‭This‬‭method‬‭is‬‭highly‬‭adaptable,‬‭but‬‭more‬‭difficult‬‭to‬‭use.‬‭It‬‭is‬‭demonstrated‬‭briefly‬‭in‬‭Video‬
‭Link 4.1, but will not be a major focus of ENG1014.‬

T‭ he‬‭second‬‭method‬‭uses‬‭the‬‭ importdata‬‭function‬‭to‬‭import‬‭data.‬‭It‬‭is‬‭very‬‭easy‬‭to‬‭use,‬
‭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‬

‭Video Link 4.1: Importing data into MATLAB (14 minutes)‬

‭6‬
‭ENG1014Engineering Numerical AnalysisCourse Notes‬

‭4.3.‬‭Output from Matlab‬

fprintf‬‭function‬
‭4.3.1.‬ ‭Overview of‬‭

T‭ he‬‭name‬‭ fprintf‬‭is‬‭short‬‭for‬‭“formatted‬‭print‬‭function”.‬‭It‬‭allows‬‭you‬‭to‬‭print‬‭your‬‭data‬
‭to‬‭a‬‭file‬‭in‬‭TXT‬‭or‬‭similar‬‭filetypes,‬‭that‬‭can‬‭be‬‭imported‬‭into‬‭other‬‭computer‬‭programs.‬‭The‬
‭function‬‭allows‬‭you‬‭to‬‭"format"‬‭how‬‭the‬‭data‬‭is‬‭printed‬‭in‬‭such‬‭a‬‭manner‬‭as‬‭to‬‭make‬‭it‬‭easy‬
‭to read.‬

T‭ he‬‭fprintf‬‭function‬‭also‬‭allows‬‭you‬‭to‬‭"write"‬‭information‬‭to‬‭the‬‭screen‬‭for‬‭the‬‭user‬‭to‬‭view‬
‭–‬ ‭in‬ ‭fact‬ ‭this‬ ‭is‬ ‭now‬ ‭its‬ ‭most‬ ‭common‬ ‭use.‬ ‭Displaying‬ ‭information‬‭on‬‭the‬‭screen‬‭becomes‬
‭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.‬

‭4.3.2.‬ ‭Printing variables‬

‭ e‬ ‭often‬ ‭use‬ ‭the‬ ‭fprintf‬ ‭statement‬ ‭to‬ ‭show‬‭the‬‭user‬‭information‬‭stored‬‭in‬‭our‬‭variables‬‭–‬


W
‭this‬‭method‬‭is‬‭much‬‭more‬‭powerful‬‭than‬‭simply‬‭omitting‬‭the‬‭semi-colon‬‭at‬‭the‬‭end‬‭of‬‭a‬‭line.‬
‭To‬‭"place"‬‭a‬‭number‬‭into‬‭this‬‭string‬‭of‬‭printed‬‭characters‬‭we‬‭use‬‭several‬‭formatting‬‭options,‬
‭but they all start with a % sign. The most common of these are:‬

S‭ ymbol‬ ‭ escription‬
D
‭%d‬ ‭Prints‬ ‭a‬ ‭“decimal”‬ ‭number‬ ‭(i.e‬ ‭in‬ ‭the‬ ‭base-10‬ ‭number‬ ‭system).‬ ‭If‬ ‭the‬
‭number‬‭is‬‭an‬‭integer,‬‭it‬‭will‬‭display‬‭as‬‭an‬‭integer,‬‭otherwise‬‭it‬‭will‬‭display‬
‭decimal places.‬
‭%f‬ ‭Prints‬ ‭a‬ ‭“floating‬ ‭point”‬ ‭number‬ ‭(i.e.‬ ‭a‬ ‭number‬ ‭with‬ ‭decimal‬ ‭places).‬
‭Decimal places are always shown.‬

T‭ hese‬‭symbols‬‭are‬‭placeholders‬‭that‬‭are‬‭included‬‭in‬‭the‬‭ 'format'‬‭part‬‭of‬‭the‬‭syntax,‬‭and‬
‭instruct‬ ‭Matlab‬ ‭to‬ ‭insert‬ ‭data‬ ‭from‬‭the‬‭variables‬‭that‬‭are‬‭listed‬‭later‬‭in‬‭the‬‭syntax‬‭(‬‭
var1,‬
var2,…‬
‭ ‭).‬ ‭Placeholders‬ ‭are‬ ‭denoted‬ ‭with‬ ‭a‬ ‭percentage‬ ‭symbol‬ ‭(%) and‬ ‭are‬ ‭coupled‬ ‭with‬
‭specifiers.‬ ‭The‬ ‭variables‬ ‭for‬ ‭your‬ ‭placeholders‬ ‭follow‬‭the‬‭list‬‭of‬‭variables‬‭as‬‭they‬‭appear‬‭in‬
‭the order written.‬

‭Note that when used in this way, the % is not the comment character‬‭.‬

‭7‬
‭ENG1014Engineering Numerical AnalysisCourse Notes‬

‭Example:‬

fprintf‬‭sample 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.‬

‭4.3.3.‬ ‭Using special characters‬


f‭ printf allows printing of special characters to allow users to have better formatting options‬
‭and display of results. Some common format options are:‬
‭●‬ ‭%s - print a string (characters enclosed by quotation marks -‬‭ "string example"‬ ‭)‬
‭●‬ ‭%c - print a single character or a character array‬
‭●‬ ‭\n - print a new line (go to the next line to continue printing)‬
‭●‬ ‭\t - print a tab‬
‭●‬ ‭\\ - print a slash‬
‭●‬ ‭%% - print a percent sign‬

‭A more extensive list of formatting options can be found within the‬‭Matlab documentation.‬

‭8‬
‭ENG1014Engineering Numerical AnalysisCourse Notes‬

‭Examples:‬

‭Figure 4.3: Examples of using special characters in fprintf.‬

‭4.3.4.‬ ‭Specifying width and precision‬

‭ 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.5.‬ ‭Printing multiple variables‬

fprintf‬‭you need‬‭to put the variables in the correct‬


‭ hile using multiple variables in‬‭
W
‭order as you assign the place holders and write the text. An example of each of the correct‬
‭and incorrect order is given below:‬

fprintf‬‭sample code to print multiple‬‭variables.‬


‭Figure 4.4: :‬‭

‭4.3.6.‬ ‭
fprintf‬‭with matrices‬

‭printf‬‭works with vectors/matrices and prints each‬‭element. 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.‬

‭An example is shown here for vector and matrix printing.‬

‭10‬
‭ENG1014Engineering Numerical AnalysisCourse Notes‬

F‭ igure 4.5: Example code for printing vector and matrix.‬


‭4.3.7.‬ ‭Using‬‭ fprintf‬‭to write to a file‬

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, and‬‭then closing the file.‬

‭1.‬ U filename = fopen()‬‭to create a file or open an‬‭existing file.‬


‭ se‬‭
‭●‬ ‭ filename‬‭is a variable containing the file handle‬
‭●‬ ‭You will need to include a “permission” that allows you to write or append to‬
‭the file, for example:‬

'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 to‬‭close the file and free up‬
‭ se‬‭
‭memory‬

sprintf‬‭function‬
‭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.‬

fprintf‬‭and‬‭
F‭ urther details on the‬‭ sprintf‬‭functions‬‭with example can be found in‬
‭Video Links 4.1, 4.2 and 4.3.‬

‭12‬
‭ENG1014Engineering Numerical AnalysisCourse Notes‬

‭Video Link 4.2: Working with string variables (37 mins)‬‭.‬

‭Video Link 4.3: Outputting into Files with MATLAB (9 mins)‬

‭Video Link 4.4: Outputting strings with MATLAB (12 mins)‬

‭13‬
‭ENG1014Engineering Numerical AnalysisCourse Notes‬

‭4.4.‬‭Relational and Logical Operators‬

‭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)‬‭, and‬‭zero is FALSE (logical 0),‬‭which‬‭can be seen from the example in Figure 4.7.‬

‭Figure 4.7: Logical function in MATLAB.‬

‭4.4.2.‬ ‭Relational Operators‬

‭ elational operators perform element-by-element comparisons between two variables. They‬


R
‭return a logical array of the same size, with elements set to logical 1 (true) where the‬
‭relation is true, and elements set to logical 0 (false) where it is not.‬

‭The following table shows the relational operators available in MATLAB:‬

‭Table 4.1: List of relational operators in MATLAB with description.‬

‭14‬
‭ENG1014Engineering Numerical AnalysisCourse Notes‬

‭These operators work on both scalar and vector variables, as seen in Figure 4.8.‬

‭Figure 4.8: Examples of relational operators producing logical data types.‬

‭ elational operators can also compare values within matrices if the matrices are the same‬
R
‭size, as seen in Figure 4.9.‬

‭Figure 4.9: Examples of relational operators in matrices.‬

‭ 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".‬

‭Figure 4.10: Relational operators and the equals sign.‬

‭15‬
‭ENG1014Engineering Numerical AnalysisCourse Notes‬

‭4.4.3.‬ ‭Using logicals for more than one condition‬

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”.‬

‭Table 4.2: Common logical operators.‬

‭Logical Operator‬ ‭Name‬ ‭ escription‬


D
‭Combines results from two relational‬
‭&‬ ‭AND‬ ‭operators. True only when both are true,‬
‭otherwise false.‬
‭Combines results from two relational‬
‭|‬ ‭OR‬ ‭operators. True when one or both are true,‬
‭false only if both are false.‬
‭~‬ ‭NOT‬ ‭Returns the opposite of a logical variable.‬

‭A|‬ ‭A=‬ ‭A=‬


‭A‬‭&‬ ‭A=‬ ‭A=‬ ‭B‬ ‭1‬ ‭0‬
‭~A‬ ‭A=‬ ‭A=‬
‭B‬ ‭1‬ ‭0‬ ‭B=‬ ‭1‬ ‭1‬ ‭1‬ ‭0‬
‭B=1‬ ‭1‬ ‭0‬ ‭1‬
‭0‬ ‭1‬
‭B=0‬ ‭0‬ ‭0‬ ‭B=‬ ‭1‬ ‭0‬
‭0‬

‭Figure 4.11: “Truth tables” for AND/OR/NOT 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 combining‬‭the 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‬

‭4.5.‬‭Using logicals to filter data‬

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

‭Video Link 4.6: More examples of filtering using logicals‬‭(4 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‬

‭Good programming practices‬


I‭n‬ ‭week‬ ‭2,‬ ‭we‬ ‭discussed‬ ‭a‬ ‭set‬ ‭of‬ ‭good‬ ‭practice‬ ‭guidelines‬ ‭for‬ ‭showing‬ ‭your‬ ‭methods‬ ‭in‬
‭solving‬‭mathematical‬‭problems‬‭by‬‭hand.‬‭We‬‭will‬‭start‬‭this‬‭week‬‭by‬‭discussing‬‭an‬‭equivalent‬
‭set of principles for writing code. These include:‬

‭●‬ 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.‬
‭●‬ ‭Designing‬‭your‬‭code‬‭to‬‭interact‬‭with‬‭the‬‭user‬‭via‬‭inputs‬‭and‬‭output,‬‭so‬‭that‬‭the‬‭user‬
‭does not need to examine the code itself.‬

‭4.6.‬‭Planning your code: flow charts‬

‭ 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.‬

‭Figure 4.14: Basic flowchart for a simple linear program‬

‭1‬
‭ENG1014Engineering Numerical AnalysisCourse Notes‬

‭4.7.‬‭Coding documentation: commenting your code‬

‭ ell-written‬ ‭code‬ ‭should‬ ‭be‬ ‭easy‬ ‭to‬ ‭read‬ ‭and‬ ‭understand.‬ ‭This‬ ‭allows‬ ‭other‬ ‭people‬
W
‭(including‬ ‭members‬‭of‬‭any‬‭teams‬‭you‬‭are‬‭part‬‭of)‬‭to‬‭use/adapt‬‭your‬‭code‬‭without‬‭needing‬
‭to‬‭spend‬‭great‬‭effort‬‭studying‬‭how‬‭it‬‭works.‬‭This‬‭section‬‭will‬‭describe‬‭some‬‭common‬‭factors‬
‭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:‬

‭Figure 4.15: Example of poorly documented code.‬

‭ omments‬‭are‬‭a‬‭feature‬‭of‬‭all‬‭programming‬‭languages.‬‭Comments‬‭are‬‭represented‬‭as‬‭green‬
C
‭text‬ ‭in‬ ‭MATLAB‬‭and‬‭declared‬‭with‬‭a‬‭percentage‬‭symbol‬‭–‬‭you‬‭have‬‭seen‬‭some‬‭examples‬‭in‬
‭earlier‬‭sections‬‭of‬‭the‬‭notes.‬‭Comment‬‭lines‬‭are‬‭not‬‭executed‬‭by‬‭MATLAB‬‭when‬‭you‬‭run‬‭the‬
‭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‬ ‭information‬‭that‬

‭2‬
‭ENG1014Engineering Numerical AnalysisCourse Notes‬

y‭ ou‬ ‭would‬‭use‬‭in‬‭your‬‭code.‬‭Comments‬‭are‬‭also‬‭an‬‭excellent‬‭option‬‭to‬‭describe‬‭limitations‬
‭and‬ ‭mention‬ ‭needed‬ ‭improvements‬ ‭of‬ ‭any‬ ‭script‬ ‭version.‬ ‭For‬ ‭complicated‬ ‭programs,‬
‭comments‬‭can‬‭be‬‭just‬‭as‬‭critical‬‭as‬‭the‬‭code‬‭itself‬‭–‬‭especially‬‭when‬‭working‬‭within‬‭a‬‭team‬
‭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‬ ‭Your‬‭name‬‭and student‬‭ID number‬‭.‬
‭o‬ ‭The‬‭date‬‭you created or last modified the m-file.‬
‭o‬ ‭A short description‬‭of what the m-file does.‬

T‭ he‬ ‭practice‬ ‭of‬ ‭adding‬ ‭sections‬ ‭in‬ ‭MATLAB‬ ‭is‬ ‭also‬ ‭useful‬ ‭for‬ ‭longer‬ ‭scripts.‬ ‭This‬ ‭makes‬ ‭it‬
‭convenient‬‭for‬‭the‬‭writer‬‭to‬‭run‬‭and‬‭check‬‭the‬‭results‬‭of‬‭any‬‭section.‬‭Adding‬‭a‬‭section‬‭in‬‭any‬
‭script‬‭also‬‭makes‬‭it‬‭convenient‬‭for‬‭other‬‭users‬‭to‬‭follow‬‭how‬‭the‬‭code‬‭approaches‬‭different‬
‭segments of the problem.‬

‭●‬ u ‭ se double‬‭%%‬‭symbols to include a section that creates‬‭and highlights code blocks.‬


‭(See Figure 4.16 for the highlighted section of "Part A")‬
‭●‬ ‭The ''Run'' button runs through the entire script. However, the‬‭''Run Section''‬‭button‬
‭can be used to run through sections of a script.‬

‭Figure 4.15 shows the Run and Run section tabs on MATLAB.‬

‭Figure 4.16: MATLAB command tabs- Runs and Run Section.‬

‭3‬
‭ENG1014Engineering Numerical AnalysisCourse Notes‬

‭Figure 4.16 provides an improved example of the code shown in Figure 4.14.‬

F‭ igure 4.17: Example of improved documentation of a script to find Fibonacci numbers‬


‭starting with the digits 5 or 8.‬

‭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).‬

‭Let's consider solving the following question.‬

‭𝑥‬
‭“ The exponential function‬‭𝑒‬ ‭can be approximated‬‭using a Taylor/Maclaurin series‬

‭𝑥‬
‭ alculate the approximation of‬‭𝑒‬ ‭using the first‬‭six 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 e‬‭x‬ ‭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‬‭𝑛‬‭= 0‬‭to‬‭𝑛‬‭= 100, it needs to be typed to 100‬‭th‬ ‭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.‬

‭Video Link 4.7: Good programming practice in Matlab. (5 mins)‬

‭6‬
‭ENG1014Engineering Numerical AnalysisCourse Notes‬

‭4.9.‬‭Functions‬

‭ ‬ ‭function‬ ‭is‬ ‭a‬ ‭group‬ ‭of‬ ‭statements‬ ‭that‬ ‭together‬ ‭perform‬ ‭a‬ ‭task.‬ ‭In‬ ‭MATLAB,‬ ‭there‬‭are‬‭a‬
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‬
‭to‬‭be‬‭created.‬‭Functions‬‭are‬‭modular‬‭as‬‭they‬‭can‬‭reuse‬‭a‬‭pattern‬‭of‬‭code‬‭on‬‭different‬‭input‬
‭values. This section will describe how to create and use custom functions in your code.‬

‭Using functions appropriately is an important part of good coding practice:‬


‭●‬ F‭ unctions‬ ‭allow‬ ‭us‬ ‭to‬ ‭perform‬ ‭a‬ ‭task‬ ‭repeatedly,‬ ‭often‬ ‭using‬ ‭slightly‬ ‭different‬
‭conditions each time, therefore aiding the adaptability of our code.‬
‭●‬ ‭Functions‬ ‭can‬ ‭be‬ ‭used‬ ‭to‬ ‭hide‬ ‭long,‬ ‭detailed‬ ‭pieces‬ ‭of‬ ‭code‬ ‭that‬ ‭perform‬
‭conceptually‬‭simple‬‭tasks.‬‭For‬‭example,‬‭we‬‭do‬‭not‬‭need‬‭to‬‭know‬‭all‬‭the‬‭steps‬‭that‬
‭a‬‭computer‬‭takes‬‭to‬‭calculate‬‭the‬‭cosine‬‭of‬‭an‬‭angle;‬‭we‬‭only‬‭need‬‭to‬‭know‬‭what‬
‭the output is and what it means.‬

‭4.9.1.‬ ‭When to use a function‬

I‭f‬ ‭you‬ ‭need‬ ‭to‬ ‭perform‬ ‭a‬ ‭certain‬ ‭set‬ ‭of‬ ‭calculations‬ ‭many‬ ‭times‬ ‭throughout‬ ‭a‬ ‭script,‬ ‭e.g.‬
‭calculate‬‭ sin(x)*cos(x)*tan(x‬ ‭,‬‭without‬‭writing‬‭a‬‭function,‬‭you‬‭would‬‭have‬‭to‬‭type‬‭it‬
‭out every time as needed in the script.‬

‭ e‬ ‭can‬ ‭create‬ ‭a‬ ‭function‬ ‭to‬ ‭compute‬ ‭sin(x)*cos(x)*tan(x)‬ ‭which‬‭will‬‭accept‬‭one‬‭input‬‭and‬


W
‭return‬ ‭the‬ ‭product‬ ‭of‬ ‭sin(x)*cos(x)*tan(x)‬ ‭as‬ ‭output.‬ ‭We‬ ‭will‬ ‭use‬‭this‬‭example‬‭to‬‭illustrate‬
‭how functions can be useful.‬

‭7‬
‭ENG1014Engineering Numerical AnalysisCourse Notes‬

‭4.9.2.‬ ‭Creating and using functions‬

‭ ser-defined‬ ‭functions‬‭allow‬‭you‬‭to‬‭create‬‭customised‬‭functions‬‭based‬‭on‬‭users'‬‭demands.‬
U
‭Like‬‭the‬‭built-in‬‭MATLAB‬‭functions,‬‭user-defined‬‭functions‬‭can‬‭have‬‭one‬‭or‬‭more‬‭inputs‬‭and‬
‭outputs.‬

‭ ‬ S‭ tart a new m-file (script file).‬



‭●‬ ‭Declare it as a function with a function header. The function header declaration‬
‭syntax is‬

function [outputs] = function_name (inputs)‬


‭Figure 4.18: A function to perform a 6-term Taylor series approximation of e‬‭x‬

‭●‬ N ‭ ote‬‭that‬‭if‬‭function_name‬‭is‬‭the‬‭function‬‭header,‬‭the‬‭function‬‭m-file‬‭name‬‭must‬‭be‬
‭function_name.m‬‭.‬‭In‬‭Figure‬‭4.17,‬‭notice‬‭the‬‭function‬‭file‬‭name‬‭and‬‭function‬‭header‬
‭name. Be aware that names are case-sensitive.‬
‭●‬ ‭Write‬‭the‬‭code‬‭for‬‭your‬‭function.‬‭This‬‭function‬‭accepts‬‭one‬‭input‬‭(x)‬‭and‬‭returns‬‭one‬
‭𝑥‬
‭output (ex_approx), which is the approximated value of‬‭𝑒‬ ‭.‬

‭A few guidelines to remember while writing any user-defined function file:‬


‭ ‬ ‭Do not‬‭use fprintf, disp or plot (put these in your‬‭main script)‬
‭✔‬ ‭Do not‬‭ask for an input prompt.‬
‭✔‬ ‭Do not‬‭use clear all; close all; clc; commands.‬
‭✔‬ ‭Do not‬‭overwrite existing MATLAB functions – pick‬‭a name that is not in use.‬
‭✔‬ ‭Do‬‭suppress all your outputs using the semi-colon.‬
‭✔‬ ‭Do‬‭document your code appropriately.‬
‭✔‬
‭For our sin*cos*tan example, the “sct” function below will calculate the desired output.‬

‭8‬
‭ENG1014Engineering Numerical AnalysisCourse Notes‬

‭4.9.3.‬ ‭Calling Functions‬

‭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.‬

‭4.9.4.‬ ‭Function Documentation‬

‭ ll user-defined function files should have documentation (written as comments) that‬


A
‭includes the following information‬‭after‬‭the function‬‭declaration:‬

‭‬ 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.‬

‭Figure 4.19: Function documentation for the "sct" function.‬

‭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.‬

‭Figure 4.20: Using command window to get user-defined function.‬

‭4.9.5.‬ ‭Function Names‬

‭Some guidelines on naming user-defined functions:‬

‭●‬ 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.)‬

‭4.9.6.‬ ‭Functions with multiple inputs and outputs‬

F‭ unctions can have multiple inputs and outputs. Let's write a function for the following‬
‭question,‬

‭“ The volume‬‭𝑉‬‭and paper surface‬‭𝐴‬‭of a conical paper‬‭cup are given by‬

‭ here‬‭r‬‭is the radius of the base of the cone and‬‭h‬‭is the height of the cone. Write a‬‭function‬
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 function‬‭script 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.‬

‭4.9.7.‬ ‭User-defined functions: checklist‬

‭Here is a checklist of things to remember when defining/calling a user-defined function:‬

‭‬
● 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‬

‭4.9.8.‬ ‭Anonymous functions‬

F‭ or‬‭short‬‭functions‬‭such‬‭as‬‭our‬‭“sct”‬‭example,‬‭writing‬‭up‬‭a‬‭dedicated‬‭function‬‭file‬‭to‬‭create‬‭a‬
‭standard‬ ‭user-defined‬ ‭function‬ ‭is‬ ‭somewhat‬ ‭inefficient.‬ ‭Anonymous‬ ‭functions‬ ‭can‬‭address‬
‭this.‬‭‬‭Anonymous‬ ‭functions‬ ‭provides‬ ‭flexibility‬ ‭to‬ ‭create‬ ‭a‬ ‭function‬ ‭"on-the-fly"‬ ‭without‬ ‭a‬
‭function file.‬

‭Some distinguishing features of anonymous functions are:‬


‭●‬ ‭They are a single-line function.‬
‭●‬ ‭When you create an anonymous function, a function handle is returned. This is the‬
‭name that is used to call the function.‬
‭●‬ ‭They can have many input arguments but can only return one output.‬
‭●‬ ‭Most often, this type of function is‬‭used to represent‬‭mathematical expressions‬

T‭ he syntax to create an anonymous function is:‬


fn_handle = @(inputs) <command>‬

‭Some examples of anonymous functions are shown below:‬

‭Figure 4.22: Examples of anonymous functions‬

‭ ideo Link 4.8: Further explanations and examples of how to create and use custom‬
V
‭functions in Matlab. (17 mins)‬

‭12‬

You might also like