introduction to programming using matlab

60
INTRODUCTION TO PROGRAMMING USING MATLAB Ela Pekalska, Marjolein van der Glas Pattern Recognition Group, Faculty of Applied Sciences Delft University of Technology August-November 2000 Send comments to [email protected]

Upload: ven-viv-gumpic

Post on 20-Dec-2015

96 views

Category:

Documents


5 download

DESCRIPTION

This is an introduction to programming using Matlab.

TRANSCRIPT

Page 1: Introduction to Programming Using Matlab

INTRODUCTION TO PROGRAMMING USING MATLAB

Ela Pekalska Marjolein van der GlasPattern Recognition Group Faculty of Applied Sciences

Delft University of TechnologyAugust-November 2000

Send comments to elaphtntudelftnl

Contents

Introduction 1

Preliminaries 3

1 How to work with Matlab 311 Input via the command-line 412 help-facilities 513 Interrupting a command or program 514 Path 615 Workspace issues 616 Saving and loading data 6

2 Mathematics with numbers vectors and matrices 7

21 Single numbers 722 An introduction to floating-point numbers 823 Assignments and variables 824 Vectors 925 Matrices 11

3 Visualization 17

31 Simple plots 1732 Several functions in one figure 1733 Other 2D plotting features - optional 1834 Printing 18

4 Curve fitting and interpolation 1941 Curve fitting 1942 Interpolation 205 Numerical analysis 2051 Evaluation of a function 2052 Integration and differentiation 216 Control flow 2161 Logical and relational operators 2262 Conditional code execution 2363 Loops 2464 Evaluation of logical and relational expressions in the control flow structures 2565 Numerical analysis and the control flow structures - optional 267 Text 2771 Character strings 2772 Text input and output 288 Cell arrays and structures - optional 3081 Cell arrays 3082 Structures 319 Script and function m-files 3391 Script m-files 3392 Function m-file 34921 Special function variables 36922 Local and global variables 37923 Indirect function evaluation - optional 3793 Scripts vs functions 3910 Optimizing the performance of Matlab code 39101 Vectorization - speed-up of computations 39102 Array preallocation 4011 File inputoutput operations 41111 Text files 42112 Binary files - optional 4312 Writing and debugging Matlab programs 44121 Structural programming 44122 Debugging 46123 Recommended programming style 46

INTRODUCTION

During this course you will learn how to use Matlab to design and to perform mathematical computations

You will also get acquainted with basic programming If you learn to use this program well you will find it very useful in future since many technical or mathematical problems can be solved using Matlab

This text includes all material (with some additional information) that you need to know however many things are treated briefly Therefore ldquoThe Student Edition of Matlabrdquo userrsquos guide should be used as a complementary book during the course A sign of a book accompanied by page numbers placed in the left margin indicates where you can find more information Read the suggested pages to better understand the concepts discussed Where no reference to the book appears it means that only this text explains some ideas since they might be more about general programming than about Matlab Exercises are marked with also in the left margin The end of an exercise is marked with _

The text of this course includes some optional parts for volunteers or for more advanced students Such a part is enclosed between two horizontal lines with the word rsquooptionalrsquo on the first line There are also rsquointermezzorsquo parts which are not essential but provide some important information If you already know how to program in a language like Pascal or C you then may find it easier or more interesting to do the optional parts as well However if you do not have any idea about programming please feel free to skip those fragments It is important that you spend enough time to learn the Matlab basics that are introduced in the first few sections If you notice that you need more time than laboratory hours please consider doing some examples during the rest of the time

Since learning Matlab is a challenging task you are encouraged to prepare each laboratory you may read a part of text at home or try the examples yourself This way you can use laboratory time to ask questions in order to make things become clearer to you We suggest the following schedule for this course However you are free to decide about your own speed taking into account that on the 5th or 6th day you have to be able to start with the final assignment

DAY 1 SECTIONS 1 ndash 3

At the end of day 1 you should be able tobull recognize built-in variablesbull define variables and perform computations using thembull know how to suppress display with (semicolon)bull add and remove variables from the workspace check which variables are currently present in theworkspacebull use on-line help to get more information on a command and know how to use the lookfor commandbull use the load and save commands to readsave data to a filebull access files at different directories (manipulate path-changing commands)bull create vectors and matrices with direct assignment (using [ ])bull use linspace to create vectorsbull create random vectors and matricesbull extract elements from vectors and matrices with subscript notation eg x(5) A(ij)bull use colon notation to create vectors and extract ranges of elements from vectors and matricesbull apply transpose operators to vectors and matricesbull perform legal addition subtraction and multiplication operations on vectors and matricesbull understand the use of array operators like + and know why they are different from the regular + operatorsbull compute inner products and the Euclidean length of vectorsbull advanced create and manipulate complex vectors and matricesbull optional delete elements from vectors and matricesbull use the plot function to make simple plots and to plot several functions in one figurebull optional make some fancy plotsbull send figures to the printer or print them to a file

Remark If you do not have enough time to exercise on matrix operations next time you should start fromsection 25 However it would be very useful if you could already try things before that time

DAY 2 SECTIONS 4 - 6

At the beginning you should exercise once again with operations on matrices (section 25) Since they areessential in Matlab be sure that you fully understand how to perform themAt the end you should be able to

bull understand better the operations on vectors and matricesbull create and manipulate Matlab polynomialsbull fit a polynomial to databull evaluate a function integrate and differentiate itbull use relational operators lt lt= gt gt= == ~= and logical operators amp | and ~bull use if end if elseif end and if elseif else end and switch constructionsbull use for-loops and while-loops and know the difference between thembull understand how logical expressions are evaluated in the control flow structuresbull optional understand how to make approximations of Taylor expansions with the given precision

DAY 3 SECTIONS 7 ndash 9

At the beginning you should exercise once again with the control flow structures (section 61-64) since they are rsquobuilding blocksrsquo of programs that you will have to createAt the end you should be able to

bull understand better the control flow structuresbull create and manipulate string variables eg compare two strings concatenate them find a substring in a string convert a numberstring into a stringnumber etcbull use freely and with understanding the text inputoutput commands input disp and fprintfbull optional operate on cell arrays and structuresbull edit and run an m-file (both functions and scripts)bull identify the differences between scripts and functionsbull understand the concept of local and global variablesbull create a function with one or more input arguments and one or more output argumentsbull use comment statements to document scripts and functionsbull optional use the feval command - know how to pass a function name as an input argument to another function

DAY 4 SECTIONS 10 - 12 + EXERCISING ON WRITING FUNCTION M-FILES

At the end you should be able tobull understand better how to build function m-filesbull preallocate memory for vectors or matrices and know why and when this is beneficialbull replace basic loops with vectorized operationsbull use colon notation to perform vectorized operationsbull advanced use array indexing instead of loops to select elements from a matrixbull advanced use logical indexing and logical functions instead of loops to select elements from matricesbull perform low level input and output with fopen fscanf and fclosebull understand how to operate on text files (inputoutput operations)bull get more understanding on the use of fprintf while writing to a filebull optional understand how to operate on binary files (inputoutput operations)bull know and understand the importance of structural programming and debuggingbull know how to debug your programbull advanced write programs using the recommended programming style

Day 5

Polishing the knowledge and experiences gained with Matlab asking questions etc First steps in the directionof the final assignment

Day 6 - 7

The final assignment

PRELIMINARIES

Below you find a few basic definitions on computers and programming Please get acquainted with them since they introduce key concepts needed in the coming sections

bull A BIT (short for binary digit) is the smallest unit of information on a computer A single bit can hold only one of two values 0 or 1 More meaningful information is obtained by combining consecutive bits into larger units such as byte

bull A BYTE - a unit of 8 bits being capable of holding a single character Large amounts of memory are indicated in terms of kilobytes (1024 bytes) megabytes (1024 kilobytes) and gigabytes (1024 megabytes)

bull BINARY SYSTEM - a number system that has two unique digits 0 and 1 Computers are based on such a system because of its electrical nature (charged versus uncharged) Each digit position represents a different power of 2 The powers of 2 increase while moving from the right most to the left most position starting from 20 = 1 Here is an example of a binary number and its representation in the decimal system

10110 = 1 _ 24 + 0 _ 23 + 1 _ 22 + 1 _ 21 + 0 _ 20 = 16 + 0 + 4 + 2 + 0 = 24

bull DATA is information represented with symbols eg numbers words signals or images

bull A COMMAND is an instruction to do a specific task

bull An ALGORITHM is a sequence of instructions for the solution of a specific task in a finite number of steps

bull A PROGRAM is the implementation of an algorithm suitable for execution by a computer

bull A VARIABLE is a container that can hold a value For example in the expression x+y x and y are variables They can represent numeric values like 255 characters like rsquocrsquo or character strings like rsquoMatlabrsquoVariables make programs more flexible When a program is executed the variables are then replaced with real data That is why the same program can process different sets of data Every variable has a name (called the variable name) and a data type A variablersquos data type indicates the sort of value that the variable represents (see below)

bull A CONSTANT is a value that never changes That makes it the opposite of a variable It can be a numeric value a character or a string

bull A DATA TYPE is a classification of a particular type of information The most basic data types are- integer a whole number a number that has no fractional part eg 3- floating-point a number with a decimal point eg 35 or 12e-16 (this stands for 12 _ 10minus16)- character readable text character eg rsquoprsquo

bull A BUG is an error in a program causing the program to stop running not to run at all or to provide wrong results Some bugs can be very subtle and hard to find The process of finding and removing bugs is called debugging

bull A FILE is a collection of data or information that has a name stored in a computer There are many different types of files data files program files text files etc

bull An ASCII FILE is a standardized readable and editable plain text file

bull A BINARY FILE is a file stored in a format which is computer-readable but not human-readable Most numeric data and all executable programs are stored in binary files Matlab binary files are those with the extension rsquomatrsquo

1 How to work with Matlab

Matlab is a tool for mathematical (technical) calculations First it can be used as a scientific calculator it provides simple mathematical operations but handles complex numbers powers logarithms trigonometric operations as well Next it allows you to plot or visualize data in many different ways perform matrix algebra work with polynomials or integrate functions Like in a programmable calculator you can create execute and save a sequence of commands in order to make your computational process automatic It can be used to

store or retrieve data In the end Matlab can also be treated as a user-friendly programming language which gives the possibility to handle mathematical calculations in an easy wayRunning Matlab creates one or more windows on your screen The most important is the Matlab Command Window which is the place where you interact with Matlab The string gtgt is the Matlab prompt (except for the Student Edition that has the EDUgtgt prompt) When the Command window is active a cursor appears after the prompt indicating that Matlab is waiting for your command which can be eg 173 or cos(x)

11 Input via the command-line2-10 Matlab is an interactive system commands followed by Enter are executed immediately The results are ifdesired displayed on screen However execution of a command will not be possible or will go wrong when thecommand is not typed according to the rules Table 1 shows a list of commands used to solve the indicatedmathematical equation (a b x and y are numbers)There are also commands that perform a specific task such as help work with a file-system like cd or workwith matrices like rank Below you find basic information that is important when starting with Matlabbull Commands in Matlab are executed by pressing Enter or Return The output will be displayed onscreen immediately Try the followinggtgt 3 + 75gtgt 184gtgt 3 7Note that spaces are not important in Matlabbull The result of the last execution is called ans It can be used on the next command line Try for instancegtgt 144ans =35000gtgt ans^(-6)ans =54399e-0454399e-04 is a computer notation of 54399 _ 10minus4 (see Preliminaries) Note that ans is always overwrittenby the last commandbull ans is an example of a Matlab built-in variable It stores the result of the recently performed computationYou can also define your own variables Look how the information is stored in the variables aand bgtgt a = 144a =35000gtgt b = a^(-6)b =54399e-04Read Preliminaries to better understand the concept of variables You will learn more on Matlabvariables in section 23bull When the command is followed by a semicolon () the output is suppressed Check the differencebetween the following expressionsgtgt 3 + 75gtgt 3 + 75gtgt x = 34bull It is possible to execute more than one command at the same time the separate commands should thenbe divided by commas (to display the output) or by semicolons (to suppress the output display) eggtgt sin(pi4) cos(pi) sin(0)ans =07071ans =0Note that the value of cos(pi) is not printedbull The output may contain some empty lines this can be suppressed by the command format compactIn contrast the command format loose will insert extra empty lines4Mathematical notation Matlab-commanda + b a + ba minus b a - bab a b3xy 3 x ya

b a b or b a

ab a^bpx sqrt(x) or x^05_ pie exp(1)i i4 middot 103 4e3 or 410^33 minus 4i 3 - 4i or 3 - 4jsin x arctan x sin(x) atan(x) ex exp(x)ln x log(x)log x log10(x)|x| abs(x)Table 1 Translation of mathematical notation to Matlab commandsbull Matlab is case sensitive There is a difference between capital and normal letters for example a iswritten as a in Matlab A will result then in an errorbull All text after a percent sign until the end of a line is treated as a comment Enter eg the followinggtgt sin(314159) this is an approximation of sin(pi)You will notice that some examples in this text are followed by comments They are meant for you andyou should skip them while typing those examplesbull Previous commands can be fetched back with the -key The command can also be changed the and -keys may be used to move around in a line and edit itKeep in mind that Matlab executes the command immediately it might be useful to have an idea of theexpected outcome12 help-facilitiesMatlab provides assistance through extensive online help The help command is the simplest way to get349-359 help that is if you know the topic or command on which you want help For examplegtgt help elfungives information on the elementary math functions of Matlab The command help displays a list of allpossible topics The topic you want help on must be exact and spelled correctly The commando lookfor ismore useful if you do not know the exact name of the command or topic For examplegtgt lookfor inversedisplays all commands for which the word inverse is included in its help-text This command results in a list ofcommands with a short description Besides the help and lookfor commands there is also a separate mousedriven help The helpwin command opens a new window on screen which can be browsed in an interactiveway To learn more read pages 353-354 from rdquoThe Student Edition of Matlabrdquobook13 Interrupting a command or programSometimes you might spot an error in your command or program Due to this error it can happen that thecommand or program does not stop Pressing Ctrl-C forces Matlab to stop the process After this theMatlab-prompt (gtgt) re-appears This may take a while though514 PathIn Matlab commands or programs are contained in m-files which are just plain text files and have an37-39 extension rsquomrsquo The m-file must be located in one of the directories which Matlab automatically searchesThe list of these directories can be listed by the command path One of the directories that is always takeninto account is the current working directory which can be identified by the command pwd Use path addpathand rmpath functions to modify the path Here is an examplegtgt pathcmatlabcmatlabtoolboxmatlabgeneralcmatlabtoolboxmatlabopsgtgt addpath hpersonal assume that this is your directorygtgt pathhpersonalcmatlabcmatlabtoolboxmatlabgeneralcmatlabtoolboxmatlabopsIt is also possible to access the path browser from the File menu-bar instead15 Workspace issuesIf you work in the Command Window Matlab memorizes all commands that you entered (as you alreadyknow - to recall previous commands the -key is useful) and all variables that you created This can be6

2425verified with the commands who which gives a list of variables present in the workspace and whos whichincludes information on name number of allocated bytes and class of the variables For example assuming thatyou performed all commands given in the beginning after typing who you should get the following informationgtgt whoYour variables area ans b xThe command clear ltnamegt deletes the variable ltnamegt from the Matlab workspace clear or clear allremoves all variables This is useful when starting a new exercise For examplegtgt clear a xgtgt whoYour variables areans b16 Saving and loading dataThe easiest way to save or load Matlab variables is by using (clicking) the File menu-bar and then the Save26 Workspace as and Load Workspace items Also Matlab commands exist which allow you to saveand load data from filesThe command save allows for saving your workspace variables either into a binary file or an ASCII file (checkPreliminaries on binary and ASCII files) Binary files automatically get the rsquomatrsquo extension which is nottrue for ASCII files However it is recommended to add a rsquotxtrsquo or dat extensionExercise 1Learn how to use the save command by exercisinggtgt s1 = sin(pi4) s2 = sin(pi2)gtgt c1 = cos(pi4) c2 = cos(pi2)gtgt str = rsquohello worldrsquo this is a string example you will learn about strings latergtgt save saves all variables in binary format to the file matlabmatgtgt save data saves all variables in binary format to the file datamat6gtgt save numdata s1 c1 saves numeric variables s1 and c1 to the file numdatamatgtgt save strdata str saves a string variable str to the file strdatamatgtgtgtgt save allsin s saves all variables that match the pattern to allsinmatgtgt save allcosdat c -ascii saves c1c2 in 8-digit ascii format to allcosdat_The load command allows for loading variables into the workspace It uses the same syntax as saveExercise 2Assuming that you have done the previous exercise try to load variables from the created filesImportant before each load command clear the workspace and after loading check which variables arepresent in the workspace (using who)gtgt load loads all variables from the file matlabmatgtgt load data s1 c1 loads only specified variables from the file datamatgtgt load strdata loads all variables from the file strdatamatIt is also possible to read ASCII files that contain rows of space separated values Such a file may containcomments that begin with a percent character The resulting data is placed into a variable with the samename as the ASCII file (without the extension) Check for examplegtgt load allcosdat loads data from the file allcosdat into variable allcosgtgt who lists variables present in the workspace now_

2 Mathematics with numbers vectors and matricesThe basic element of Matlab is a matrix (or an array) Special cases arebull a 1 times 1-matrix a scalar or a single numberbull a matrix existing only of one row or one column a vector21 Single numbersYou have already got some experience with Matlab and you know that it can be used as a calculator To do4-614-1727that you can for example simply typegtgt 31256The result will beans =55714By default Matlab displays only 5 digits The command format long increases this number to 15 format

short reduces it to 5 again For examplegtgt format longgtgt 31256ans =557142857142857Exercise 3Define the format Matlab such that empty lines are suppressed and the output is given with 5 digitsCalculategtgt pigtgt sin(pi)Note that the answer is not exactly 0 _Use the command format to put Matlab in its standard-format ie short and loose7intermezzo

22 An introduction to floating-point numbersIn a computer numbers can be represented only in a discrete form It means that numbers are stored286 within a limited range and with a finite precision Integers can be represented exactly with the base of 2(read Preliminaries on bits and the binary system) The typical size of an integer is 16 bits so the largestpositive integer which can be stored is 216 = 65536 If negative integers are permitted then 16 bits allow forrepresenting integers between minus32768 and 32767 Within this range operations defined on the set of integerscan be performed exactlyHowever this is not valid for other real numbers In practice computers are integer machines and are capableof representing real numbers only by using complicated codes The most popular code is the floating pointstandard The term floating point is derived from the fact that there is no fixed number of digits before andafter the decimal point meaning that the decimal point can float Note that most floating-point numbers thata computer can represent are just approximations Therefore care should be taken that these approximationslead to reasonable results If a programmer is not careful small discrepancies in the approximations can causemeaningless results Note the difference between eg the integer arithmetic and floating-point arithmeticInteger arithmetic Floating-point arithmetic2 + 4 = 6 187 = 257143 4 = 12 25714 7 = 1799982511 = 2 100003 = 33333e+03When describing floating-point numbers precision refers to the number of bits used for the fractional partThe larger the precision the more exact fractional quantities can be represented Floating-point numbers areoften classified as single precision or double precision A double-precision number uses twice as many bits asa single-precision value so it can represent fractional values much better However the precision itself is notdouble The extra bits are also used to increase the range of magnitudes that can be representedMatlab relies on a computerrsquos floating point arithmetic You could have already noticed that in the last408-410 exercise since the value of sin(_) was almost zero and not completely zero It came from the fact that boththe value of _ is represented with a finite precision and the sin function is also approximatedThe fundamental type in Matlab is double which stands for a representation with a double precision It uses64 bits The single precision obtained by using the single type offers 32 bits Since most numeric operationsrequire high accuracy the double type is used by defaultThe exact machine precision might be defined as the smallest positive number _ that added to 1 does notchange the result so 1 + _ = 1 in floating-point arithmetic this value is larger than zero (in exact arithmeticof course _ = 0 holds) Matlab machine precision is stored in the built-in variable eps _ 22204e-16 Thismeans that the relative accuracy of individual arithmetic operations is about 16 digitsend intermezzo

23 Assignments and variablesWorking with complex numbers is easily done with MatlabExercise 4Choose two complex numbers for example -3 + 2i and 5 - 7i Try to add subtract multiply and dividethese two numbers _During this exercise the complex numbers had to be typed four times To reduce this assign each number to4-610-12a variable For the previous exercise this results ingtgt z = -3 + 2igtgt w = 5 - 7igtgt y1 = z + w y2 = z - w y3 = z w y4 = z w y5 = w zFormally there is no need to declare (ie define the name size and the type of) a new variable in Matlab Avariable is simply created by an assignment (the way it has been done above) Each newly created numerical

variable is always of the double type You can change this type by converting it into eg the single type 11a variable a is converted into a different type by performing eg a = single(a) a = int16(a) etc8In some cases when huge matrices should be handled and precision is not very important this might be a wayto proceed Also when only integers are taken into consideration it might be useful to convert the doublerepresentations into eg int16 or int321 integer types Since most computations should be performed with ahigh accuracy Matlab automatically chooses the double type It means that real numbers are approximatedwith the highest possible precision However it is important to emphasize that integer numbers are alwaysrepresented exactly no matter which numeric type is usedBear in mind that undefined values cannot be assigned to a variable So the following is not possiblegtgt clear x to make sure that x does not existgtgt fun = x^2 + 4 sin (x)It becomes possible bygtgt x = pi 3 fun = x^2 + 4 sin (x)Exercise 5Predict the result ofx = pi 3 x = x - 1 x = x + 5 x = abs(x) xCheck your prediction by performing these commands in Matlab _Exercise 6Here are some examples of different types of Matlab variables You do not need to understand them all nowsince you will learn more about them during the course Create them manually in Matlabgtgt this_is_my_very_simple_variable_today = 5 a number check what happens since thegtgt name is very long (gt 31 characters)gtgt 2t = 8 what is the problem with this commandgtgt this_is_a_matrix = [1 2 3 4 5 6] a matrixgtgt c = rsquoErsquo a charactergtgt str = rsquoHello worldrsquo a stringgtgt m = [rsquoJrsquorsquoorsquorsquohrsquorsquonrsquo] try to guess what it isCheck the types by using the command whos Use clear ltnamegt to remove a variable from the workspace _Exercise 7In addition to creating variables by assigning values to them a few other ways exist For instance there is anumber of built-in variables eg ans pi eps i inf or nan Find out what value is assigned to each of these74584 built-in variables _24 VectorsRow vectors are lists of numbers separated either by commas or by spaces They are examples of simple arrays41-49 The number of entries is known as the length of the vector (the command length exists as well) Their entitiesare referred to as elements or components The entries must be enclosed in [ ]gtgt v = [-1 sin(3) 7]v =-10000 01411 70000gtgt length(v)ans =3A number of operations can be done on vectors A vector can be multiplied by a scalar or addedsubtractedtofrom another vector with the same length or a number can be addedsubtracted tofrom a vector Allthese operations are carried out element-by-element Vectors can be also built from the already existing onesgtgt v = [-1 2 7] w = [2 3 4]gtgt z = v + w an element-by-element sumz =1 5 119gtgt v3 = v + 2 add 2 to all elements of vector v3v3 =1 4 9gtgt t = [2v -w]ans =-2 4 14 -2 -3 -4Also a particular value can be changed or displayedgtgt v(2) = -1 w(2) change the 2nd value of v display the 2nd value of wv =-1 -1 7ans =

3A colon notation is an important shortcut used when producing row vectors (see Table 3 and help colon)gtgt 25ans =2 3 4 5gtgt -23ans =-2 -1 0 1 2 3In general firststeplast produces a vector of entities with the value first incrementing by the stepuntil it reaches lastgtgt 020524ans =02000 07000 12000 17000 22000gtgt -3310ans =-3 0 3 6 9gtgt 15-05-05 negative step is also possibleans =15000 10000 05000 0 -05000Parts of vectors can be extracted by using a colon notationgtgt r = [-126 2 3 -2] -126 =gt -1 1 3 5r =-1 1 3 5 2 3 -2gtgt r(36) get elements of r which are on the positions from 3 to 6ans =3 5 2 3gtgt r(125) get elements of r which are on the positions from 1 to 5 taken with the step of 2ans =-1 3 2gtgt r(5-12) what will you get hereTo create column vectors you should separate entries by a semicolon () or by new linesgtgt f = [-1 3 5]f =-135The same operations as on row vectors can be done on column vectors However you cannot for exampleadd a column vector to a row vector To do that you need an operation called transposing which converts acolumn vector into a row vector and vice versa10gtgt f = [-1 3 5] a column vectorgtgt frsquo frsquo is a row vectorans =-1 3 5gtgt v = [-1 2 7] a row vectorgtgt f + v you cannot add a column vector f to a row vector v Error using ==gt +Matrix dimensions must agreegtgt frsquo + vans =-2 5 12gtgt f + vrsquoans =-2512If x is a complex vector than xrsquo gives the conjugate transpose of x eggtgt x = [1+2i -1+i]x =10000 + 20000i -10000 + 10000igtgt xrsquo this is the conjugate transposeans =10000 - 20000i-10000 - 10000i

gtgt xrsquo this is the rsquonormalrsquo transposeans =10000 + 20000i-10000 + 10000iExercise 8Exercise to become acquainted with operating on row and column vectors Enter all examples given in thissection and make new variations yourself Exercise with the colon notation approach as well _25 MatricesAn ntimesk matrix is a rectangular array of numbers having n rows and k columns Defining a matrix in Matlabis similar to defining a vector The generalization is straightforward if you know that a matrix consists of row49-6175-86vectors (or column vectors) Commas or spaces are used to separate elements in a row and semicolons areused to separate individual rows For example the matrix A =01 2 34 5 67 8 91Ais defined asgtgt A = [1 2 3 4 5 6 7 8 9] row by row inputA =1 2 34 5 67 8 9Another examples are for instancegtgt A2 = [14 -125]A2 =1 2 3 4-1 1 3 5gtgt A3 = [1 3-4 7]A3 =1 3-4 711Command ResultA(ij) Aij

A(j) j-th column of AA(i) i-th row of AA(klmn) (l minus k + 1) times (n minus m + 1) matrix with elements Aij with k _ i _ l m _ j _ nv(ij)rsquo rsquovector-partrsquo (vi vi+1 vj) of vector vTable 2 Manipulation of (groups of) matrix-elementsCommand Resultn = rank (A) n becomes the rank of matrix Ax = det (A) x becomes the determinant of matrix AC = size (A) C becomes a row-vector with 2 elements the number of rows and columns of Ax = trace (A) x becomes the trace (sum of diagonal elements) of matrix Ax = norm (v) x becomes the length of vector vC = A + B sum of two matricesC = A - B subtraction of two matricesC = A B multiplication of two matricesC = A B rdquoelement-by-elementrdquo multiplication (A and B are of equal size)C = A ^ k power of a matrix (k 2 Z can also be used for Aminus1)C = A ^ k rdquoelement-by-elementrdquo power of a matrixC = Arsquo the transposed of a matrix AT

C = A B rdquoelement-by-elementrdquo division (A and B are of equal size)U = A B finds the solution that minimizes the squared error in Ax minus BU = B A solution of XA = B analogous to the previous commandC = inv (A) C becomes the inverse of AC = null (A) C is an orthonormal basis for the null space of Aobtained from the singular value decompositionC = orth (A) C is an orthonormal basis for the range of AC = rref (A) C is the reduced row echelon form of AL = eig (A) L is a vector containing the -possibly complex- eigenvalues of a square matrix A[X D] = eig (A) produces a diagonal matrix D of eigenvalues and a full matrix X

whose columns are the corresponding eigenvectors of AS = svd (A) S is a vector containing the singular values of A[U S V] = svd (A) S is a diagonal matrix of the same dimension as Awith nonnegative diagonal elements in decreasing orderThe columns U and V are the accompanying singular vectorsx = linspace(a b n) generates a vector x of n equally spaced points between a and bx = logspace(a b n) generates a vector x starting at 10a and ended at 10b containing n valuesA = diag (v) gives a diagonal matrix with the elements v1 v2 vn on the diagonalA = eye (n) A is a n times n identity matrixA = zeros (n m) A is a n times m matrix with zeros (default m = n)A = rand (n m) A is a n times m matrix with elements uniformly distributed between 0 and 1A = randn (n m) ditto - with elements standard normal distributedv = max (A) v becomes a vector with the maximum value of the elements in each column of Aor v is the maximum of all elements if A is a vectorv = min (A) ditto - with minimumv = sum (A) ditto - with sumTable 3 Frequently used matrix operations and functions12Transposing a vector changes it from a row to a column or the other way around This idea can be extendedto a matrix where transposing interchanges rows with the corresponding columns as in the examplegtgt A2 A2rsquoA2 =1 2 3 4-1 1 3 5ans =1 -12 13 34 5gtgt size(A2) returns the size (dimensions) of a matrixans =2 4gtgt size(A2rsquo)ans =4 2There exists also some built-in matrices of size specified by the user (see Table 2) A few examples are givenbelowgtgt E = [] an empty matrix of 0-by-0 elementsE =[]gtgt I = eye(3) the identity matrixI =1 0 00 1 00 0 1gtgt B = rand(23) a matrix of random numbers you will get a different one00227 09101 0922200299 00640 03309gtgt O = ones(32)O =1 11 11 1gtgt r = [1 3 -2] R = diag(r) create a diagonal matrix with r on the diagonalR =1 0 00 3 00 0 -2gtgt v = linspace(124) a vector is also an example of a matrixv =10000 13333 16667 20000It is often needed to build a larger matrix from the smaller onesgtgt x = [4 -1] y = [-1 4]x =4

-1y =-1 4gtgt X = [x yrsquo] X consists of the columns x and yrsquoX =4 -1-1 4gtgt T = [ -1 3 4 4 5 6] t = 1313gtgt T2 = [T t] add to T a new row namely the row vector t getting T2T2 =-1 3 44 5 61 2 3gtgt G = [1 5 4 5 0 2] G is a matrix of the 3-by-2 size check size(G)gtgt T3 = [T2 G] T3 consists of T2 and new columns being the colums of GT3 = added at the end of T2-1 3 4 1 54 5 6 4 51 2 3 0 2gtgt [diag(56) ones(32)]ans =5 00 61 11 11 1A part can be extract from a matrix in a similar way as from a vector Each element in the matrix is indexedby a row and a column to which it belongs Mathematically the element from the i-th row and the j-thcolumn of the matrix A is denoted by Aij Matlab provides the A(ij) notationgtgt A = [13 46 79]A =1 2 34 5 67 8 9gtgt A(12) A(23) A(31)ans =2ans =6ans =7gtgt A(43) A is a 3-by-3 matrix Index exceeds matrix dimensionsgtgt A(23) = A(23) + 2A(11)A =1 2 34 5 87 8 9Having defined a matrix it is easy to extended it automatically For the matrix A it can be done eg asfollowsgtgt A(52) = 5 assign 5 to the position (52) the uninitializedA = elements become zeros1 2 34 5 87 8 90 0 00 5 0Different parts of the matrix A can be now extractedgtgt A(2) extract the 2nd column of Aans =25814

05gtgtgt A(34) extract the rows 3rd and 4th of Aans =7 8 90 0 0gtgt A(2312) extract a part of Aans =4 57 8If needed the other zero elements of the matrix A can be also defined by eggtgt A(4) = [1 2 3] assign vector [1 2 3] to the 4th row of Agtgt A(5[13]) = [4 5] a rsquoshortcutrsquo when assigning A(51) = 4 and A(53) = 5gtgt A how does the matrix A look like nowAs you have seen in the examples above it is possible to manipulate (groups of) matrix-elements Thecommands are shortly explained in Table 2Exercise 9Define the matrix A = [14 58 1 1 1 1] Predict and check the result ofgtgt B = A(3)gtgt C = A(1322)gtgt A(11) = 9gtgt A(2313) = [0 0 0 0 0 0]gtgt A(l212) = [l l 3 3]gtgt A = A(3314)_Exercise 10Define the matrices T=[ 3 4 1 8 -4 3] A = [diag(-123) T -4 4 1 2 1] Perform the followingoperations on the matrix Abull extract a vector consisting of the 2nd and 4th elements of the 3rd rowbull find the minimum of the 3rd columnbull find the maximum of the 2nd rowbull compute the sum of the 2nd columbull compute the mean of the 1st and 4th rowsbull extract the submatrix consisting of the 1st and 3rd rows and all columnsbull extract the submatrix consisting of the 1st and 2nd rows and the 3rd 4th and 5th columnsbull compute the total sum of the 1st and 2nd rowsbull add 3 to all elements of the 2nd and 3rd colums_Table 3 shows some frequently used matrix operations and functions A few examples are provided belowgtgt B = rand(23) a matrix of random numbers you will get a different oneB =09501 06068 0891302311 04860 07621gtgt B2 = [1 2 5 1 5 6]gtgt B + B2rsquo add two matrices why B2rsquo is needed instead of B2ans =19501 56068 5891322311 14860 67621gtgt S = ans4 divide all elements of the matrix ans by 4S =04875 14017 1472805578 03715 1690515gtgt C = [1 -1 4 7 0 -1]gtgt B C matrix multiplication is not defined for B and C Error using ==gt Inner matrix dimensions must agreegtgt B C but you can multiply element-by-elementans =09501 -06068 3565216180 0 -07621gtgt D = B Crsquo or you can make the multiplication legal Crsquo is now 3-by-2D =39085 5759627935 08559

gtgt D^3 this is equivalent to D D Dans =1992503 2041413990133 910548gtgt D^3 - 2 do for all elements raise to the power 3 and subtract 2ans =577069 1890638198005 -13731gtgtgtgt r = [1 3 -2]r B2 this is a legal operation r is a 1-by-3 matrix and B2 isans = 3-by-2 matrix B2 r is an illegal operation6 -7Remind that an n-by-k matrix A (having n rows and k columns) can be multiply by another matrix B onlyif B has k rows ie S is of the k-by-m size (m is arbitrary) As a result you get an n-by-m matrixA ˙B = C A 2 Rntimesk B 2 Rktimesm C 2 Rntimesm

RemarkYou can now compute the inner product between two vectors x and y xT y = Pi xi yi in a simple waygtgt f = [-1 3 5] a column vectorgtgt v = [-1 2 7] a column vectorgtgt frsquo v this is the inner productans =42gtgt f vrsquo be careful now a 3-by-1 matrix is multiplied by a 1-by-3gtgt matrix which results in a 3-by-3 matrix (the outer product)ans =1 -2 -7-3 6 21-5 10 35gtgt f v this is an element-by-element multiplication1635gtgt sum (f v) this is an another way to compute the inner productans =42Exercise 11Perform all operations from Table 3 using chosen matrices A and B vector v and scalars k a b n and m _Exercise 12Let A be a random 3 times 3 matrix and b a random 3 times 1 vector Given that Ax = b then x = Aminus1b Find x(there exist at least two possible commands to do this look at Table 3) _optionalThe concept of an empty matrix [] is also very useful in Matlab For instance a few columns or rows canbe removed from a matrix by assigning an empty matrix to it Try for example16Symbol Color Symbol Styley yellow dotted liner red o circlesg green - solid lineb blue - dashdotted lineTable 4 Plot colors and stylesgtgt C = [1 2 3 4 5 6 7 8 1 1 1 1]gtgt D = C D(2) = [] now a copy of C is in D remove the 2nd column of Dgtgt C ([13]) = [] remove the rows 1 and 3 from Cend optional

3 VisualizationMatlab can be used to visualize the results of an experiment Therefore you should define variables each ofthem containing all values of one parameter to plot31 Simple plotsWith the command plot a graphical display can be made plot(y) draws the points (1 y(1)) (2 y(2)) 184 (n y(n)) and connects the points with a straight line plot(xy) does the same for (x(1) y(1)) (x(2) y(2)) (x(n) y(n)) x and y have to be row- or column vectors of equal lengthThe commands loglog semilogx and semilogy are similar to plot except that they use logarithmic axesExercise 13Type the following commands after predicting the resultgtgt x = 0330

gtgt y = 2^[010] this is the same as y = [1 2 4 8 16 32 64 128 256 512 1024]gtgt plot(xy) to get a graphic representationgtgt semilogy(xy) to get logarithmic axesAs you can see the same figure is used for both plot commands The previous function is removed as soonas the next is displayed The command figure gives you an extra figure Repeat the previous commandsbut generate a new figure before plotting the second function so that you can see both functions in separatewindows You can also switch back to a figure using figure(n) where n is its number _Exercise 14Make a plot such that the coordinates (2 6) (25 18) (5 175) (42 125) and (212) are connected by aline _Exercise 15Plot the function y = sin(x) + x minus x cos(x) in two separate figures for the intervals 0 lt x lt 30 andminus100 lt x lt 100 _32 Several functions in one figureWhen more than one function is plotted in one figure it might be useful to use different markers and colors184-188197-201Table 4 shows a few possibilities help plot shows allThere are different ways to get more than one function into a figure The first one is with the command holdon After this command all functions will be plotted in the same figure until the command hold off is usedAn examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt plot (x1 y1 rsquordrsquo)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)17gtgt hold ongtgt plot (x2 y2 rsquoy-rsquo)gtgt plot (x1y1rsquok-rsquo)gtgt hold offA second method to display more than one function in one figure is to plot several functions at the same timeThe next commands will have the same results as the commands in the previous examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt plot (x1 y1rsquordrsquo x2 y2 rsquoy-rsquo x1 y1 rsquok-rsquo)It is also possible to get more than one figure in one figure window With the command subplot the windowcan be horizontally and vertically divided into any number of subfiguresgtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt subplot(131) plot (x1 y1rsquordrsquo)gtgt subplot(132) plot (x2 y2 rsquoy-rsquo)gtgt subplot(133) plot (x1 y1 rsquok-rsquo)optional

33 Other 2D plotting featuresIn the introduction of this chapter some commands similar to plot loglog semilogx and semilogy were201-211 mentioned There are however more ways to display dataExercise 16To get an impression of other visualizations type the following commands and describe the result (note thatthe command figure creates a new figure window)gtgt figure bar plot of a bell shaped curvegtgt x = -290229gtgt bar (x exp (-xx))gtgt figure stairstep plot of a sine wavegtgt x = 002510gtgt stairs (x sin (x))gtgt figure errorbar plotgtgt x = -2012gtgt y = erf (x) error function check help if you are interestedgtgt e = rand (size (x)) 10gtgt errorbar (x y e)

_end optional

34 PrintingBefore printing a figure you made you might want to add some information such as a title or change the189-196 lay-out a little Table 5 shows some of the commands that can be usedExercise 17Plot the functions y1 = sin(4x) y2 = x cos(x) y3 = (x + 1)minus1px for x = 0 025 10 and a single point(x y) = (4 5) in one figure with different colors and styles Make a legend containing the three functionsMake labels for both axes and a title Add a text to the single point saying single point Change the minimumand maximum values of the axes such that function y3 can be looked at in more detail _When the displayed figure is to your liking you can print it to paper The easiest way to do this is to click onFile in the menu-bar and to choose Print If in the print window you click OK your figure will be printed onthe printer indicated in the print window18Command Resultgrid onoff adds a grid to the plot at the tick marks or removes itaxis([xmin xmax ymin ymax]) sets the minimum and maximum values of the axesbox offon removes the axes box or shows itxlabel(rsquotextrsquo) plots the label text on the x axisylabel(rsquotextrsquo) plots the label text on the y axistitle(rsquotextrsquo) plots a title above the graphtext(xyrsquotextrsquo) adds text at the point (xy)gtext(rsquotextrsquo) adds text at a manually (with a mouse) indicated pointlegend(rsquofun1rsquorsquofun2rsquo) plots a legend box (move it with your mouse) to name your functionslegend off deletes the legend boxTable 5 Plot-manipulationsThere is also a print command which can be used to send a figure to a printer or output it to a file Youcan optionally specify a print device (ie an output format such as tiff or postscript) and options that controlvarious characteristics of the printed file (ie which Figure to print etc) You can also print to a file if youspecify the file name If you do not provide an extension print adds one Since they are many parametersthey will not be explained here (check help print to learn more) Instead try to understand the examplesgtgt print -dwinc print the current Figure to the current printer in colorgtgt print -f1 -deps myfileeps print Figure no1 to the file myfileeps in blackgtgt print -f1 -depsc myfileceps print Figure no1 to the file myfilecoleps in colorgtgt print -dtiff myfile1tiff print the current Figure to the file myfile1tiffgtgt print -dpsc myfile1cps print the current Figure to the file myfile1ps in colorgtgt print -f2 -djpeg myfile2 print Figure no2 to the file myfile2jpgExercise 18Exercise with printing (especially to a file) the figure from Exercise 16 _

4 Curve fitting and interpolationThere are two ways to describe data with an analytical function- curve fitting or regression finding a smooth curve that best fits (approximates) the data accordingto a criterion (eg best least square fit) The curve does not have to go through any of the data points- interpolation the data are assumed to be correct desired in a way to describe what happens betweenthe data points In other words given a finite set of points the goal of interpolation is to find a functionfrom a given class of functions (eg polynomials) which passes through the specified pointsThe figure below illustrates the difference between regression (curve fitting) and interpolationminus5 0 5minus6minus4minus20246810fiting a 3rd order polynomialinterpolation

41 Curve fittingMatlab interprets the best fit of a curve by the lsquoleast squares curve fittingrsquo The curve used is restricted153-15619to polynomials With the command polyfit any polynomial can be fitted to the data polyfit (x y n)finds the coefficients of a polynomial of degree n that fits the data (finds the linear relation between x and y)Letrsquos start with finding a linear regression of some datagtgt x = 010gtgt y = [-10 24 102 158 284 276 299 405 483 522 751]gtgt p = polyfit (x y 1) find the fitting polynomial of order 1p = 06772 -03914

The output of polyfit is a row vector of the polynomial coefficients the solution of this example is thereforey = 06772x minus 03914Exercise 19Execute the above example Plot the data and the fitted curve in a figure Determine the 2nd and 9th orderpolynomial of these data as well and display the solution in a figureHint x1 = linspace (xmin xmax n) results in a vector with n element evenly distributed from xmintill xmax z = polyval (p x1) calculates the values of the polynomial for every element of x1 _Exercise 20Define x and y as followsgtgt x = -55gtgt y = 02x^3 - x + 2 a 3rd order polynomialgtgt y = y + randn(111) add some noise to yDetermine the 3rd order polynomial fitting y (note that because of added noise the coefficients are differentthat originally chosen) Try some other polynomials as well Plot the results in a figure _42 InterpolationThe simplest way to examine an interpolation is by displaying the function plots with the command plot157-161 The neighboring data points are connected with straight lines This is called a linear interpolation Whenmore data-points are taken into account the effect of interpolation becomes less visible Analyzegtgt x1 = linspace(0 2pi2)gtgt x2 = linspace(0 2pi4)gtgt x3 = linspace(0 2pi16)gtgt x4 = linspace(0 2pi256)gtgt plot(x1sin(x1)x2sin(x2)x3sin(x3)x4sin(x4))gtgt legend(rsquo2 pointsrsquorsquo4 pointsrsquorsquo16 pointsrsquorsquo256 pointsrsquo)

5 Numerical analysisNumerical analysis can be used whenever it is impossible or very difficult to determine the analytical solutionMatlab can be used to find for example the minimum maximum or integral of a certain function51 Evaluation of a functionAs said before the command plot plots a function by connecting defined data points Sometimes however a168-173 function is constant and not very interesting over some range and then acts unexpectedly wildly over anotherWith plot this function might be misinterpreted The command fplot is then useful An examplegtgt x = 0pi82pigtgt y = sin (8x)gtgt plot (x y rsquobrsquo)gtgt hold ongtgt fplot (rsquosin (8z)rsquo [0 2pi] rsquorrsquo)gtgt title (rsquosin (8z)rsquo)gtgt hold off20Command Resultfplot (rsquofunrsquo [min x max x]) plots the function fun for min x till max xfmin (rsquofunrsquo min x max x) gives the x-value of the miminum of thefunction fun between min x and max xfzero (rsquofunrsquo x0) gives the x-value for which the functionfun is zero in the neighborhood of x0Table 6 Evaluation of a functionExecution of these commands results in a figure with an almost straight blue line and a red sine fplot canalso be used to plot a defined functiongtgt f = rsquosin (8z)rsquogtgt fplot (f [0 2pi] rsquorrsquo)gtgt title (f)Other useful commands for a detailed study of a range of a function are listed in Table 6Exercise 21The command fmax does not exist Use one or more of the commands from Table 6 to determine the maximumof the function x cos(x) for 10 lt x lt 15 _52 Integration and differentiationThe integral- or the surface underneath a 2D function- can be determined with the command trapz trapz173-182 does this by measuring the surface between the x-axis and the -by a straight line connected- data points Theaccuracy of this method depends on the distance between the data pointsgtgt x = 00510 y = 05 sqrt (x) + x sin (x) area1 = trapz (x y)

area1 =181655gtgt x = 000510 y = 05 sqrt (x) + x sin (x) area2 = trapz (x y)area2 =183846Differentiation is done by determining the slope in each data point Numerically this is done by first fitting apolynomial followed by differentiating this functiongtgt x = 010gtgt y = [-10 24 102 -158 284 276 775 35 483 522 751]gtgt p = polyfit (x y 5)p = 00026 -00554 03634 -06888 02747 00877gtgt dp = polyder (p)dp = 00132 -02216 10903 -13776 02747gtgt x1 = linspace (0 10 200)gtgt z = polyval (p x1)gtgt dz = polyval (dp x1)gtgt plot (x y rsquog-rsquo x1 z rsquobrsquo x1 dz rsquorrsquo)gtgt legend (rsquodata pointsrsquo rsquocurve fitrsquo rsquoderivativersquo)Exercise 22Determine the integral and derivative of the 4th polynomial fitted through (xy) with x = [4 5 6 7 8 9 1011 12 13] y = [1284 1200 724 -096 -1116 -2096 -2700 -2496 -956 2544] _

6 Control flowAs you know it is possible to execute more than one command at the same time (see section 11) Theseparate commands should then be divided by commarsquos (to display the output) or by semicolons (to suppress21output display) Control flow loops increase the number of possibilities A control flow structure is a block ofcommands that allows conditional code execution and making loops61 Logical and relational operatorsTo use control flow commands it is necessary to perform operations that result in logical values TRUE or88-91 FALSE In Matlab the result of a logical operation is 1 if it is true and 0 if it is false Table 7 shows therelational and logical operations2 Another way to get to know more about them is to type help relop Therelational operators lt lt= gt gt= == and ~= can be used to compare two arrays of the same size or anarray to a scalar The logical operators amp | and ~ allow for the logical combination or negation of relationaloperators In addition three functions are also available xor any and all (use help to find out more)Important The logical amp and | have the equal precedence in Matlab which means that those operatorsassociate from left to right A common situation isgtgt b = 10gtgt 1 | b gt 0 amp 0ans =0gtgt (1 | b gt 0) amp 0 this indicates the same as aboveans =0gtgt 1 | (b gt 0 amp 0)ans =1This shows that you should always use brackets to indicate in which way the operators should be evaluatedCommand Resulta = (b gt c) a is 1 if b is larger than c Similar are lt gt= and lt=a = (b == c) a is 1 if b is equal to ca = (b ~= c) a is 1 if b is not equal ca = ~b logical complement a is 1 if b is 0a = (b amp c) logical AND a is 1 if b = TRUE AND c = TRUEa = (b | c) logical OR a is 1 if b = TRUE OR c = TRUETable 7 Relational and logical operationsExercise 23Predict and check the result of each of the operations of Table 7 for b = 0 and c = -1 _Exercise 24Define two vectors with seven elements (randn(17)) and perform all logical operations including xor anyand all _Exercise 25While doing logical operations between a vector and a scalar each element of the vector is compared to thescalar Predict and check the result of each logical operator for the vector b = [2 31 -40 0] and the scalarc = 0 _Before moving on check whether you now understand the following relations

gtgt a = randperm(10) a random permutation of the numbers from 1 to 10gtgt b = 110gtgt b - (a lt= 7) subtracts from b a 0-1 vector taking 1 for a lt= 7 and 0 otherwisegtgt (a gt= 2) amp (a lt 4) returns ones at positions where 2 lt= a lt 4gtgt ~(b gt 4) returns ones at positions where b lt= 4gtgt (a == b) | b == 3 returns ones at positions where a is equal to b or b is equal to 3gtgt any (a gt 5) returns 1 when ANY of the a elements are larger than 5gtgt any (b lt 5 amp a gt 8) returns 1 when there in the evaluated expressiongtgt (b lt 5 amp a gt 8) appears at least one 1gtgt all (b gt 2) returns 1 when ALL b elements are larger than 22rdquoequal tordquo in the table on page 88 of rdquoThe Student Edition of Matlabrdquo must be rdquo==rdquo instead of rdquo=rdquo2262 Conditional code executionSelection control structures if-blocks are used to decide which instruction to execute next depending whether117-119 expression is TRUE or not The general description is given below In the examples below the command dispis frequently used This command displays on the screen the text between the quotesbull if endSyntaxif logical_expressionstatement1statement2endExampleif (a gt 0)b = adisp (rsquoa is positiversquo)endbull if else endSyntaxif logical_expressionblock of statementsevaluated if TRUEelseblock of statementsevaluated if FALSEendExampleif (temperature gt 100)disp (rsquoAbove boilingrsquo)toohigh = 1elsedisp (rsquoTemperature is OKrsquo)toohigh = 0endbull if elseif else endSyntaxif logical_expression1block of statements evaluatedif logical_expression1 is TRUEelseif logical_expression2block of statements evaluatedif logical_expression2 is TRUEelseblock of statements evaluatedif no other expression is TRUEendExampleif (height gt 190)disp (rsquovery tallrsquo)elseif (height gt 170)disp (rsquotallrsquo)elseif (height lt 150)disp (rsquosmallrsquo)

elsedisp (rsquoaveragersquo)endRemark To do the exercises below a script m-file will be useful It is an external file that contains asequence of Matlab commands What you need to do is to open an editor enter all commands needed forthe solution of a task save it with the extension rsquomrsquo (eg mytaskm) and then run it from the CommandWindow by typing mytask To open the Matlab editor go to the File menu-bar choose the Open optionand then m-file A new window will appear where you can write your scripts and save them on the disk Allcommands in the script will be executed in Matlab You will learn more on script m-files in section 91Important m-script file must be saved in one of the directories in Matlabrsquos pathAn example A script shortm can be created from the two lines given below and run by calling shortx = 0054plot (x sin(x) rsquo-rsquo)Exercise 26Create a script that asks for a number N and computes the drag coefficient C depending on the Reynoldrsquos23number N (make use of the if elseif construction) The command input might be useful here(read pages 32-33 from rdquoThe Student Edition of Matlabrdquoor use help)C =8gtgtgtltgtgtgt0 N _ 024N N 2 (0 01]24N (1 + 014N07) N 2 (01 1e3]043 N 2 (1e3 5e5]019 minus 8e4N N gt 5e5Check whether your script works correctly Compute the drag coefficient for eg N = -3e3 001 56 1e3 3e6(remember that eg 3e3 is a Matlab notation of 3 _ 103) _Exercise 27Write a script that asks for an integer and checks whether it can be divided by 2 or 3 Consider all possibilitiessuch as divisible by both 2 and 3 divisible by 2 and not by 3 etc (use the command rem) _Another selection structure is switch which switches between several cases depending on an expression which119-120 is either a scalar or a stringSyntaxswitch expressioncase choice1block of commands1case choice2a choice2bblock of commands2otherwiseblock of commandsendExamplemethod = 2switch methodcase 12disp(rsquoMethod is linearrsquo)case 3disp(rsquoMethod is cubicrsquo)case 4disp(rsquoMethod is nearestrsquo)otherwisedisp(rsquoUnknown methodrsquo)endThe statements following the first case where the expression matches the choice are executed Thisconstruction can be very handy to avoid long if elseif else end constructions Theexpression can be a scalar or a string A scalar expression matches a choice if expression == choice Astring expression matches a choice if strcmp(expression choice) returns 1 (is true) (strcmp is a commandcomparing two strings)Important Note that the switch-construction only allows the execution of one group of commandsExercise 28Assume that the months are represented by numbers from 1 to 12 Write a script that asks you to provide a

month and returns the number of days in that particular month Alternatively write a script that asks youto provide a month name (eg rsquoJunersquo) instead of a number Use the switch-construction _63 LoopsIteration control structures loops are used to repeat a block of statements until some condition is met Two114-117 types of loops existbull the for loop that repeats a group of statements a fixed number of timesSyntaxfor index = firststeplastblock of statementsendExamplesumx = 0for i=1length(x)sumx = sumx + x(i)end24You can specify any step including a negative value The index of the for-loop can be also a vectorSee some examples of possible variationsExample 1for i=12nendExample 2for i=n-13endExample 3for x=0054disp(x^2)endExample 4for x=[25 9 81]disp(sqrt(x))endbull while loop which evaluates a group of commands as long as expression is TRUESyntaxwhile expressionstatement1statement2statement3endExampleN = 100iter = 1msum = 0while iter lt= Nmsum = msum + iteriter = iter + 1endExercise 29Given the vectors x and y write a script computing the a matrix whose elements should be created accordingto a formula given below (make use of the length command to check the number of elements in both vectors)- aij = yixj (make sure that a division by zero will not occur)- bij = xi _ yj

- cij = 1 max (xi yj)_Exercise 30Determine the sum of the first 50 squared numbers with a control loop _Exercise 31Write a script to find the largest value n such that the sum p13 + p23 + + pn3 is less than 1000 _optionalExercise 32Write a script that transposes a matrix A Check its correctness with the Matlab operation Arsquo _Exercise 33

Write a script that asks for a temperature in degrees Celsius tc and computes the equivalent temperature indegrees Fahrenheit tf (use the formula tf = 95 _ tc + 32) The script should keep running until no numberis provided to convert The functions input and isempty (use help to learn more) should be useful here _end optional

64 Evaluation of logical and relational expressions in the control flow structuresThe relational and logical expressions may become more complicated It is not difficult to operate on them ifyou understand how they are evaluated To explain more details let us consider the following exampleif (~isempty(data)) amp (max(data) lt 5)endThis construction of the if-block is necessary to avoid comparison if data happens to be an empty matrix Insuch a case you cannot evaluate any expression and Matlab gives an error The amp operator returns 1 only ifboth expressions ~isempty (data) and max(data) lt 5 are true and 0 otherwise When data is an emptymatrix the next expression is not evaluated since the whole amp-expression is already known to be false Thesecond expression is checked only if data is a non-empty matrix Remember to put logical expression unitsbetween brackets to avoid wrong evaluations25Important The fact that computers make use of floating-point arithmetic means that often you should becareful when comparing two floating-point numbers just byif (x == y)end(Of course such a construction is allowed eg when you know that x and y represent integers) Instead of theabove construction you may try using thisif (abs (x - y) lt tolerance) eg tolerance = 1e-10endExercise 34Consider the following examplemax_iter = 50tolerance = 1e-4iter = 0xold = 01x = 1while (abs (x - xold) gt tolerance) amp (iter lt max_iter)xold = xx = cos(xold)iter = iter + 1endThis short program tries to solve the equation cos(x) = x (x is the solution found) Make the script solve cosfrom the presented code Note that the while-loop is repeated as long as both conditions are true If eitherthe condition (|x - xold| lt= tolerance) or (iter gt= max iter) is fulfilled then the loop is quitted Runthe script solve cos for different tolerance parameters eg 1e-3 1e-6 1e-8 1e-10 etc Use format long tocheck more precisely how much the found x is really different from cos(x) For each tolerance value checkthe number of performed iterations (iter value) _Exercise 35Create the script solve cos2 which is equal to the one given replacing the while-loop condition bywhile (abs (x - xold) gt tolerance) | (iter lt max_iter)Try to understand the difference and confirm your expectations by running solve cos2 What happens toiter _optional

65 Numerical analysis and the control flow structuresTake a look at the problem of a Taylor expansion The series will be determined numerically until the additionalterms are smaller than a defined precision Look at the Taylor expansion of 11minusx = 1 + x + x2 + withx = 042s = 0 x = 1 s = 0 x = 1x0 = 042 x0 = 042while (x gt 1e-6) or while (x gt (1e-6)s)s = s + x s = s + xx = x x0 x = x x0end endThe approximation of 11minusx is returned in s (first letter of sum) In the first case (on the left) the iteration

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 2: Introduction to Programming Using Matlab

Contents

Introduction 1

Preliminaries 3

1 How to work with Matlab 311 Input via the command-line 412 help-facilities 513 Interrupting a command or program 514 Path 615 Workspace issues 616 Saving and loading data 6

2 Mathematics with numbers vectors and matrices 7

21 Single numbers 722 An introduction to floating-point numbers 823 Assignments and variables 824 Vectors 925 Matrices 11

3 Visualization 17

31 Simple plots 1732 Several functions in one figure 1733 Other 2D plotting features - optional 1834 Printing 18

4 Curve fitting and interpolation 1941 Curve fitting 1942 Interpolation 205 Numerical analysis 2051 Evaluation of a function 2052 Integration and differentiation 216 Control flow 2161 Logical and relational operators 2262 Conditional code execution 2363 Loops 2464 Evaluation of logical and relational expressions in the control flow structures 2565 Numerical analysis and the control flow structures - optional 267 Text 2771 Character strings 2772 Text input and output 288 Cell arrays and structures - optional 3081 Cell arrays 3082 Structures 319 Script and function m-files 3391 Script m-files 3392 Function m-file 34921 Special function variables 36922 Local and global variables 37923 Indirect function evaluation - optional 3793 Scripts vs functions 3910 Optimizing the performance of Matlab code 39101 Vectorization - speed-up of computations 39102 Array preallocation 4011 File inputoutput operations 41111 Text files 42112 Binary files - optional 4312 Writing and debugging Matlab programs 44121 Structural programming 44122 Debugging 46123 Recommended programming style 46

INTRODUCTION

During this course you will learn how to use Matlab to design and to perform mathematical computations

You will also get acquainted with basic programming If you learn to use this program well you will find it very useful in future since many technical or mathematical problems can be solved using Matlab

This text includes all material (with some additional information) that you need to know however many things are treated briefly Therefore ldquoThe Student Edition of Matlabrdquo userrsquos guide should be used as a complementary book during the course A sign of a book accompanied by page numbers placed in the left margin indicates where you can find more information Read the suggested pages to better understand the concepts discussed Where no reference to the book appears it means that only this text explains some ideas since they might be more about general programming than about Matlab Exercises are marked with also in the left margin The end of an exercise is marked with _

The text of this course includes some optional parts for volunteers or for more advanced students Such a part is enclosed between two horizontal lines with the word rsquooptionalrsquo on the first line There are also rsquointermezzorsquo parts which are not essential but provide some important information If you already know how to program in a language like Pascal or C you then may find it easier or more interesting to do the optional parts as well However if you do not have any idea about programming please feel free to skip those fragments It is important that you spend enough time to learn the Matlab basics that are introduced in the first few sections If you notice that you need more time than laboratory hours please consider doing some examples during the rest of the time

Since learning Matlab is a challenging task you are encouraged to prepare each laboratory you may read a part of text at home or try the examples yourself This way you can use laboratory time to ask questions in order to make things become clearer to you We suggest the following schedule for this course However you are free to decide about your own speed taking into account that on the 5th or 6th day you have to be able to start with the final assignment

DAY 1 SECTIONS 1 ndash 3

At the end of day 1 you should be able tobull recognize built-in variablesbull define variables and perform computations using thembull know how to suppress display with (semicolon)bull add and remove variables from the workspace check which variables are currently present in theworkspacebull use on-line help to get more information on a command and know how to use the lookfor commandbull use the load and save commands to readsave data to a filebull access files at different directories (manipulate path-changing commands)bull create vectors and matrices with direct assignment (using [ ])bull use linspace to create vectorsbull create random vectors and matricesbull extract elements from vectors and matrices with subscript notation eg x(5) A(ij)bull use colon notation to create vectors and extract ranges of elements from vectors and matricesbull apply transpose operators to vectors and matricesbull perform legal addition subtraction and multiplication operations on vectors and matricesbull understand the use of array operators like + and know why they are different from the regular + operatorsbull compute inner products and the Euclidean length of vectorsbull advanced create and manipulate complex vectors and matricesbull optional delete elements from vectors and matricesbull use the plot function to make simple plots and to plot several functions in one figurebull optional make some fancy plotsbull send figures to the printer or print them to a file

Remark If you do not have enough time to exercise on matrix operations next time you should start fromsection 25 However it would be very useful if you could already try things before that time

DAY 2 SECTIONS 4 - 6

At the beginning you should exercise once again with operations on matrices (section 25) Since they areessential in Matlab be sure that you fully understand how to perform themAt the end you should be able to

bull understand better the operations on vectors and matricesbull create and manipulate Matlab polynomialsbull fit a polynomial to databull evaluate a function integrate and differentiate itbull use relational operators lt lt= gt gt= == ~= and logical operators amp | and ~bull use if end if elseif end and if elseif else end and switch constructionsbull use for-loops and while-loops and know the difference between thembull understand how logical expressions are evaluated in the control flow structuresbull optional understand how to make approximations of Taylor expansions with the given precision

DAY 3 SECTIONS 7 ndash 9

At the beginning you should exercise once again with the control flow structures (section 61-64) since they are rsquobuilding blocksrsquo of programs that you will have to createAt the end you should be able to

bull understand better the control flow structuresbull create and manipulate string variables eg compare two strings concatenate them find a substring in a string convert a numberstring into a stringnumber etcbull use freely and with understanding the text inputoutput commands input disp and fprintfbull optional operate on cell arrays and structuresbull edit and run an m-file (both functions and scripts)bull identify the differences between scripts and functionsbull understand the concept of local and global variablesbull create a function with one or more input arguments and one or more output argumentsbull use comment statements to document scripts and functionsbull optional use the feval command - know how to pass a function name as an input argument to another function

DAY 4 SECTIONS 10 - 12 + EXERCISING ON WRITING FUNCTION M-FILES

At the end you should be able tobull understand better how to build function m-filesbull preallocate memory for vectors or matrices and know why and when this is beneficialbull replace basic loops with vectorized operationsbull use colon notation to perform vectorized operationsbull advanced use array indexing instead of loops to select elements from a matrixbull advanced use logical indexing and logical functions instead of loops to select elements from matricesbull perform low level input and output with fopen fscanf and fclosebull understand how to operate on text files (inputoutput operations)bull get more understanding on the use of fprintf while writing to a filebull optional understand how to operate on binary files (inputoutput operations)bull know and understand the importance of structural programming and debuggingbull know how to debug your programbull advanced write programs using the recommended programming style

Day 5

Polishing the knowledge and experiences gained with Matlab asking questions etc First steps in the directionof the final assignment

Day 6 - 7

The final assignment

PRELIMINARIES

Below you find a few basic definitions on computers and programming Please get acquainted with them since they introduce key concepts needed in the coming sections

bull A BIT (short for binary digit) is the smallest unit of information on a computer A single bit can hold only one of two values 0 or 1 More meaningful information is obtained by combining consecutive bits into larger units such as byte

bull A BYTE - a unit of 8 bits being capable of holding a single character Large amounts of memory are indicated in terms of kilobytes (1024 bytes) megabytes (1024 kilobytes) and gigabytes (1024 megabytes)

bull BINARY SYSTEM - a number system that has two unique digits 0 and 1 Computers are based on such a system because of its electrical nature (charged versus uncharged) Each digit position represents a different power of 2 The powers of 2 increase while moving from the right most to the left most position starting from 20 = 1 Here is an example of a binary number and its representation in the decimal system

10110 = 1 _ 24 + 0 _ 23 + 1 _ 22 + 1 _ 21 + 0 _ 20 = 16 + 0 + 4 + 2 + 0 = 24

bull DATA is information represented with symbols eg numbers words signals or images

bull A COMMAND is an instruction to do a specific task

bull An ALGORITHM is a sequence of instructions for the solution of a specific task in a finite number of steps

bull A PROGRAM is the implementation of an algorithm suitable for execution by a computer

bull A VARIABLE is a container that can hold a value For example in the expression x+y x and y are variables They can represent numeric values like 255 characters like rsquocrsquo or character strings like rsquoMatlabrsquoVariables make programs more flexible When a program is executed the variables are then replaced with real data That is why the same program can process different sets of data Every variable has a name (called the variable name) and a data type A variablersquos data type indicates the sort of value that the variable represents (see below)

bull A CONSTANT is a value that never changes That makes it the opposite of a variable It can be a numeric value a character or a string

bull A DATA TYPE is a classification of a particular type of information The most basic data types are- integer a whole number a number that has no fractional part eg 3- floating-point a number with a decimal point eg 35 or 12e-16 (this stands for 12 _ 10minus16)- character readable text character eg rsquoprsquo

bull A BUG is an error in a program causing the program to stop running not to run at all or to provide wrong results Some bugs can be very subtle and hard to find The process of finding and removing bugs is called debugging

bull A FILE is a collection of data or information that has a name stored in a computer There are many different types of files data files program files text files etc

bull An ASCII FILE is a standardized readable and editable plain text file

bull A BINARY FILE is a file stored in a format which is computer-readable but not human-readable Most numeric data and all executable programs are stored in binary files Matlab binary files are those with the extension rsquomatrsquo

1 How to work with Matlab

Matlab is a tool for mathematical (technical) calculations First it can be used as a scientific calculator it provides simple mathematical operations but handles complex numbers powers logarithms trigonometric operations as well Next it allows you to plot or visualize data in many different ways perform matrix algebra work with polynomials or integrate functions Like in a programmable calculator you can create execute and save a sequence of commands in order to make your computational process automatic It can be used to

store or retrieve data In the end Matlab can also be treated as a user-friendly programming language which gives the possibility to handle mathematical calculations in an easy wayRunning Matlab creates one or more windows on your screen The most important is the Matlab Command Window which is the place where you interact with Matlab The string gtgt is the Matlab prompt (except for the Student Edition that has the EDUgtgt prompt) When the Command window is active a cursor appears after the prompt indicating that Matlab is waiting for your command which can be eg 173 or cos(x)

11 Input via the command-line2-10 Matlab is an interactive system commands followed by Enter are executed immediately The results are ifdesired displayed on screen However execution of a command will not be possible or will go wrong when thecommand is not typed according to the rules Table 1 shows a list of commands used to solve the indicatedmathematical equation (a b x and y are numbers)There are also commands that perform a specific task such as help work with a file-system like cd or workwith matrices like rank Below you find basic information that is important when starting with Matlabbull Commands in Matlab are executed by pressing Enter or Return The output will be displayed onscreen immediately Try the followinggtgt 3 + 75gtgt 184gtgt 3 7Note that spaces are not important in Matlabbull The result of the last execution is called ans It can be used on the next command line Try for instancegtgt 144ans =35000gtgt ans^(-6)ans =54399e-0454399e-04 is a computer notation of 54399 _ 10minus4 (see Preliminaries) Note that ans is always overwrittenby the last commandbull ans is an example of a Matlab built-in variable It stores the result of the recently performed computationYou can also define your own variables Look how the information is stored in the variables aand bgtgt a = 144a =35000gtgt b = a^(-6)b =54399e-04Read Preliminaries to better understand the concept of variables You will learn more on Matlabvariables in section 23bull When the command is followed by a semicolon () the output is suppressed Check the differencebetween the following expressionsgtgt 3 + 75gtgt 3 + 75gtgt x = 34bull It is possible to execute more than one command at the same time the separate commands should thenbe divided by commas (to display the output) or by semicolons (to suppress the output display) eggtgt sin(pi4) cos(pi) sin(0)ans =07071ans =0Note that the value of cos(pi) is not printedbull The output may contain some empty lines this can be suppressed by the command format compactIn contrast the command format loose will insert extra empty lines4Mathematical notation Matlab-commanda + b a + ba minus b a - bab a b3xy 3 x ya

b a b or b a

ab a^bpx sqrt(x) or x^05_ pie exp(1)i i4 middot 103 4e3 or 410^33 minus 4i 3 - 4i or 3 - 4jsin x arctan x sin(x) atan(x) ex exp(x)ln x log(x)log x log10(x)|x| abs(x)Table 1 Translation of mathematical notation to Matlab commandsbull Matlab is case sensitive There is a difference between capital and normal letters for example a iswritten as a in Matlab A will result then in an errorbull All text after a percent sign until the end of a line is treated as a comment Enter eg the followinggtgt sin(314159) this is an approximation of sin(pi)You will notice that some examples in this text are followed by comments They are meant for you andyou should skip them while typing those examplesbull Previous commands can be fetched back with the -key The command can also be changed the and -keys may be used to move around in a line and edit itKeep in mind that Matlab executes the command immediately it might be useful to have an idea of theexpected outcome12 help-facilitiesMatlab provides assistance through extensive online help The help command is the simplest way to get349-359 help that is if you know the topic or command on which you want help For examplegtgt help elfungives information on the elementary math functions of Matlab The command help displays a list of allpossible topics The topic you want help on must be exact and spelled correctly The commando lookfor ismore useful if you do not know the exact name of the command or topic For examplegtgt lookfor inversedisplays all commands for which the word inverse is included in its help-text This command results in a list ofcommands with a short description Besides the help and lookfor commands there is also a separate mousedriven help The helpwin command opens a new window on screen which can be browsed in an interactiveway To learn more read pages 353-354 from rdquoThe Student Edition of Matlabrdquobook13 Interrupting a command or programSometimes you might spot an error in your command or program Due to this error it can happen that thecommand or program does not stop Pressing Ctrl-C forces Matlab to stop the process After this theMatlab-prompt (gtgt) re-appears This may take a while though514 PathIn Matlab commands or programs are contained in m-files which are just plain text files and have an37-39 extension rsquomrsquo The m-file must be located in one of the directories which Matlab automatically searchesThe list of these directories can be listed by the command path One of the directories that is always takeninto account is the current working directory which can be identified by the command pwd Use path addpathand rmpath functions to modify the path Here is an examplegtgt pathcmatlabcmatlabtoolboxmatlabgeneralcmatlabtoolboxmatlabopsgtgt addpath hpersonal assume that this is your directorygtgt pathhpersonalcmatlabcmatlabtoolboxmatlabgeneralcmatlabtoolboxmatlabopsIt is also possible to access the path browser from the File menu-bar instead15 Workspace issuesIf you work in the Command Window Matlab memorizes all commands that you entered (as you alreadyknow - to recall previous commands the -key is useful) and all variables that you created This can be6

2425verified with the commands who which gives a list of variables present in the workspace and whos whichincludes information on name number of allocated bytes and class of the variables For example assuming thatyou performed all commands given in the beginning after typing who you should get the following informationgtgt whoYour variables area ans b xThe command clear ltnamegt deletes the variable ltnamegt from the Matlab workspace clear or clear allremoves all variables This is useful when starting a new exercise For examplegtgt clear a xgtgt whoYour variables areans b16 Saving and loading dataThe easiest way to save or load Matlab variables is by using (clicking) the File menu-bar and then the Save26 Workspace as and Load Workspace items Also Matlab commands exist which allow you to saveand load data from filesThe command save allows for saving your workspace variables either into a binary file or an ASCII file (checkPreliminaries on binary and ASCII files) Binary files automatically get the rsquomatrsquo extension which is nottrue for ASCII files However it is recommended to add a rsquotxtrsquo or dat extensionExercise 1Learn how to use the save command by exercisinggtgt s1 = sin(pi4) s2 = sin(pi2)gtgt c1 = cos(pi4) c2 = cos(pi2)gtgt str = rsquohello worldrsquo this is a string example you will learn about strings latergtgt save saves all variables in binary format to the file matlabmatgtgt save data saves all variables in binary format to the file datamat6gtgt save numdata s1 c1 saves numeric variables s1 and c1 to the file numdatamatgtgt save strdata str saves a string variable str to the file strdatamatgtgtgtgt save allsin s saves all variables that match the pattern to allsinmatgtgt save allcosdat c -ascii saves c1c2 in 8-digit ascii format to allcosdat_The load command allows for loading variables into the workspace It uses the same syntax as saveExercise 2Assuming that you have done the previous exercise try to load variables from the created filesImportant before each load command clear the workspace and after loading check which variables arepresent in the workspace (using who)gtgt load loads all variables from the file matlabmatgtgt load data s1 c1 loads only specified variables from the file datamatgtgt load strdata loads all variables from the file strdatamatIt is also possible to read ASCII files that contain rows of space separated values Such a file may containcomments that begin with a percent character The resulting data is placed into a variable with the samename as the ASCII file (without the extension) Check for examplegtgt load allcosdat loads data from the file allcosdat into variable allcosgtgt who lists variables present in the workspace now_

2 Mathematics with numbers vectors and matricesThe basic element of Matlab is a matrix (or an array) Special cases arebull a 1 times 1-matrix a scalar or a single numberbull a matrix existing only of one row or one column a vector21 Single numbersYou have already got some experience with Matlab and you know that it can be used as a calculator To do4-614-1727that you can for example simply typegtgt 31256The result will beans =55714By default Matlab displays only 5 digits The command format long increases this number to 15 format

short reduces it to 5 again For examplegtgt format longgtgt 31256ans =557142857142857Exercise 3Define the format Matlab such that empty lines are suppressed and the output is given with 5 digitsCalculategtgt pigtgt sin(pi)Note that the answer is not exactly 0 _Use the command format to put Matlab in its standard-format ie short and loose7intermezzo

22 An introduction to floating-point numbersIn a computer numbers can be represented only in a discrete form It means that numbers are stored286 within a limited range and with a finite precision Integers can be represented exactly with the base of 2(read Preliminaries on bits and the binary system) The typical size of an integer is 16 bits so the largestpositive integer which can be stored is 216 = 65536 If negative integers are permitted then 16 bits allow forrepresenting integers between minus32768 and 32767 Within this range operations defined on the set of integerscan be performed exactlyHowever this is not valid for other real numbers In practice computers are integer machines and are capableof representing real numbers only by using complicated codes The most popular code is the floating pointstandard The term floating point is derived from the fact that there is no fixed number of digits before andafter the decimal point meaning that the decimal point can float Note that most floating-point numbers thata computer can represent are just approximations Therefore care should be taken that these approximationslead to reasonable results If a programmer is not careful small discrepancies in the approximations can causemeaningless results Note the difference between eg the integer arithmetic and floating-point arithmeticInteger arithmetic Floating-point arithmetic2 + 4 = 6 187 = 257143 4 = 12 25714 7 = 1799982511 = 2 100003 = 33333e+03When describing floating-point numbers precision refers to the number of bits used for the fractional partThe larger the precision the more exact fractional quantities can be represented Floating-point numbers areoften classified as single precision or double precision A double-precision number uses twice as many bits asa single-precision value so it can represent fractional values much better However the precision itself is notdouble The extra bits are also used to increase the range of magnitudes that can be representedMatlab relies on a computerrsquos floating point arithmetic You could have already noticed that in the last408-410 exercise since the value of sin(_) was almost zero and not completely zero It came from the fact that boththe value of _ is represented with a finite precision and the sin function is also approximatedThe fundamental type in Matlab is double which stands for a representation with a double precision It uses64 bits The single precision obtained by using the single type offers 32 bits Since most numeric operationsrequire high accuracy the double type is used by defaultThe exact machine precision might be defined as the smallest positive number _ that added to 1 does notchange the result so 1 + _ = 1 in floating-point arithmetic this value is larger than zero (in exact arithmeticof course _ = 0 holds) Matlab machine precision is stored in the built-in variable eps _ 22204e-16 Thismeans that the relative accuracy of individual arithmetic operations is about 16 digitsend intermezzo

23 Assignments and variablesWorking with complex numbers is easily done with MatlabExercise 4Choose two complex numbers for example -3 + 2i and 5 - 7i Try to add subtract multiply and dividethese two numbers _During this exercise the complex numbers had to be typed four times To reduce this assign each number to4-610-12a variable For the previous exercise this results ingtgt z = -3 + 2igtgt w = 5 - 7igtgt y1 = z + w y2 = z - w y3 = z w y4 = z w y5 = w zFormally there is no need to declare (ie define the name size and the type of) a new variable in Matlab Avariable is simply created by an assignment (the way it has been done above) Each newly created numerical

variable is always of the double type You can change this type by converting it into eg the single type 11a variable a is converted into a different type by performing eg a = single(a) a = int16(a) etc8In some cases when huge matrices should be handled and precision is not very important this might be a wayto proceed Also when only integers are taken into consideration it might be useful to convert the doublerepresentations into eg int16 or int321 integer types Since most computations should be performed with ahigh accuracy Matlab automatically chooses the double type It means that real numbers are approximatedwith the highest possible precision However it is important to emphasize that integer numbers are alwaysrepresented exactly no matter which numeric type is usedBear in mind that undefined values cannot be assigned to a variable So the following is not possiblegtgt clear x to make sure that x does not existgtgt fun = x^2 + 4 sin (x)It becomes possible bygtgt x = pi 3 fun = x^2 + 4 sin (x)Exercise 5Predict the result ofx = pi 3 x = x - 1 x = x + 5 x = abs(x) xCheck your prediction by performing these commands in Matlab _Exercise 6Here are some examples of different types of Matlab variables You do not need to understand them all nowsince you will learn more about them during the course Create them manually in Matlabgtgt this_is_my_very_simple_variable_today = 5 a number check what happens since thegtgt name is very long (gt 31 characters)gtgt 2t = 8 what is the problem with this commandgtgt this_is_a_matrix = [1 2 3 4 5 6] a matrixgtgt c = rsquoErsquo a charactergtgt str = rsquoHello worldrsquo a stringgtgt m = [rsquoJrsquorsquoorsquorsquohrsquorsquonrsquo] try to guess what it isCheck the types by using the command whos Use clear ltnamegt to remove a variable from the workspace _Exercise 7In addition to creating variables by assigning values to them a few other ways exist For instance there is anumber of built-in variables eg ans pi eps i inf or nan Find out what value is assigned to each of these74584 built-in variables _24 VectorsRow vectors are lists of numbers separated either by commas or by spaces They are examples of simple arrays41-49 The number of entries is known as the length of the vector (the command length exists as well) Their entitiesare referred to as elements or components The entries must be enclosed in [ ]gtgt v = [-1 sin(3) 7]v =-10000 01411 70000gtgt length(v)ans =3A number of operations can be done on vectors A vector can be multiplied by a scalar or addedsubtractedtofrom another vector with the same length or a number can be addedsubtracted tofrom a vector Allthese operations are carried out element-by-element Vectors can be also built from the already existing onesgtgt v = [-1 2 7] w = [2 3 4]gtgt z = v + w an element-by-element sumz =1 5 119gtgt v3 = v + 2 add 2 to all elements of vector v3v3 =1 4 9gtgt t = [2v -w]ans =-2 4 14 -2 -3 -4Also a particular value can be changed or displayedgtgt v(2) = -1 w(2) change the 2nd value of v display the 2nd value of wv =-1 -1 7ans =

3A colon notation is an important shortcut used when producing row vectors (see Table 3 and help colon)gtgt 25ans =2 3 4 5gtgt -23ans =-2 -1 0 1 2 3In general firststeplast produces a vector of entities with the value first incrementing by the stepuntil it reaches lastgtgt 020524ans =02000 07000 12000 17000 22000gtgt -3310ans =-3 0 3 6 9gtgt 15-05-05 negative step is also possibleans =15000 10000 05000 0 -05000Parts of vectors can be extracted by using a colon notationgtgt r = [-126 2 3 -2] -126 =gt -1 1 3 5r =-1 1 3 5 2 3 -2gtgt r(36) get elements of r which are on the positions from 3 to 6ans =3 5 2 3gtgt r(125) get elements of r which are on the positions from 1 to 5 taken with the step of 2ans =-1 3 2gtgt r(5-12) what will you get hereTo create column vectors you should separate entries by a semicolon () or by new linesgtgt f = [-1 3 5]f =-135The same operations as on row vectors can be done on column vectors However you cannot for exampleadd a column vector to a row vector To do that you need an operation called transposing which converts acolumn vector into a row vector and vice versa10gtgt f = [-1 3 5] a column vectorgtgt frsquo frsquo is a row vectorans =-1 3 5gtgt v = [-1 2 7] a row vectorgtgt f + v you cannot add a column vector f to a row vector v Error using ==gt +Matrix dimensions must agreegtgt frsquo + vans =-2 5 12gtgt f + vrsquoans =-2512If x is a complex vector than xrsquo gives the conjugate transpose of x eggtgt x = [1+2i -1+i]x =10000 + 20000i -10000 + 10000igtgt xrsquo this is the conjugate transposeans =10000 - 20000i-10000 - 10000i

gtgt xrsquo this is the rsquonormalrsquo transposeans =10000 + 20000i-10000 + 10000iExercise 8Exercise to become acquainted with operating on row and column vectors Enter all examples given in thissection and make new variations yourself Exercise with the colon notation approach as well _25 MatricesAn ntimesk matrix is a rectangular array of numbers having n rows and k columns Defining a matrix in Matlabis similar to defining a vector The generalization is straightforward if you know that a matrix consists of row49-6175-86vectors (or column vectors) Commas or spaces are used to separate elements in a row and semicolons areused to separate individual rows For example the matrix A =01 2 34 5 67 8 91Ais defined asgtgt A = [1 2 3 4 5 6 7 8 9] row by row inputA =1 2 34 5 67 8 9Another examples are for instancegtgt A2 = [14 -125]A2 =1 2 3 4-1 1 3 5gtgt A3 = [1 3-4 7]A3 =1 3-4 711Command ResultA(ij) Aij

A(j) j-th column of AA(i) i-th row of AA(klmn) (l minus k + 1) times (n minus m + 1) matrix with elements Aij with k _ i _ l m _ j _ nv(ij)rsquo rsquovector-partrsquo (vi vi+1 vj) of vector vTable 2 Manipulation of (groups of) matrix-elementsCommand Resultn = rank (A) n becomes the rank of matrix Ax = det (A) x becomes the determinant of matrix AC = size (A) C becomes a row-vector with 2 elements the number of rows and columns of Ax = trace (A) x becomes the trace (sum of diagonal elements) of matrix Ax = norm (v) x becomes the length of vector vC = A + B sum of two matricesC = A - B subtraction of two matricesC = A B multiplication of two matricesC = A B rdquoelement-by-elementrdquo multiplication (A and B are of equal size)C = A ^ k power of a matrix (k 2 Z can also be used for Aminus1)C = A ^ k rdquoelement-by-elementrdquo power of a matrixC = Arsquo the transposed of a matrix AT

C = A B rdquoelement-by-elementrdquo division (A and B are of equal size)U = A B finds the solution that minimizes the squared error in Ax minus BU = B A solution of XA = B analogous to the previous commandC = inv (A) C becomes the inverse of AC = null (A) C is an orthonormal basis for the null space of Aobtained from the singular value decompositionC = orth (A) C is an orthonormal basis for the range of AC = rref (A) C is the reduced row echelon form of AL = eig (A) L is a vector containing the -possibly complex- eigenvalues of a square matrix A[X D] = eig (A) produces a diagonal matrix D of eigenvalues and a full matrix X

whose columns are the corresponding eigenvectors of AS = svd (A) S is a vector containing the singular values of A[U S V] = svd (A) S is a diagonal matrix of the same dimension as Awith nonnegative diagonal elements in decreasing orderThe columns U and V are the accompanying singular vectorsx = linspace(a b n) generates a vector x of n equally spaced points between a and bx = logspace(a b n) generates a vector x starting at 10a and ended at 10b containing n valuesA = diag (v) gives a diagonal matrix with the elements v1 v2 vn on the diagonalA = eye (n) A is a n times n identity matrixA = zeros (n m) A is a n times m matrix with zeros (default m = n)A = rand (n m) A is a n times m matrix with elements uniformly distributed between 0 and 1A = randn (n m) ditto - with elements standard normal distributedv = max (A) v becomes a vector with the maximum value of the elements in each column of Aor v is the maximum of all elements if A is a vectorv = min (A) ditto - with minimumv = sum (A) ditto - with sumTable 3 Frequently used matrix operations and functions12Transposing a vector changes it from a row to a column or the other way around This idea can be extendedto a matrix where transposing interchanges rows with the corresponding columns as in the examplegtgt A2 A2rsquoA2 =1 2 3 4-1 1 3 5ans =1 -12 13 34 5gtgt size(A2) returns the size (dimensions) of a matrixans =2 4gtgt size(A2rsquo)ans =4 2There exists also some built-in matrices of size specified by the user (see Table 2) A few examples are givenbelowgtgt E = [] an empty matrix of 0-by-0 elementsE =[]gtgt I = eye(3) the identity matrixI =1 0 00 1 00 0 1gtgt B = rand(23) a matrix of random numbers you will get a different one00227 09101 0922200299 00640 03309gtgt O = ones(32)O =1 11 11 1gtgt r = [1 3 -2] R = diag(r) create a diagonal matrix with r on the diagonalR =1 0 00 3 00 0 -2gtgt v = linspace(124) a vector is also an example of a matrixv =10000 13333 16667 20000It is often needed to build a larger matrix from the smaller onesgtgt x = [4 -1] y = [-1 4]x =4

-1y =-1 4gtgt X = [x yrsquo] X consists of the columns x and yrsquoX =4 -1-1 4gtgt T = [ -1 3 4 4 5 6] t = 1313gtgt T2 = [T t] add to T a new row namely the row vector t getting T2T2 =-1 3 44 5 61 2 3gtgt G = [1 5 4 5 0 2] G is a matrix of the 3-by-2 size check size(G)gtgt T3 = [T2 G] T3 consists of T2 and new columns being the colums of GT3 = added at the end of T2-1 3 4 1 54 5 6 4 51 2 3 0 2gtgt [diag(56) ones(32)]ans =5 00 61 11 11 1A part can be extract from a matrix in a similar way as from a vector Each element in the matrix is indexedby a row and a column to which it belongs Mathematically the element from the i-th row and the j-thcolumn of the matrix A is denoted by Aij Matlab provides the A(ij) notationgtgt A = [13 46 79]A =1 2 34 5 67 8 9gtgt A(12) A(23) A(31)ans =2ans =6ans =7gtgt A(43) A is a 3-by-3 matrix Index exceeds matrix dimensionsgtgt A(23) = A(23) + 2A(11)A =1 2 34 5 87 8 9Having defined a matrix it is easy to extended it automatically For the matrix A it can be done eg asfollowsgtgt A(52) = 5 assign 5 to the position (52) the uninitializedA = elements become zeros1 2 34 5 87 8 90 0 00 5 0Different parts of the matrix A can be now extractedgtgt A(2) extract the 2nd column of Aans =25814

05gtgtgt A(34) extract the rows 3rd and 4th of Aans =7 8 90 0 0gtgt A(2312) extract a part of Aans =4 57 8If needed the other zero elements of the matrix A can be also defined by eggtgt A(4) = [1 2 3] assign vector [1 2 3] to the 4th row of Agtgt A(5[13]) = [4 5] a rsquoshortcutrsquo when assigning A(51) = 4 and A(53) = 5gtgt A how does the matrix A look like nowAs you have seen in the examples above it is possible to manipulate (groups of) matrix-elements Thecommands are shortly explained in Table 2Exercise 9Define the matrix A = [14 58 1 1 1 1] Predict and check the result ofgtgt B = A(3)gtgt C = A(1322)gtgt A(11) = 9gtgt A(2313) = [0 0 0 0 0 0]gtgt A(l212) = [l l 3 3]gtgt A = A(3314)_Exercise 10Define the matrices T=[ 3 4 1 8 -4 3] A = [diag(-123) T -4 4 1 2 1] Perform the followingoperations on the matrix Abull extract a vector consisting of the 2nd and 4th elements of the 3rd rowbull find the minimum of the 3rd columnbull find the maximum of the 2nd rowbull compute the sum of the 2nd columbull compute the mean of the 1st and 4th rowsbull extract the submatrix consisting of the 1st and 3rd rows and all columnsbull extract the submatrix consisting of the 1st and 2nd rows and the 3rd 4th and 5th columnsbull compute the total sum of the 1st and 2nd rowsbull add 3 to all elements of the 2nd and 3rd colums_Table 3 shows some frequently used matrix operations and functions A few examples are provided belowgtgt B = rand(23) a matrix of random numbers you will get a different oneB =09501 06068 0891302311 04860 07621gtgt B2 = [1 2 5 1 5 6]gtgt B + B2rsquo add two matrices why B2rsquo is needed instead of B2ans =19501 56068 5891322311 14860 67621gtgt S = ans4 divide all elements of the matrix ans by 4S =04875 14017 1472805578 03715 1690515gtgt C = [1 -1 4 7 0 -1]gtgt B C matrix multiplication is not defined for B and C Error using ==gt Inner matrix dimensions must agreegtgt B C but you can multiply element-by-elementans =09501 -06068 3565216180 0 -07621gtgt D = B Crsquo or you can make the multiplication legal Crsquo is now 3-by-2D =39085 5759627935 08559

gtgt D^3 this is equivalent to D D Dans =1992503 2041413990133 910548gtgt D^3 - 2 do for all elements raise to the power 3 and subtract 2ans =577069 1890638198005 -13731gtgtgtgt r = [1 3 -2]r B2 this is a legal operation r is a 1-by-3 matrix and B2 isans = 3-by-2 matrix B2 r is an illegal operation6 -7Remind that an n-by-k matrix A (having n rows and k columns) can be multiply by another matrix B onlyif B has k rows ie S is of the k-by-m size (m is arbitrary) As a result you get an n-by-m matrixA ˙B = C A 2 Rntimesk B 2 Rktimesm C 2 Rntimesm

RemarkYou can now compute the inner product between two vectors x and y xT y = Pi xi yi in a simple waygtgt f = [-1 3 5] a column vectorgtgt v = [-1 2 7] a column vectorgtgt frsquo v this is the inner productans =42gtgt f vrsquo be careful now a 3-by-1 matrix is multiplied by a 1-by-3gtgt matrix which results in a 3-by-3 matrix (the outer product)ans =1 -2 -7-3 6 21-5 10 35gtgt f v this is an element-by-element multiplication1635gtgt sum (f v) this is an another way to compute the inner productans =42Exercise 11Perform all operations from Table 3 using chosen matrices A and B vector v and scalars k a b n and m _Exercise 12Let A be a random 3 times 3 matrix and b a random 3 times 1 vector Given that Ax = b then x = Aminus1b Find x(there exist at least two possible commands to do this look at Table 3) _optionalThe concept of an empty matrix [] is also very useful in Matlab For instance a few columns or rows canbe removed from a matrix by assigning an empty matrix to it Try for example16Symbol Color Symbol Styley yellow dotted liner red o circlesg green - solid lineb blue - dashdotted lineTable 4 Plot colors and stylesgtgt C = [1 2 3 4 5 6 7 8 1 1 1 1]gtgt D = C D(2) = [] now a copy of C is in D remove the 2nd column of Dgtgt C ([13]) = [] remove the rows 1 and 3 from Cend optional

3 VisualizationMatlab can be used to visualize the results of an experiment Therefore you should define variables each ofthem containing all values of one parameter to plot31 Simple plotsWith the command plot a graphical display can be made plot(y) draws the points (1 y(1)) (2 y(2)) 184 (n y(n)) and connects the points with a straight line plot(xy) does the same for (x(1) y(1)) (x(2) y(2)) (x(n) y(n)) x and y have to be row- or column vectors of equal lengthThe commands loglog semilogx and semilogy are similar to plot except that they use logarithmic axesExercise 13Type the following commands after predicting the resultgtgt x = 0330

gtgt y = 2^[010] this is the same as y = [1 2 4 8 16 32 64 128 256 512 1024]gtgt plot(xy) to get a graphic representationgtgt semilogy(xy) to get logarithmic axesAs you can see the same figure is used for both plot commands The previous function is removed as soonas the next is displayed The command figure gives you an extra figure Repeat the previous commandsbut generate a new figure before plotting the second function so that you can see both functions in separatewindows You can also switch back to a figure using figure(n) where n is its number _Exercise 14Make a plot such that the coordinates (2 6) (25 18) (5 175) (42 125) and (212) are connected by aline _Exercise 15Plot the function y = sin(x) + x minus x cos(x) in two separate figures for the intervals 0 lt x lt 30 andminus100 lt x lt 100 _32 Several functions in one figureWhen more than one function is plotted in one figure it might be useful to use different markers and colors184-188197-201Table 4 shows a few possibilities help plot shows allThere are different ways to get more than one function into a figure The first one is with the command holdon After this command all functions will be plotted in the same figure until the command hold off is usedAn examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt plot (x1 y1 rsquordrsquo)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)17gtgt hold ongtgt plot (x2 y2 rsquoy-rsquo)gtgt plot (x1y1rsquok-rsquo)gtgt hold offA second method to display more than one function in one figure is to plot several functions at the same timeThe next commands will have the same results as the commands in the previous examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt plot (x1 y1rsquordrsquo x2 y2 rsquoy-rsquo x1 y1 rsquok-rsquo)It is also possible to get more than one figure in one figure window With the command subplot the windowcan be horizontally and vertically divided into any number of subfiguresgtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt subplot(131) plot (x1 y1rsquordrsquo)gtgt subplot(132) plot (x2 y2 rsquoy-rsquo)gtgt subplot(133) plot (x1 y1 rsquok-rsquo)optional

33 Other 2D plotting featuresIn the introduction of this chapter some commands similar to plot loglog semilogx and semilogy were201-211 mentioned There are however more ways to display dataExercise 16To get an impression of other visualizations type the following commands and describe the result (note thatthe command figure creates a new figure window)gtgt figure bar plot of a bell shaped curvegtgt x = -290229gtgt bar (x exp (-xx))gtgt figure stairstep plot of a sine wavegtgt x = 002510gtgt stairs (x sin (x))gtgt figure errorbar plotgtgt x = -2012gtgt y = erf (x) error function check help if you are interestedgtgt e = rand (size (x)) 10gtgt errorbar (x y e)

_end optional

34 PrintingBefore printing a figure you made you might want to add some information such as a title or change the189-196 lay-out a little Table 5 shows some of the commands that can be usedExercise 17Plot the functions y1 = sin(4x) y2 = x cos(x) y3 = (x + 1)minus1px for x = 0 025 10 and a single point(x y) = (4 5) in one figure with different colors and styles Make a legend containing the three functionsMake labels for both axes and a title Add a text to the single point saying single point Change the minimumand maximum values of the axes such that function y3 can be looked at in more detail _When the displayed figure is to your liking you can print it to paper The easiest way to do this is to click onFile in the menu-bar and to choose Print If in the print window you click OK your figure will be printed onthe printer indicated in the print window18Command Resultgrid onoff adds a grid to the plot at the tick marks or removes itaxis([xmin xmax ymin ymax]) sets the minimum and maximum values of the axesbox offon removes the axes box or shows itxlabel(rsquotextrsquo) plots the label text on the x axisylabel(rsquotextrsquo) plots the label text on the y axistitle(rsquotextrsquo) plots a title above the graphtext(xyrsquotextrsquo) adds text at the point (xy)gtext(rsquotextrsquo) adds text at a manually (with a mouse) indicated pointlegend(rsquofun1rsquorsquofun2rsquo) plots a legend box (move it with your mouse) to name your functionslegend off deletes the legend boxTable 5 Plot-manipulationsThere is also a print command which can be used to send a figure to a printer or output it to a file Youcan optionally specify a print device (ie an output format such as tiff or postscript) and options that controlvarious characteristics of the printed file (ie which Figure to print etc) You can also print to a file if youspecify the file name If you do not provide an extension print adds one Since they are many parametersthey will not be explained here (check help print to learn more) Instead try to understand the examplesgtgt print -dwinc print the current Figure to the current printer in colorgtgt print -f1 -deps myfileeps print Figure no1 to the file myfileeps in blackgtgt print -f1 -depsc myfileceps print Figure no1 to the file myfilecoleps in colorgtgt print -dtiff myfile1tiff print the current Figure to the file myfile1tiffgtgt print -dpsc myfile1cps print the current Figure to the file myfile1ps in colorgtgt print -f2 -djpeg myfile2 print Figure no2 to the file myfile2jpgExercise 18Exercise with printing (especially to a file) the figure from Exercise 16 _

4 Curve fitting and interpolationThere are two ways to describe data with an analytical function- curve fitting or regression finding a smooth curve that best fits (approximates) the data accordingto a criterion (eg best least square fit) The curve does not have to go through any of the data points- interpolation the data are assumed to be correct desired in a way to describe what happens betweenthe data points In other words given a finite set of points the goal of interpolation is to find a functionfrom a given class of functions (eg polynomials) which passes through the specified pointsThe figure below illustrates the difference between regression (curve fitting) and interpolationminus5 0 5minus6minus4minus20246810fiting a 3rd order polynomialinterpolation

41 Curve fittingMatlab interprets the best fit of a curve by the lsquoleast squares curve fittingrsquo The curve used is restricted153-15619to polynomials With the command polyfit any polynomial can be fitted to the data polyfit (x y n)finds the coefficients of a polynomial of degree n that fits the data (finds the linear relation between x and y)Letrsquos start with finding a linear regression of some datagtgt x = 010gtgt y = [-10 24 102 158 284 276 299 405 483 522 751]gtgt p = polyfit (x y 1) find the fitting polynomial of order 1p = 06772 -03914

The output of polyfit is a row vector of the polynomial coefficients the solution of this example is thereforey = 06772x minus 03914Exercise 19Execute the above example Plot the data and the fitted curve in a figure Determine the 2nd and 9th orderpolynomial of these data as well and display the solution in a figureHint x1 = linspace (xmin xmax n) results in a vector with n element evenly distributed from xmintill xmax z = polyval (p x1) calculates the values of the polynomial for every element of x1 _Exercise 20Define x and y as followsgtgt x = -55gtgt y = 02x^3 - x + 2 a 3rd order polynomialgtgt y = y + randn(111) add some noise to yDetermine the 3rd order polynomial fitting y (note that because of added noise the coefficients are differentthat originally chosen) Try some other polynomials as well Plot the results in a figure _42 InterpolationThe simplest way to examine an interpolation is by displaying the function plots with the command plot157-161 The neighboring data points are connected with straight lines This is called a linear interpolation Whenmore data-points are taken into account the effect of interpolation becomes less visible Analyzegtgt x1 = linspace(0 2pi2)gtgt x2 = linspace(0 2pi4)gtgt x3 = linspace(0 2pi16)gtgt x4 = linspace(0 2pi256)gtgt plot(x1sin(x1)x2sin(x2)x3sin(x3)x4sin(x4))gtgt legend(rsquo2 pointsrsquorsquo4 pointsrsquorsquo16 pointsrsquorsquo256 pointsrsquo)

5 Numerical analysisNumerical analysis can be used whenever it is impossible or very difficult to determine the analytical solutionMatlab can be used to find for example the minimum maximum or integral of a certain function51 Evaluation of a functionAs said before the command plot plots a function by connecting defined data points Sometimes however a168-173 function is constant and not very interesting over some range and then acts unexpectedly wildly over anotherWith plot this function might be misinterpreted The command fplot is then useful An examplegtgt x = 0pi82pigtgt y = sin (8x)gtgt plot (x y rsquobrsquo)gtgt hold ongtgt fplot (rsquosin (8z)rsquo [0 2pi] rsquorrsquo)gtgt title (rsquosin (8z)rsquo)gtgt hold off20Command Resultfplot (rsquofunrsquo [min x max x]) plots the function fun for min x till max xfmin (rsquofunrsquo min x max x) gives the x-value of the miminum of thefunction fun between min x and max xfzero (rsquofunrsquo x0) gives the x-value for which the functionfun is zero in the neighborhood of x0Table 6 Evaluation of a functionExecution of these commands results in a figure with an almost straight blue line and a red sine fplot canalso be used to plot a defined functiongtgt f = rsquosin (8z)rsquogtgt fplot (f [0 2pi] rsquorrsquo)gtgt title (f)Other useful commands for a detailed study of a range of a function are listed in Table 6Exercise 21The command fmax does not exist Use one or more of the commands from Table 6 to determine the maximumof the function x cos(x) for 10 lt x lt 15 _52 Integration and differentiationThe integral- or the surface underneath a 2D function- can be determined with the command trapz trapz173-182 does this by measuring the surface between the x-axis and the -by a straight line connected- data points Theaccuracy of this method depends on the distance between the data pointsgtgt x = 00510 y = 05 sqrt (x) + x sin (x) area1 = trapz (x y)

area1 =181655gtgt x = 000510 y = 05 sqrt (x) + x sin (x) area2 = trapz (x y)area2 =183846Differentiation is done by determining the slope in each data point Numerically this is done by first fitting apolynomial followed by differentiating this functiongtgt x = 010gtgt y = [-10 24 102 -158 284 276 775 35 483 522 751]gtgt p = polyfit (x y 5)p = 00026 -00554 03634 -06888 02747 00877gtgt dp = polyder (p)dp = 00132 -02216 10903 -13776 02747gtgt x1 = linspace (0 10 200)gtgt z = polyval (p x1)gtgt dz = polyval (dp x1)gtgt plot (x y rsquog-rsquo x1 z rsquobrsquo x1 dz rsquorrsquo)gtgt legend (rsquodata pointsrsquo rsquocurve fitrsquo rsquoderivativersquo)Exercise 22Determine the integral and derivative of the 4th polynomial fitted through (xy) with x = [4 5 6 7 8 9 1011 12 13] y = [1284 1200 724 -096 -1116 -2096 -2700 -2496 -956 2544] _

6 Control flowAs you know it is possible to execute more than one command at the same time (see section 11) Theseparate commands should then be divided by commarsquos (to display the output) or by semicolons (to suppress21output display) Control flow loops increase the number of possibilities A control flow structure is a block ofcommands that allows conditional code execution and making loops61 Logical and relational operatorsTo use control flow commands it is necessary to perform operations that result in logical values TRUE or88-91 FALSE In Matlab the result of a logical operation is 1 if it is true and 0 if it is false Table 7 shows therelational and logical operations2 Another way to get to know more about them is to type help relop Therelational operators lt lt= gt gt= == and ~= can be used to compare two arrays of the same size or anarray to a scalar The logical operators amp | and ~ allow for the logical combination or negation of relationaloperators In addition three functions are also available xor any and all (use help to find out more)Important The logical amp and | have the equal precedence in Matlab which means that those operatorsassociate from left to right A common situation isgtgt b = 10gtgt 1 | b gt 0 amp 0ans =0gtgt (1 | b gt 0) amp 0 this indicates the same as aboveans =0gtgt 1 | (b gt 0 amp 0)ans =1This shows that you should always use brackets to indicate in which way the operators should be evaluatedCommand Resulta = (b gt c) a is 1 if b is larger than c Similar are lt gt= and lt=a = (b == c) a is 1 if b is equal to ca = (b ~= c) a is 1 if b is not equal ca = ~b logical complement a is 1 if b is 0a = (b amp c) logical AND a is 1 if b = TRUE AND c = TRUEa = (b | c) logical OR a is 1 if b = TRUE OR c = TRUETable 7 Relational and logical operationsExercise 23Predict and check the result of each of the operations of Table 7 for b = 0 and c = -1 _Exercise 24Define two vectors with seven elements (randn(17)) and perform all logical operations including xor anyand all _Exercise 25While doing logical operations between a vector and a scalar each element of the vector is compared to thescalar Predict and check the result of each logical operator for the vector b = [2 31 -40 0] and the scalarc = 0 _Before moving on check whether you now understand the following relations

gtgt a = randperm(10) a random permutation of the numbers from 1 to 10gtgt b = 110gtgt b - (a lt= 7) subtracts from b a 0-1 vector taking 1 for a lt= 7 and 0 otherwisegtgt (a gt= 2) amp (a lt 4) returns ones at positions where 2 lt= a lt 4gtgt ~(b gt 4) returns ones at positions where b lt= 4gtgt (a == b) | b == 3 returns ones at positions where a is equal to b or b is equal to 3gtgt any (a gt 5) returns 1 when ANY of the a elements are larger than 5gtgt any (b lt 5 amp a gt 8) returns 1 when there in the evaluated expressiongtgt (b lt 5 amp a gt 8) appears at least one 1gtgt all (b gt 2) returns 1 when ALL b elements are larger than 22rdquoequal tordquo in the table on page 88 of rdquoThe Student Edition of Matlabrdquo must be rdquo==rdquo instead of rdquo=rdquo2262 Conditional code executionSelection control structures if-blocks are used to decide which instruction to execute next depending whether117-119 expression is TRUE or not The general description is given below In the examples below the command dispis frequently used This command displays on the screen the text between the quotesbull if endSyntaxif logical_expressionstatement1statement2endExampleif (a gt 0)b = adisp (rsquoa is positiversquo)endbull if else endSyntaxif logical_expressionblock of statementsevaluated if TRUEelseblock of statementsevaluated if FALSEendExampleif (temperature gt 100)disp (rsquoAbove boilingrsquo)toohigh = 1elsedisp (rsquoTemperature is OKrsquo)toohigh = 0endbull if elseif else endSyntaxif logical_expression1block of statements evaluatedif logical_expression1 is TRUEelseif logical_expression2block of statements evaluatedif logical_expression2 is TRUEelseblock of statements evaluatedif no other expression is TRUEendExampleif (height gt 190)disp (rsquovery tallrsquo)elseif (height gt 170)disp (rsquotallrsquo)elseif (height lt 150)disp (rsquosmallrsquo)

elsedisp (rsquoaveragersquo)endRemark To do the exercises below a script m-file will be useful It is an external file that contains asequence of Matlab commands What you need to do is to open an editor enter all commands needed forthe solution of a task save it with the extension rsquomrsquo (eg mytaskm) and then run it from the CommandWindow by typing mytask To open the Matlab editor go to the File menu-bar choose the Open optionand then m-file A new window will appear where you can write your scripts and save them on the disk Allcommands in the script will be executed in Matlab You will learn more on script m-files in section 91Important m-script file must be saved in one of the directories in Matlabrsquos pathAn example A script shortm can be created from the two lines given below and run by calling shortx = 0054plot (x sin(x) rsquo-rsquo)Exercise 26Create a script that asks for a number N and computes the drag coefficient C depending on the Reynoldrsquos23number N (make use of the if elseif construction) The command input might be useful here(read pages 32-33 from rdquoThe Student Edition of Matlabrdquoor use help)C =8gtgtgtltgtgtgt0 N _ 024N N 2 (0 01]24N (1 + 014N07) N 2 (01 1e3]043 N 2 (1e3 5e5]019 minus 8e4N N gt 5e5Check whether your script works correctly Compute the drag coefficient for eg N = -3e3 001 56 1e3 3e6(remember that eg 3e3 is a Matlab notation of 3 _ 103) _Exercise 27Write a script that asks for an integer and checks whether it can be divided by 2 or 3 Consider all possibilitiessuch as divisible by both 2 and 3 divisible by 2 and not by 3 etc (use the command rem) _Another selection structure is switch which switches between several cases depending on an expression which119-120 is either a scalar or a stringSyntaxswitch expressioncase choice1block of commands1case choice2a choice2bblock of commands2otherwiseblock of commandsendExamplemethod = 2switch methodcase 12disp(rsquoMethod is linearrsquo)case 3disp(rsquoMethod is cubicrsquo)case 4disp(rsquoMethod is nearestrsquo)otherwisedisp(rsquoUnknown methodrsquo)endThe statements following the first case where the expression matches the choice are executed Thisconstruction can be very handy to avoid long if elseif else end constructions Theexpression can be a scalar or a string A scalar expression matches a choice if expression == choice Astring expression matches a choice if strcmp(expression choice) returns 1 (is true) (strcmp is a commandcomparing two strings)Important Note that the switch-construction only allows the execution of one group of commandsExercise 28Assume that the months are represented by numbers from 1 to 12 Write a script that asks you to provide a

month and returns the number of days in that particular month Alternatively write a script that asks youto provide a month name (eg rsquoJunersquo) instead of a number Use the switch-construction _63 LoopsIteration control structures loops are used to repeat a block of statements until some condition is met Two114-117 types of loops existbull the for loop that repeats a group of statements a fixed number of timesSyntaxfor index = firststeplastblock of statementsendExamplesumx = 0for i=1length(x)sumx = sumx + x(i)end24You can specify any step including a negative value The index of the for-loop can be also a vectorSee some examples of possible variationsExample 1for i=12nendExample 2for i=n-13endExample 3for x=0054disp(x^2)endExample 4for x=[25 9 81]disp(sqrt(x))endbull while loop which evaluates a group of commands as long as expression is TRUESyntaxwhile expressionstatement1statement2statement3endExampleN = 100iter = 1msum = 0while iter lt= Nmsum = msum + iteriter = iter + 1endExercise 29Given the vectors x and y write a script computing the a matrix whose elements should be created accordingto a formula given below (make use of the length command to check the number of elements in both vectors)- aij = yixj (make sure that a division by zero will not occur)- bij = xi _ yj

- cij = 1 max (xi yj)_Exercise 30Determine the sum of the first 50 squared numbers with a control loop _Exercise 31Write a script to find the largest value n such that the sum p13 + p23 + + pn3 is less than 1000 _optionalExercise 32Write a script that transposes a matrix A Check its correctness with the Matlab operation Arsquo _Exercise 33

Write a script that asks for a temperature in degrees Celsius tc and computes the equivalent temperature indegrees Fahrenheit tf (use the formula tf = 95 _ tc + 32) The script should keep running until no numberis provided to convert The functions input and isempty (use help to learn more) should be useful here _end optional

64 Evaluation of logical and relational expressions in the control flow structuresThe relational and logical expressions may become more complicated It is not difficult to operate on them ifyou understand how they are evaluated To explain more details let us consider the following exampleif (~isempty(data)) amp (max(data) lt 5)endThis construction of the if-block is necessary to avoid comparison if data happens to be an empty matrix Insuch a case you cannot evaluate any expression and Matlab gives an error The amp operator returns 1 only ifboth expressions ~isempty (data) and max(data) lt 5 are true and 0 otherwise When data is an emptymatrix the next expression is not evaluated since the whole amp-expression is already known to be false Thesecond expression is checked only if data is a non-empty matrix Remember to put logical expression unitsbetween brackets to avoid wrong evaluations25Important The fact that computers make use of floating-point arithmetic means that often you should becareful when comparing two floating-point numbers just byif (x == y)end(Of course such a construction is allowed eg when you know that x and y represent integers) Instead of theabove construction you may try using thisif (abs (x - y) lt tolerance) eg tolerance = 1e-10endExercise 34Consider the following examplemax_iter = 50tolerance = 1e-4iter = 0xold = 01x = 1while (abs (x - xold) gt tolerance) amp (iter lt max_iter)xold = xx = cos(xold)iter = iter + 1endThis short program tries to solve the equation cos(x) = x (x is the solution found) Make the script solve cosfrom the presented code Note that the while-loop is repeated as long as both conditions are true If eitherthe condition (|x - xold| lt= tolerance) or (iter gt= max iter) is fulfilled then the loop is quitted Runthe script solve cos for different tolerance parameters eg 1e-3 1e-6 1e-8 1e-10 etc Use format long tocheck more precisely how much the found x is really different from cos(x) For each tolerance value checkthe number of performed iterations (iter value) _Exercise 35Create the script solve cos2 which is equal to the one given replacing the while-loop condition bywhile (abs (x - xold) gt tolerance) | (iter lt max_iter)Try to understand the difference and confirm your expectations by running solve cos2 What happens toiter _optional

65 Numerical analysis and the control flow structuresTake a look at the problem of a Taylor expansion The series will be determined numerically until the additionalterms are smaller than a defined precision Look at the Taylor expansion of 11minusx = 1 + x + x2 + withx = 042s = 0 x = 1 s = 0 x = 1x0 = 042 x0 = 042while (x gt 1e-6) or while (x gt (1e-6)s)s = s + x s = s + xx = x x0 x = x x0end endThe approximation of 11minusx is returned in s (first letter of sum) In the first case (on the left) the iteration

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 3: Introduction to Programming Using Matlab

INTRODUCTION

During this course you will learn how to use Matlab to design and to perform mathematical computations

You will also get acquainted with basic programming If you learn to use this program well you will find it very useful in future since many technical or mathematical problems can be solved using Matlab

This text includes all material (with some additional information) that you need to know however many things are treated briefly Therefore ldquoThe Student Edition of Matlabrdquo userrsquos guide should be used as a complementary book during the course A sign of a book accompanied by page numbers placed in the left margin indicates where you can find more information Read the suggested pages to better understand the concepts discussed Where no reference to the book appears it means that only this text explains some ideas since they might be more about general programming than about Matlab Exercises are marked with also in the left margin The end of an exercise is marked with _

The text of this course includes some optional parts for volunteers or for more advanced students Such a part is enclosed between two horizontal lines with the word rsquooptionalrsquo on the first line There are also rsquointermezzorsquo parts which are not essential but provide some important information If you already know how to program in a language like Pascal or C you then may find it easier or more interesting to do the optional parts as well However if you do not have any idea about programming please feel free to skip those fragments It is important that you spend enough time to learn the Matlab basics that are introduced in the first few sections If you notice that you need more time than laboratory hours please consider doing some examples during the rest of the time

Since learning Matlab is a challenging task you are encouraged to prepare each laboratory you may read a part of text at home or try the examples yourself This way you can use laboratory time to ask questions in order to make things become clearer to you We suggest the following schedule for this course However you are free to decide about your own speed taking into account that on the 5th or 6th day you have to be able to start with the final assignment

DAY 1 SECTIONS 1 ndash 3

At the end of day 1 you should be able tobull recognize built-in variablesbull define variables and perform computations using thembull know how to suppress display with (semicolon)bull add and remove variables from the workspace check which variables are currently present in theworkspacebull use on-line help to get more information on a command and know how to use the lookfor commandbull use the load and save commands to readsave data to a filebull access files at different directories (manipulate path-changing commands)bull create vectors and matrices with direct assignment (using [ ])bull use linspace to create vectorsbull create random vectors and matricesbull extract elements from vectors and matrices with subscript notation eg x(5) A(ij)bull use colon notation to create vectors and extract ranges of elements from vectors and matricesbull apply transpose operators to vectors and matricesbull perform legal addition subtraction and multiplication operations on vectors and matricesbull understand the use of array operators like + and know why they are different from the regular + operatorsbull compute inner products and the Euclidean length of vectorsbull advanced create and manipulate complex vectors and matricesbull optional delete elements from vectors and matricesbull use the plot function to make simple plots and to plot several functions in one figurebull optional make some fancy plotsbull send figures to the printer or print them to a file

Remark If you do not have enough time to exercise on matrix operations next time you should start fromsection 25 However it would be very useful if you could already try things before that time

DAY 2 SECTIONS 4 - 6

At the beginning you should exercise once again with operations on matrices (section 25) Since they areessential in Matlab be sure that you fully understand how to perform themAt the end you should be able to

bull understand better the operations on vectors and matricesbull create and manipulate Matlab polynomialsbull fit a polynomial to databull evaluate a function integrate and differentiate itbull use relational operators lt lt= gt gt= == ~= and logical operators amp | and ~bull use if end if elseif end and if elseif else end and switch constructionsbull use for-loops and while-loops and know the difference between thembull understand how logical expressions are evaluated in the control flow structuresbull optional understand how to make approximations of Taylor expansions with the given precision

DAY 3 SECTIONS 7 ndash 9

At the beginning you should exercise once again with the control flow structures (section 61-64) since they are rsquobuilding blocksrsquo of programs that you will have to createAt the end you should be able to

bull understand better the control flow structuresbull create and manipulate string variables eg compare two strings concatenate them find a substring in a string convert a numberstring into a stringnumber etcbull use freely and with understanding the text inputoutput commands input disp and fprintfbull optional operate on cell arrays and structuresbull edit and run an m-file (both functions and scripts)bull identify the differences between scripts and functionsbull understand the concept of local and global variablesbull create a function with one or more input arguments and one or more output argumentsbull use comment statements to document scripts and functionsbull optional use the feval command - know how to pass a function name as an input argument to another function

DAY 4 SECTIONS 10 - 12 + EXERCISING ON WRITING FUNCTION M-FILES

At the end you should be able tobull understand better how to build function m-filesbull preallocate memory for vectors or matrices and know why and when this is beneficialbull replace basic loops with vectorized operationsbull use colon notation to perform vectorized operationsbull advanced use array indexing instead of loops to select elements from a matrixbull advanced use logical indexing and logical functions instead of loops to select elements from matricesbull perform low level input and output with fopen fscanf and fclosebull understand how to operate on text files (inputoutput operations)bull get more understanding on the use of fprintf while writing to a filebull optional understand how to operate on binary files (inputoutput operations)bull know and understand the importance of structural programming and debuggingbull know how to debug your programbull advanced write programs using the recommended programming style

Day 5

Polishing the knowledge and experiences gained with Matlab asking questions etc First steps in the directionof the final assignment

Day 6 - 7

The final assignment

PRELIMINARIES

Below you find a few basic definitions on computers and programming Please get acquainted with them since they introduce key concepts needed in the coming sections

bull A BIT (short for binary digit) is the smallest unit of information on a computer A single bit can hold only one of two values 0 or 1 More meaningful information is obtained by combining consecutive bits into larger units such as byte

bull A BYTE - a unit of 8 bits being capable of holding a single character Large amounts of memory are indicated in terms of kilobytes (1024 bytes) megabytes (1024 kilobytes) and gigabytes (1024 megabytes)

bull BINARY SYSTEM - a number system that has two unique digits 0 and 1 Computers are based on such a system because of its electrical nature (charged versus uncharged) Each digit position represents a different power of 2 The powers of 2 increase while moving from the right most to the left most position starting from 20 = 1 Here is an example of a binary number and its representation in the decimal system

10110 = 1 _ 24 + 0 _ 23 + 1 _ 22 + 1 _ 21 + 0 _ 20 = 16 + 0 + 4 + 2 + 0 = 24

bull DATA is information represented with symbols eg numbers words signals or images

bull A COMMAND is an instruction to do a specific task

bull An ALGORITHM is a sequence of instructions for the solution of a specific task in a finite number of steps

bull A PROGRAM is the implementation of an algorithm suitable for execution by a computer

bull A VARIABLE is a container that can hold a value For example in the expression x+y x and y are variables They can represent numeric values like 255 characters like rsquocrsquo or character strings like rsquoMatlabrsquoVariables make programs more flexible When a program is executed the variables are then replaced with real data That is why the same program can process different sets of data Every variable has a name (called the variable name) and a data type A variablersquos data type indicates the sort of value that the variable represents (see below)

bull A CONSTANT is a value that never changes That makes it the opposite of a variable It can be a numeric value a character or a string

bull A DATA TYPE is a classification of a particular type of information The most basic data types are- integer a whole number a number that has no fractional part eg 3- floating-point a number with a decimal point eg 35 or 12e-16 (this stands for 12 _ 10minus16)- character readable text character eg rsquoprsquo

bull A BUG is an error in a program causing the program to stop running not to run at all or to provide wrong results Some bugs can be very subtle and hard to find The process of finding and removing bugs is called debugging

bull A FILE is a collection of data or information that has a name stored in a computer There are many different types of files data files program files text files etc

bull An ASCII FILE is a standardized readable and editable plain text file

bull A BINARY FILE is a file stored in a format which is computer-readable but not human-readable Most numeric data and all executable programs are stored in binary files Matlab binary files are those with the extension rsquomatrsquo

1 How to work with Matlab

Matlab is a tool for mathematical (technical) calculations First it can be used as a scientific calculator it provides simple mathematical operations but handles complex numbers powers logarithms trigonometric operations as well Next it allows you to plot or visualize data in many different ways perform matrix algebra work with polynomials or integrate functions Like in a programmable calculator you can create execute and save a sequence of commands in order to make your computational process automatic It can be used to

store or retrieve data In the end Matlab can also be treated as a user-friendly programming language which gives the possibility to handle mathematical calculations in an easy wayRunning Matlab creates one or more windows on your screen The most important is the Matlab Command Window which is the place where you interact with Matlab The string gtgt is the Matlab prompt (except for the Student Edition that has the EDUgtgt prompt) When the Command window is active a cursor appears after the prompt indicating that Matlab is waiting for your command which can be eg 173 or cos(x)

11 Input via the command-line2-10 Matlab is an interactive system commands followed by Enter are executed immediately The results are ifdesired displayed on screen However execution of a command will not be possible or will go wrong when thecommand is not typed according to the rules Table 1 shows a list of commands used to solve the indicatedmathematical equation (a b x and y are numbers)There are also commands that perform a specific task such as help work with a file-system like cd or workwith matrices like rank Below you find basic information that is important when starting with Matlabbull Commands in Matlab are executed by pressing Enter or Return The output will be displayed onscreen immediately Try the followinggtgt 3 + 75gtgt 184gtgt 3 7Note that spaces are not important in Matlabbull The result of the last execution is called ans It can be used on the next command line Try for instancegtgt 144ans =35000gtgt ans^(-6)ans =54399e-0454399e-04 is a computer notation of 54399 _ 10minus4 (see Preliminaries) Note that ans is always overwrittenby the last commandbull ans is an example of a Matlab built-in variable It stores the result of the recently performed computationYou can also define your own variables Look how the information is stored in the variables aand bgtgt a = 144a =35000gtgt b = a^(-6)b =54399e-04Read Preliminaries to better understand the concept of variables You will learn more on Matlabvariables in section 23bull When the command is followed by a semicolon () the output is suppressed Check the differencebetween the following expressionsgtgt 3 + 75gtgt 3 + 75gtgt x = 34bull It is possible to execute more than one command at the same time the separate commands should thenbe divided by commas (to display the output) or by semicolons (to suppress the output display) eggtgt sin(pi4) cos(pi) sin(0)ans =07071ans =0Note that the value of cos(pi) is not printedbull The output may contain some empty lines this can be suppressed by the command format compactIn contrast the command format loose will insert extra empty lines4Mathematical notation Matlab-commanda + b a + ba minus b a - bab a b3xy 3 x ya

b a b or b a

ab a^bpx sqrt(x) or x^05_ pie exp(1)i i4 middot 103 4e3 or 410^33 minus 4i 3 - 4i or 3 - 4jsin x arctan x sin(x) atan(x) ex exp(x)ln x log(x)log x log10(x)|x| abs(x)Table 1 Translation of mathematical notation to Matlab commandsbull Matlab is case sensitive There is a difference between capital and normal letters for example a iswritten as a in Matlab A will result then in an errorbull All text after a percent sign until the end of a line is treated as a comment Enter eg the followinggtgt sin(314159) this is an approximation of sin(pi)You will notice that some examples in this text are followed by comments They are meant for you andyou should skip them while typing those examplesbull Previous commands can be fetched back with the -key The command can also be changed the and -keys may be used to move around in a line and edit itKeep in mind that Matlab executes the command immediately it might be useful to have an idea of theexpected outcome12 help-facilitiesMatlab provides assistance through extensive online help The help command is the simplest way to get349-359 help that is if you know the topic or command on which you want help For examplegtgt help elfungives information on the elementary math functions of Matlab The command help displays a list of allpossible topics The topic you want help on must be exact and spelled correctly The commando lookfor ismore useful if you do not know the exact name of the command or topic For examplegtgt lookfor inversedisplays all commands for which the word inverse is included in its help-text This command results in a list ofcommands with a short description Besides the help and lookfor commands there is also a separate mousedriven help The helpwin command opens a new window on screen which can be browsed in an interactiveway To learn more read pages 353-354 from rdquoThe Student Edition of Matlabrdquobook13 Interrupting a command or programSometimes you might spot an error in your command or program Due to this error it can happen that thecommand or program does not stop Pressing Ctrl-C forces Matlab to stop the process After this theMatlab-prompt (gtgt) re-appears This may take a while though514 PathIn Matlab commands or programs are contained in m-files which are just plain text files and have an37-39 extension rsquomrsquo The m-file must be located in one of the directories which Matlab automatically searchesThe list of these directories can be listed by the command path One of the directories that is always takeninto account is the current working directory which can be identified by the command pwd Use path addpathand rmpath functions to modify the path Here is an examplegtgt pathcmatlabcmatlabtoolboxmatlabgeneralcmatlabtoolboxmatlabopsgtgt addpath hpersonal assume that this is your directorygtgt pathhpersonalcmatlabcmatlabtoolboxmatlabgeneralcmatlabtoolboxmatlabopsIt is also possible to access the path browser from the File menu-bar instead15 Workspace issuesIf you work in the Command Window Matlab memorizes all commands that you entered (as you alreadyknow - to recall previous commands the -key is useful) and all variables that you created This can be6

2425verified with the commands who which gives a list of variables present in the workspace and whos whichincludes information on name number of allocated bytes and class of the variables For example assuming thatyou performed all commands given in the beginning after typing who you should get the following informationgtgt whoYour variables area ans b xThe command clear ltnamegt deletes the variable ltnamegt from the Matlab workspace clear or clear allremoves all variables This is useful when starting a new exercise For examplegtgt clear a xgtgt whoYour variables areans b16 Saving and loading dataThe easiest way to save or load Matlab variables is by using (clicking) the File menu-bar and then the Save26 Workspace as and Load Workspace items Also Matlab commands exist which allow you to saveand load data from filesThe command save allows for saving your workspace variables either into a binary file or an ASCII file (checkPreliminaries on binary and ASCII files) Binary files automatically get the rsquomatrsquo extension which is nottrue for ASCII files However it is recommended to add a rsquotxtrsquo or dat extensionExercise 1Learn how to use the save command by exercisinggtgt s1 = sin(pi4) s2 = sin(pi2)gtgt c1 = cos(pi4) c2 = cos(pi2)gtgt str = rsquohello worldrsquo this is a string example you will learn about strings latergtgt save saves all variables in binary format to the file matlabmatgtgt save data saves all variables in binary format to the file datamat6gtgt save numdata s1 c1 saves numeric variables s1 and c1 to the file numdatamatgtgt save strdata str saves a string variable str to the file strdatamatgtgtgtgt save allsin s saves all variables that match the pattern to allsinmatgtgt save allcosdat c -ascii saves c1c2 in 8-digit ascii format to allcosdat_The load command allows for loading variables into the workspace It uses the same syntax as saveExercise 2Assuming that you have done the previous exercise try to load variables from the created filesImportant before each load command clear the workspace and after loading check which variables arepresent in the workspace (using who)gtgt load loads all variables from the file matlabmatgtgt load data s1 c1 loads only specified variables from the file datamatgtgt load strdata loads all variables from the file strdatamatIt is also possible to read ASCII files that contain rows of space separated values Such a file may containcomments that begin with a percent character The resulting data is placed into a variable with the samename as the ASCII file (without the extension) Check for examplegtgt load allcosdat loads data from the file allcosdat into variable allcosgtgt who lists variables present in the workspace now_

2 Mathematics with numbers vectors and matricesThe basic element of Matlab is a matrix (or an array) Special cases arebull a 1 times 1-matrix a scalar or a single numberbull a matrix existing only of one row or one column a vector21 Single numbersYou have already got some experience with Matlab and you know that it can be used as a calculator To do4-614-1727that you can for example simply typegtgt 31256The result will beans =55714By default Matlab displays only 5 digits The command format long increases this number to 15 format

short reduces it to 5 again For examplegtgt format longgtgt 31256ans =557142857142857Exercise 3Define the format Matlab such that empty lines are suppressed and the output is given with 5 digitsCalculategtgt pigtgt sin(pi)Note that the answer is not exactly 0 _Use the command format to put Matlab in its standard-format ie short and loose7intermezzo

22 An introduction to floating-point numbersIn a computer numbers can be represented only in a discrete form It means that numbers are stored286 within a limited range and with a finite precision Integers can be represented exactly with the base of 2(read Preliminaries on bits and the binary system) The typical size of an integer is 16 bits so the largestpositive integer which can be stored is 216 = 65536 If negative integers are permitted then 16 bits allow forrepresenting integers between minus32768 and 32767 Within this range operations defined on the set of integerscan be performed exactlyHowever this is not valid for other real numbers In practice computers are integer machines and are capableof representing real numbers only by using complicated codes The most popular code is the floating pointstandard The term floating point is derived from the fact that there is no fixed number of digits before andafter the decimal point meaning that the decimal point can float Note that most floating-point numbers thata computer can represent are just approximations Therefore care should be taken that these approximationslead to reasonable results If a programmer is not careful small discrepancies in the approximations can causemeaningless results Note the difference between eg the integer arithmetic and floating-point arithmeticInteger arithmetic Floating-point arithmetic2 + 4 = 6 187 = 257143 4 = 12 25714 7 = 1799982511 = 2 100003 = 33333e+03When describing floating-point numbers precision refers to the number of bits used for the fractional partThe larger the precision the more exact fractional quantities can be represented Floating-point numbers areoften classified as single precision or double precision A double-precision number uses twice as many bits asa single-precision value so it can represent fractional values much better However the precision itself is notdouble The extra bits are also used to increase the range of magnitudes that can be representedMatlab relies on a computerrsquos floating point arithmetic You could have already noticed that in the last408-410 exercise since the value of sin(_) was almost zero and not completely zero It came from the fact that boththe value of _ is represented with a finite precision and the sin function is also approximatedThe fundamental type in Matlab is double which stands for a representation with a double precision It uses64 bits The single precision obtained by using the single type offers 32 bits Since most numeric operationsrequire high accuracy the double type is used by defaultThe exact machine precision might be defined as the smallest positive number _ that added to 1 does notchange the result so 1 + _ = 1 in floating-point arithmetic this value is larger than zero (in exact arithmeticof course _ = 0 holds) Matlab machine precision is stored in the built-in variable eps _ 22204e-16 Thismeans that the relative accuracy of individual arithmetic operations is about 16 digitsend intermezzo

23 Assignments and variablesWorking with complex numbers is easily done with MatlabExercise 4Choose two complex numbers for example -3 + 2i and 5 - 7i Try to add subtract multiply and dividethese two numbers _During this exercise the complex numbers had to be typed four times To reduce this assign each number to4-610-12a variable For the previous exercise this results ingtgt z = -3 + 2igtgt w = 5 - 7igtgt y1 = z + w y2 = z - w y3 = z w y4 = z w y5 = w zFormally there is no need to declare (ie define the name size and the type of) a new variable in Matlab Avariable is simply created by an assignment (the way it has been done above) Each newly created numerical

variable is always of the double type You can change this type by converting it into eg the single type 11a variable a is converted into a different type by performing eg a = single(a) a = int16(a) etc8In some cases when huge matrices should be handled and precision is not very important this might be a wayto proceed Also when only integers are taken into consideration it might be useful to convert the doublerepresentations into eg int16 or int321 integer types Since most computations should be performed with ahigh accuracy Matlab automatically chooses the double type It means that real numbers are approximatedwith the highest possible precision However it is important to emphasize that integer numbers are alwaysrepresented exactly no matter which numeric type is usedBear in mind that undefined values cannot be assigned to a variable So the following is not possiblegtgt clear x to make sure that x does not existgtgt fun = x^2 + 4 sin (x)It becomes possible bygtgt x = pi 3 fun = x^2 + 4 sin (x)Exercise 5Predict the result ofx = pi 3 x = x - 1 x = x + 5 x = abs(x) xCheck your prediction by performing these commands in Matlab _Exercise 6Here are some examples of different types of Matlab variables You do not need to understand them all nowsince you will learn more about them during the course Create them manually in Matlabgtgt this_is_my_very_simple_variable_today = 5 a number check what happens since thegtgt name is very long (gt 31 characters)gtgt 2t = 8 what is the problem with this commandgtgt this_is_a_matrix = [1 2 3 4 5 6] a matrixgtgt c = rsquoErsquo a charactergtgt str = rsquoHello worldrsquo a stringgtgt m = [rsquoJrsquorsquoorsquorsquohrsquorsquonrsquo] try to guess what it isCheck the types by using the command whos Use clear ltnamegt to remove a variable from the workspace _Exercise 7In addition to creating variables by assigning values to them a few other ways exist For instance there is anumber of built-in variables eg ans pi eps i inf or nan Find out what value is assigned to each of these74584 built-in variables _24 VectorsRow vectors are lists of numbers separated either by commas or by spaces They are examples of simple arrays41-49 The number of entries is known as the length of the vector (the command length exists as well) Their entitiesare referred to as elements or components The entries must be enclosed in [ ]gtgt v = [-1 sin(3) 7]v =-10000 01411 70000gtgt length(v)ans =3A number of operations can be done on vectors A vector can be multiplied by a scalar or addedsubtractedtofrom another vector with the same length or a number can be addedsubtracted tofrom a vector Allthese operations are carried out element-by-element Vectors can be also built from the already existing onesgtgt v = [-1 2 7] w = [2 3 4]gtgt z = v + w an element-by-element sumz =1 5 119gtgt v3 = v + 2 add 2 to all elements of vector v3v3 =1 4 9gtgt t = [2v -w]ans =-2 4 14 -2 -3 -4Also a particular value can be changed or displayedgtgt v(2) = -1 w(2) change the 2nd value of v display the 2nd value of wv =-1 -1 7ans =

3A colon notation is an important shortcut used when producing row vectors (see Table 3 and help colon)gtgt 25ans =2 3 4 5gtgt -23ans =-2 -1 0 1 2 3In general firststeplast produces a vector of entities with the value first incrementing by the stepuntil it reaches lastgtgt 020524ans =02000 07000 12000 17000 22000gtgt -3310ans =-3 0 3 6 9gtgt 15-05-05 negative step is also possibleans =15000 10000 05000 0 -05000Parts of vectors can be extracted by using a colon notationgtgt r = [-126 2 3 -2] -126 =gt -1 1 3 5r =-1 1 3 5 2 3 -2gtgt r(36) get elements of r which are on the positions from 3 to 6ans =3 5 2 3gtgt r(125) get elements of r which are on the positions from 1 to 5 taken with the step of 2ans =-1 3 2gtgt r(5-12) what will you get hereTo create column vectors you should separate entries by a semicolon () or by new linesgtgt f = [-1 3 5]f =-135The same operations as on row vectors can be done on column vectors However you cannot for exampleadd a column vector to a row vector To do that you need an operation called transposing which converts acolumn vector into a row vector and vice versa10gtgt f = [-1 3 5] a column vectorgtgt frsquo frsquo is a row vectorans =-1 3 5gtgt v = [-1 2 7] a row vectorgtgt f + v you cannot add a column vector f to a row vector v Error using ==gt +Matrix dimensions must agreegtgt frsquo + vans =-2 5 12gtgt f + vrsquoans =-2512If x is a complex vector than xrsquo gives the conjugate transpose of x eggtgt x = [1+2i -1+i]x =10000 + 20000i -10000 + 10000igtgt xrsquo this is the conjugate transposeans =10000 - 20000i-10000 - 10000i

gtgt xrsquo this is the rsquonormalrsquo transposeans =10000 + 20000i-10000 + 10000iExercise 8Exercise to become acquainted with operating on row and column vectors Enter all examples given in thissection and make new variations yourself Exercise with the colon notation approach as well _25 MatricesAn ntimesk matrix is a rectangular array of numbers having n rows and k columns Defining a matrix in Matlabis similar to defining a vector The generalization is straightforward if you know that a matrix consists of row49-6175-86vectors (or column vectors) Commas or spaces are used to separate elements in a row and semicolons areused to separate individual rows For example the matrix A =01 2 34 5 67 8 91Ais defined asgtgt A = [1 2 3 4 5 6 7 8 9] row by row inputA =1 2 34 5 67 8 9Another examples are for instancegtgt A2 = [14 -125]A2 =1 2 3 4-1 1 3 5gtgt A3 = [1 3-4 7]A3 =1 3-4 711Command ResultA(ij) Aij

A(j) j-th column of AA(i) i-th row of AA(klmn) (l minus k + 1) times (n minus m + 1) matrix with elements Aij with k _ i _ l m _ j _ nv(ij)rsquo rsquovector-partrsquo (vi vi+1 vj) of vector vTable 2 Manipulation of (groups of) matrix-elementsCommand Resultn = rank (A) n becomes the rank of matrix Ax = det (A) x becomes the determinant of matrix AC = size (A) C becomes a row-vector with 2 elements the number of rows and columns of Ax = trace (A) x becomes the trace (sum of diagonal elements) of matrix Ax = norm (v) x becomes the length of vector vC = A + B sum of two matricesC = A - B subtraction of two matricesC = A B multiplication of two matricesC = A B rdquoelement-by-elementrdquo multiplication (A and B are of equal size)C = A ^ k power of a matrix (k 2 Z can also be used for Aminus1)C = A ^ k rdquoelement-by-elementrdquo power of a matrixC = Arsquo the transposed of a matrix AT

C = A B rdquoelement-by-elementrdquo division (A and B are of equal size)U = A B finds the solution that minimizes the squared error in Ax minus BU = B A solution of XA = B analogous to the previous commandC = inv (A) C becomes the inverse of AC = null (A) C is an orthonormal basis for the null space of Aobtained from the singular value decompositionC = orth (A) C is an orthonormal basis for the range of AC = rref (A) C is the reduced row echelon form of AL = eig (A) L is a vector containing the -possibly complex- eigenvalues of a square matrix A[X D] = eig (A) produces a diagonal matrix D of eigenvalues and a full matrix X

whose columns are the corresponding eigenvectors of AS = svd (A) S is a vector containing the singular values of A[U S V] = svd (A) S is a diagonal matrix of the same dimension as Awith nonnegative diagonal elements in decreasing orderThe columns U and V are the accompanying singular vectorsx = linspace(a b n) generates a vector x of n equally spaced points between a and bx = logspace(a b n) generates a vector x starting at 10a and ended at 10b containing n valuesA = diag (v) gives a diagonal matrix with the elements v1 v2 vn on the diagonalA = eye (n) A is a n times n identity matrixA = zeros (n m) A is a n times m matrix with zeros (default m = n)A = rand (n m) A is a n times m matrix with elements uniformly distributed between 0 and 1A = randn (n m) ditto - with elements standard normal distributedv = max (A) v becomes a vector with the maximum value of the elements in each column of Aor v is the maximum of all elements if A is a vectorv = min (A) ditto - with minimumv = sum (A) ditto - with sumTable 3 Frequently used matrix operations and functions12Transposing a vector changes it from a row to a column or the other way around This idea can be extendedto a matrix where transposing interchanges rows with the corresponding columns as in the examplegtgt A2 A2rsquoA2 =1 2 3 4-1 1 3 5ans =1 -12 13 34 5gtgt size(A2) returns the size (dimensions) of a matrixans =2 4gtgt size(A2rsquo)ans =4 2There exists also some built-in matrices of size specified by the user (see Table 2) A few examples are givenbelowgtgt E = [] an empty matrix of 0-by-0 elementsE =[]gtgt I = eye(3) the identity matrixI =1 0 00 1 00 0 1gtgt B = rand(23) a matrix of random numbers you will get a different one00227 09101 0922200299 00640 03309gtgt O = ones(32)O =1 11 11 1gtgt r = [1 3 -2] R = diag(r) create a diagonal matrix with r on the diagonalR =1 0 00 3 00 0 -2gtgt v = linspace(124) a vector is also an example of a matrixv =10000 13333 16667 20000It is often needed to build a larger matrix from the smaller onesgtgt x = [4 -1] y = [-1 4]x =4

-1y =-1 4gtgt X = [x yrsquo] X consists of the columns x and yrsquoX =4 -1-1 4gtgt T = [ -1 3 4 4 5 6] t = 1313gtgt T2 = [T t] add to T a new row namely the row vector t getting T2T2 =-1 3 44 5 61 2 3gtgt G = [1 5 4 5 0 2] G is a matrix of the 3-by-2 size check size(G)gtgt T3 = [T2 G] T3 consists of T2 and new columns being the colums of GT3 = added at the end of T2-1 3 4 1 54 5 6 4 51 2 3 0 2gtgt [diag(56) ones(32)]ans =5 00 61 11 11 1A part can be extract from a matrix in a similar way as from a vector Each element in the matrix is indexedby a row and a column to which it belongs Mathematically the element from the i-th row and the j-thcolumn of the matrix A is denoted by Aij Matlab provides the A(ij) notationgtgt A = [13 46 79]A =1 2 34 5 67 8 9gtgt A(12) A(23) A(31)ans =2ans =6ans =7gtgt A(43) A is a 3-by-3 matrix Index exceeds matrix dimensionsgtgt A(23) = A(23) + 2A(11)A =1 2 34 5 87 8 9Having defined a matrix it is easy to extended it automatically For the matrix A it can be done eg asfollowsgtgt A(52) = 5 assign 5 to the position (52) the uninitializedA = elements become zeros1 2 34 5 87 8 90 0 00 5 0Different parts of the matrix A can be now extractedgtgt A(2) extract the 2nd column of Aans =25814

05gtgtgt A(34) extract the rows 3rd and 4th of Aans =7 8 90 0 0gtgt A(2312) extract a part of Aans =4 57 8If needed the other zero elements of the matrix A can be also defined by eggtgt A(4) = [1 2 3] assign vector [1 2 3] to the 4th row of Agtgt A(5[13]) = [4 5] a rsquoshortcutrsquo when assigning A(51) = 4 and A(53) = 5gtgt A how does the matrix A look like nowAs you have seen in the examples above it is possible to manipulate (groups of) matrix-elements Thecommands are shortly explained in Table 2Exercise 9Define the matrix A = [14 58 1 1 1 1] Predict and check the result ofgtgt B = A(3)gtgt C = A(1322)gtgt A(11) = 9gtgt A(2313) = [0 0 0 0 0 0]gtgt A(l212) = [l l 3 3]gtgt A = A(3314)_Exercise 10Define the matrices T=[ 3 4 1 8 -4 3] A = [diag(-123) T -4 4 1 2 1] Perform the followingoperations on the matrix Abull extract a vector consisting of the 2nd and 4th elements of the 3rd rowbull find the minimum of the 3rd columnbull find the maximum of the 2nd rowbull compute the sum of the 2nd columbull compute the mean of the 1st and 4th rowsbull extract the submatrix consisting of the 1st and 3rd rows and all columnsbull extract the submatrix consisting of the 1st and 2nd rows and the 3rd 4th and 5th columnsbull compute the total sum of the 1st and 2nd rowsbull add 3 to all elements of the 2nd and 3rd colums_Table 3 shows some frequently used matrix operations and functions A few examples are provided belowgtgt B = rand(23) a matrix of random numbers you will get a different oneB =09501 06068 0891302311 04860 07621gtgt B2 = [1 2 5 1 5 6]gtgt B + B2rsquo add two matrices why B2rsquo is needed instead of B2ans =19501 56068 5891322311 14860 67621gtgt S = ans4 divide all elements of the matrix ans by 4S =04875 14017 1472805578 03715 1690515gtgt C = [1 -1 4 7 0 -1]gtgt B C matrix multiplication is not defined for B and C Error using ==gt Inner matrix dimensions must agreegtgt B C but you can multiply element-by-elementans =09501 -06068 3565216180 0 -07621gtgt D = B Crsquo or you can make the multiplication legal Crsquo is now 3-by-2D =39085 5759627935 08559

gtgt D^3 this is equivalent to D D Dans =1992503 2041413990133 910548gtgt D^3 - 2 do for all elements raise to the power 3 and subtract 2ans =577069 1890638198005 -13731gtgtgtgt r = [1 3 -2]r B2 this is a legal operation r is a 1-by-3 matrix and B2 isans = 3-by-2 matrix B2 r is an illegal operation6 -7Remind that an n-by-k matrix A (having n rows and k columns) can be multiply by another matrix B onlyif B has k rows ie S is of the k-by-m size (m is arbitrary) As a result you get an n-by-m matrixA ˙B = C A 2 Rntimesk B 2 Rktimesm C 2 Rntimesm

RemarkYou can now compute the inner product between two vectors x and y xT y = Pi xi yi in a simple waygtgt f = [-1 3 5] a column vectorgtgt v = [-1 2 7] a column vectorgtgt frsquo v this is the inner productans =42gtgt f vrsquo be careful now a 3-by-1 matrix is multiplied by a 1-by-3gtgt matrix which results in a 3-by-3 matrix (the outer product)ans =1 -2 -7-3 6 21-5 10 35gtgt f v this is an element-by-element multiplication1635gtgt sum (f v) this is an another way to compute the inner productans =42Exercise 11Perform all operations from Table 3 using chosen matrices A and B vector v and scalars k a b n and m _Exercise 12Let A be a random 3 times 3 matrix and b a random 3 times 1 vector Given that Ax = b then x = Aminus1b Find x(there exist at least two possible commands to do this look at Table 3) _optionalThe concept of an empty matrix [] is also very useful in Matlab For instance a few columns or rows canbe removed from a matrix by assigning an empty matrix to it Try for example16Symbol Color Symbol Styley yellow dotted liner red o circlesg green - solid lineb blue - dashdotted lineTable 4 Plot colors and stylesgtgt C = [1 2 3 4 5 6 7 8 1 1 1 1]gtgt D = C D(2) = [] now a copy of C is in D remove the 2nd column of Dgtgt C ([13]) = [] remove the rows 1 and 3 from Cend optional

3 VisualizationMatlab can be used to visualize the results of an experiment Therefore you should define variables each ofthem containing all values of one parameter to plot31 Simple plotsWith the command plot a graphical display can be made plot(y) draws the points (1 y(1)) (2 y(2)) 184 (n y(n)) and connects the points with a straight line plot(xy) does the same for (x(1) y(1)) (x(2) y(2)) (x(n) y(n)) x and y have to be row- or column vectors of equal lengthThe commands loglog semilogx and semilogy are similar to plot except that they use logarithmic axesExercise 13Type the following commands after predicting the resultgtgt x = 0330

gtgt y = 2^[010] this is the same as y = [1 2 4 8 16 32 64 128 256 512 1024]gtgt plot(xy) to get a graphic representationgtgt semilogy(xy) to get logarithmic axesAs you can see the same figure is used for both plot commands The previous function is removed as soonas the next is displayed The command figure gives you an extra figure Repeat the previous commandsbut generate a new figure before plotting the second function so that you can see both functions in separatewindows You can also switch back to a figure using figure(n) where n is its number _Exercise 14Make a plot such that the coordinates (2 6) (25 18) (5 175) (42 125) and (212) are connected by aline _Exercise 15Plot the function y = sin(x) + x minus x cos(x) in two separate figures for the intervals 0 lt x lt 30 andminus100 lt x lt 100 _32 Several functions in one figureWhen more than one function is plotted in one figure it might be useful to use different markers and colors184-188197-201Table 4 shows a few possibilities help plot shows allThere are different ways to get more than one function into a figure The first one is with the command holdon After this command all functions will be plotted in the same figure until the command hold off is usedAn examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt plot (x1 y1 rsquordrsquo)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)17gtgt hold ongtgt plot (x2 y2 rsquoy-rsquo)gtgt plot (x1y1rsquok-rsquo)gtgt hold offA second method to display more than one function in one figure is to plot several functions at the same timeThe next commands will have the same results as the commands in the previous examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt plot (x1 y1rsquordrsquo x2 y2 rsquoy-rsquo x1 y1 rsquok-rsquo)It is also possible to get more than one figure in one figure window With the command subplot the windowcan be horizontally and vertically divided into any number of subfiguresgtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt subplot(131) plot (x1 y1rsquordrsquo)gtgt subplot(132) plot (x2 y2 rsquoy-rsquo)gtgt subplot(133) plot (x1 y1 rsquok-rsquo)optional

33 Other 2D plotting featuresIn the introduction of this chapter some commands similar to plot loglog semilogx and semilogy were201-211 mentioned There are however more ways to display dataExercise 16To get an impression of other visualizations type the following commands and describe the result (note thatthe command figure creates a new figure window)gtgt figure bar plot of a bell shaped curvegtgt x = -290229gtgt bar (x exp (-xx))gtgt figure stairstep plot of a sine wavegtgt x = 002510gtgt stairs (x sin (x))gtgt figure errorbar plotgtgt x = -2012gtgt y = erf (x) error function check help if you are interestedgtgt e = rand (size (x)) 10gtgt errorbar (x y e)

_end optional

34 PrintingBefore printing a figure you made you might want to add some information such as a title or change the189-196 lay-out a little Table 5 shows some of the commands that can be usedExercise 17Plot the functions y1 = sin(4x) y2 = x cos(x) y3 = (x + 1)minus1px for x = 0 025 10 and a single point(x y) = (4 5) in one figure with different colors and styles Make a legend containing the three functionsMake labels for both axes and a title Add a text to the single point saying single point Change the minimumand maximum values of the axes such that function y3 can be looked at in more detail _When the displayed figure is to your liking you can print it to paper The easiest way to do this is to click onFile in the menu-bar and to choose Print If in the print window you click OK your figure will be printed onthe printer indicated in the print window18Command Resultgrid onoff adds a grid to the plot at the tick marks or removes itaxis([xmin xmax ymin ymax]) sets the minimum and maximum values of the axesbox offon removes the axes box or shows itxlabel(rsquotextrsquo) plots the label text on the x axisylabel(rsquotextrsquo) plots the label text on the y axistitle(rsquotextrsquo) plots a title above the graphtext(xyrsquotextrsquo) adds text at the point (xy)gtext(rsquotextrsquo) adds text at a manually (with a mouse) indicated pointlegend(rsquofun1rsquorsquofun2rsquo) plots a legend box (move it with your mouse) to name your functionslegend off deletes the legend boxTable 5 Plot-manipulationsThere is also a print command which can be used to send a figure to a printer or output it to a file Youcan optionally specify a print device (ie an output format such as tiff or postscript) and options that controlvarious characteristics of the printed file (ie which Figure to print etc) You can also print to a file if youspecify the file name If you do not provide an extension print adds one Since they are many parametersthey will not be explained here (check help print to learn more) Instead try to understand the examplesgtgt print -dwinc print the current Figure to the current printer in colorgtgt print -f1 -deps myfileeps print Figure no1 to the file myfileeps in blackgtgt print -f1 -depsc myfileceps print Figure no1 to the file myfilecoleps in colorgtgt print -dtiff myfile1tiff print the current Figure to the file myfile1tiffgtgt print -dpsc myfile1cps print the current Figure to the file myfile1ps in colorgtgt print -f2 -djpeg myfile2 print Figure no2 to the file myfile2jpgExercise 18Exercise with printing (especially to a file) the figure from Exercise 16 _

4 Curve fitting and interpolationThere are two ways to describe data with an analytical function- curve fitting or regression finding a smooth curve that best fits (approximates) the data accordingto a criterion (eg best least square fit) The curve does not have to go through any of the data points- interpolation the data are assumed to be correct desired in a way to describe what happens betweenthe data points In other words given a finite set of points the goal of interpolation is to find a functionfrom a given class of functions (eg polynomials) which passes through the specified pointsThe figure below illustrates the difference between regression (curve fitting) and interpolationminus5 0 5minus6minus4minus20246810fiting a 3rd order polynomialinterpolation

41 Curve fittingMatlab interprets the best fit of a curve by the lsquoleast squares curve fittingrsquo The curve used is restricted153-15619to polynomials With the command polyfit any polynomial can be fitted to the data polyfit (x y n)finds the coefficients of a polynomial of degree n that fits the data (finds the linear relation between x and y)Letrsquos start with finding a linear regression of some datagtgt x = 010gtgt y = [-10 24 102 158 284 276 299 405 483 522 751]gtgt p = polyfit (x y 1) find the fitting polynomial of order 1p = 06772 -03914

The output of polyfit is a row vector of the polynomial coefficients the solution of this example is thereforey = 06772x minus 03914Exercise 19Execute the above example Plot the data and the fitted curve in a figure Determine the 2nd and 9th orderpolynomial of these data as well and display the solution in a figureHint x1 = linspace (xmin xmax n) results in a vector with n element evenly distributed from xmintill xmax z = polyval (p x1) calculates the values of the polynomial for every element of x1 _Exercise 20Define x and y as followsgtgt x = -55gtgt y = 02x^3 - x + 2 a 3rd order polynomialgtgt y = y + randn(111) add some noise to yDetermine the 3rd order polynomial fitting y (note that because of added noise the coefficients are differentthat originally chosen) Try some other polynomials as well Plot the results in a figure _42 InterpolationThe simplest way to examine an interpolation is by displaying the function plots with the command plot157-161 The neighboring data points are connected with straight lines This is called a linear interpolation Whenmore data-points are taken into account the effect of interpolation becomes less visible Analyzegtgt x1 = linspace(0 2pi2)gtgt x2 = linspace(0 2pi4)gtgt x3 = linspace(0 2pi16)gtgt x4 = linspace(0 2pi256)gtgt plot(x1sin(x1)x2sin(x2)x3sin(x3)x4sin(x4))gtgt legend(rsquo2 pointsrsquorsquo4 pointsrsquorsquo16 pointsrsquorsquo256 pointsrsquo)

5 Numerical analysisNumerical analysis can be used whenever it is impossible or very difficult to determine the analytical solutionMatlab can be used to find for example the minimum maximum or integral of a certain function51 Evaluation of a functionAs said before the command plot plots a function by connecting defined data points Sometimes however a168-173 function is constant and not very interesting over some range and then acts unexpectedly wildly over anotherWith plot this function might be misinterpreted The command fplot is then useful An examplegtgt x = 0pi82pigtgt y = sin (8x)gtgt plot (x y rsquobrsquo)gtgt hold ongtgt fplot (rsquosin (8z)rsquo [0 2pi] rsquorrsquo)gtgt title (rsquosin (8z)rsquo)gtgt hold off20Command Resultfplot (rsquofunrsquo [min x max x]) plots the function fun for min x till max xfmin (rsquofunrsquo min x max x) gives the x-value of the miminum of thefunction fun between min x and max xfzero (rsquofunrsquo x0) gives the x-value for which the functionfun is zero in the neighborhood of x0Table 6 Evaluation of a functionExecution of these commands results in a figure with an almost straight blue line and a red sine fplot canalso be used to plot a defined functiongtgt f = rsquosin (8z)rsquogtgt fplot (f [0 2pi] rsquorrsquo)gtgt title (f)Other useful commands for a detailed study of a range of a function are listed in Table 6Exercise 21The command fmax does not exist Use one or more of the commands from Table 6 to determine the maximumof the function x cos(x) for 10 lt x lt 15 _52 Integration and differentiationThe integral- or the surface underneath a 2D function- can be determined with the command trapz trapz173-182 does this by measuring the surface between the x-axis and the -by a straight line connected- data points Theaccuracy of this method depends on the distance between the data pointsgtgt x = 00510 y = 05 sqrt (x) + x sin (x) area1 = trapz (x y)

area1 =181655gtgt x = 000510 y = 05 sqrt (x) + x sin (x) area2 = trapz (x y)area2 =183846Differentiation is done by determining the slope in each data point Numerically this is done by first fitting apolynomial followed by differentiating this functiongtgt x = 010gtgt y = [-10 24 102 -158 284 276 775 35 483 522 751]gtgt p = polyfit (x y 5)p = 00026 -00554 03634 -06888 02747 00877gtgt dp = polyder (p)dp = 00132 -02216 10903 -13776 02747gtgt x1 = linspace (0 10 200)gtgt z = polyval (p x1)gtgt dz = polyval (dp x1)gtgt plot (x y rsquog-rsquo x1 z rsquobrsquo x1 dz rsquorrsquo)gtgt legend (rsquodata pointsrsquo rsquocurve fitrsquo rsquoderivativersquo)Exercise 22Determine the integral and derivative of the 4th polynomial fitted through (xy) with x = [4 5 6 7 8 9 1011 12 13] y = [1284 1200 724 -096 -1116 -2096 -2700 -2496 -956 2544] _

6 Control flowAs you know it is possible to execute more than one command at the same time (see section 11) Theseparate commands should then be divided by commarsquos (to display the output) or by semicolons (to suppress21output display) Control flow loops increase the number of possibilities A control flow structure is a block ofcommands that allows conditional code execution and making loops61 Logical and relational operatorsTo use control flow commands it is necessary to perform operations that result in logical values TRUE or88-91 FALSE In Matlab the result of a logical operation is 1 if it is true and 0 if it is false Table 7 shows therelational and logical operations2 Another way to get to know more about them is to type help relop Therelational operators lt lt= gt gt= == and ~= can be used to compare two arrays of the same size or anarray to a scalar The logical operators amp | and ~ allow for the logical combination or negation of relationaloperators In addition three functions are also available xor any and all (use help to find out more)Important The logical amp and | have the equal precedence in Matlab which means that those operatorsassociate from left to right A common situation isgtgt b = 10gtgt 1 | b gt 0 amp 0ans =0gtgt (1 | b gt 0) amp 0 this indicates the same as aboveans =0gtgt 1 | (b gt 0 amp 0)ans =1This shows that you should always use brackets to indicate in which way the operators should be evaluatedCommand Resulta = (b gt c) a is 1 if b is larger than c Similar are lt gt= and lt=a = (b == c) a is 1 if b is equal to ca = (b ~= c) a is 1 if b is not equal ca = ~b logical complement a is 1 if b is 0a = (b amp c) logical AND a is 1 if b = TRUE AND c = TRUEa = (b | c) logical OR a is 1 if b = TRUE OR c = TRUETable 7 Relational and logical operationsExercise 23Predict and check the result of each of the operations of Table 7 for b = 0 and c = -1 _Exercise 24Define two vectors with seven elements (randn(17)) and perform all logical operations including xor anyand all _Exercise 25While doing logical operations between a vector and a scalar each element of the vector is compared to thescalar Predict and check the result of each logical operator for the vector b = [2 31 -40 0] and the scalarc = 0 _Before moving on check whether you now understand the following relations

gtgt a = randperm(10) a random permutation of the numbers from 1 to 10gtgt b = 110gtgt b - (a lt= 7) subtracts from b a 0-1 vector taking 1 for a lt= 7 and 0 otherwisegtgt (a gt= 2) amp (a lt 4) returns ones at positions where 2 lt= a lt 4gtgt ~(b gt 4) returns ones at positions where b lt= 4gtgt (a == b) | b == 3 returns ones at positions where a is equal to b or b is equal to 3gtgt any (a gt 5) returns 1 when ANY of the a elements are larger than 5gtgt any (b lt 5 amp a gt 8) returns 1 when there in the evaluated expressiongtgt (b lt 5 amp a gt 8) appears at least one 1gtgt all (b gt 2) returns 1 when ALL b elements are larger than 22rdquoequal tordquo in the table on page 88 of rdquoThe Student Edition of Matlabrdquo must be rdquo==rdquo instead of rdquo=rdquo2262 Conditional code executionSelection control structures if-blocks are used to decide which instruction to execute next depending whether117-119 expression is TRUE or not The general description is given below In the examples below the command dispis frequently used This command displays on the screen the text between the quotesbull if endSyntaxif logical_expressionstatement1statement2endExampleif (a gt 0)b = adisp (rsquoa is positiversquo)endbull if else endSyntaxif logical_expressionblock of statementsevaluated if TRUEelseblock of statementsevaluated if FALSEendExampleif (temperature gt 100)disp (rsquoAbove boilingrsquo)toohigh = 1elsedisp (rsquoTemperature is OKrsquo)toohigh = 0endbull if elseif else endSyntaxif logical_expression1block of statements evaluatedif logical_expression1 is TRUEelseif logical_expression2block of statements evaluatedif logical_expression2 is TRUEelseblock of statements evaluatedif no other expression is TRUEendExampleif (height gt 190)disp (rsquovery tallrsquo)elseif (height gt 170)disp (rsquotallrsquo)elseif (height lt 150)disp (rsquosmallrsquo)

elsedisp (rsquoaveragersquo)endRemark To do the exercises below a script m-file will be useful It is an external file that contains asequence of Matlab commands What you need to do is to open an editor enter all commands needed forthe solution of a task save it with the extension rsquomrsquo (eg mytaskm) and then run it from the CommandWindow by typing mytask To open the Matlab editor go to the File menu-bar choose the Open optionand then m-file A new window will appear where you can write your scripts and save them on the disk Allcommands in the script will be executed in Matlab You will learn more on script m-files in section 91Important m-script file must be saved in one of the directories in Matlabrsquos pathAn example A script shortm can be created from the two lines given below and run by calling shortx = 0054plot (x sin(x) rsquo-rsquo)Exercise 26Create a script that asks for a number N and computes the drag coefficient C depending on the Reynoldrsquos23number N (make use of the if elseif construction) The command input might be useful here(read pages 32-33 from rdquoThe Student Edition of Matlabrdquoor use help)C =8gtgtgtltgtgtgt0 N _ 024N N 2 (0 01]24N (1 + 014N07) N 2 (01 1e3]043 N 2 (1e3 5e5]019 minus 8e4N N gt 5e5Check whether your script works correctly Compute the drag coefficient for eg N = -3e3 001 56 1e3 3e6(remember that eg 3e3 is a Matlab notation of 3 _ 103) _Exercise 27Write a script that asks for an integer and checks whether it can be divided by 2 or 3 Consider all possibilitiessuch as divisible by both 2 and 3 divisible by 2 and not by 3 etc (use the command rem) _Another selection structure is switch which switches between several cases depending on an expression which119-120 is either a scalar or a stringSyntaxswitch expressioncase choice1block of commands1case choice2a choice2bblock of commands2otherwiseblock of commandsendExamplemethod = 2switch methodcase 12disp(rsquoMethod is linearrsquo)case 3disp(rsquoMethod is cubicrsquo)case 4disp(rsquoMethod is nearestrsquo)otherwisedisp(rsquoUnknown methodrsquo)endThe statements following the first case where the expression matches the choice are executed Thisconstruction can be very handy to avoid long if elseif else end constructions Theexpression can be a scalar or a string A scalar expression matches a choice if expression == choice Astring expression matches a choice if strcmp(expression choice) returns 1 (is true) (strcmp is a commandcomparing two strings)Important Note that the switch-construction only allows the execution of one group of commandsExercise 28Assume that the months are represented by numbers from 1 to 12 Write a script that asks you to provide a

month and returns the number of days in that particular month Alternatively write a script that asks youto provide a month name (eg rsquoJunersquo) instead of a number Use the switch-construction _63 LoopsIteration control structures loops are used to repeat a block of statements until some condition is met Two114-117 types of loops existbull the for loop that repeats a group of statements a fixed number of timesSyntaxfor index = firststeplastblock of statementsendExamplesumx = 0for i=1length(x)sumx = sumx + x(i)end24You can specify any step including a negative value The index of the for-loop can be also a vectorSee some examples of possible variationsExample 1for i=12nendExample 2for i=n-13endExample 3for x=0054disp(x^2)endExample 4for x=[25 9 81]disp(sqrt(x))endbull while loop which evaluates a group of commands as long as expression is TRUESyntaxwhile expressionstatement1statement2statement3endExampleN = 100iter = 1msum = 0while iter lt= Nmsum = msum + iteriter = iter + 1endExercise 29Given the vectors x and y write a script computing the a matrix whose elements should be created accordingto a formula given below (make use of the length command to check the number of elements in both vectors)- aij = yixj (make sure that a division by zero will not occur)- bij = xi _ yj

- cij = 1 max (xi yj)_Exercise 30Determine the sum of the first 50 squared numbers with a control loop _Exercise 31Write a script to find the largest value n such that the sum p13 + p23 + + pn3 is less than 1000 _optionalExercise 32Write a script that transposes a matrix A Check its correctness with the Matlab operation Arsquo _Exercise 33

Write a script that asks for a temperature in degrees Celsius tc and computes the equivalent temperature indegrees Fahrenheit tf (use the formula tf = 95 _ tc + 32) The script should keep running until no numberis provided to convert The functions input and isempty (use help to learn more) should be useful here _end optional

64 Evaluation of logical and relational expressions in the control flow structuresThe relational and logical expressions may become more complicated It is not difficult to operate on them ifyou understand how they are evaluated To explain more details let us consider the following exampleif (~isempty(data)) amp (max(data) lt 5)endThis construction of the if-block is necessary to avoid comparison if data happens to be an empty matrix Insuch a case you cannot evaluate any expression and Matlab gives an error The amp operator returns 1 only ifboth expressions ~isempty (data) and max(data) lt 5 are true and 0 otherwise When data is an emptymatrix the next expression is not evaluated since the whole amp-expression is already known to be false Thesecond expression is checked only if data is a non-empty matrix Remember to put logical expression unitsbetween brackets to avoid wrong evaluations25Important The fact that computers make use of floating-point arithmetic means that often you should becareful when comparing two floating-point numbers just byif (x == y)end(Of course such a construction is allowed eg when you know that x and y represent integers) Instead of theabove construction you may try using thisif (abs (x - y) lt tolerance) eg tolerance = 1e-10endExercise 34Consider the following examplemax_iter = 50tolerance = 1e-4iter = 0xold = 01x = 1while (abs (x - xold) gt tolerance) amp (iter lt max_iter)xold = xx = cos(xold)iter = iter + 1endThis short program tries to solve the equation cos(x) = x (x is the solution found) Make the script solve cosfrom the presented code Note that the while-loop is repeated as long as both conditions are true If eitherthe condition (|x - xold| lt= tolerance) or (iter gt= max iter) is fulfilled then the loop is quitted Runthe script solve cos for different tolerance parameters eg 1e-3 1e-6 1e-8 1e-10 etc Use format long tocheck more precisely how much the found x is really different from cos(x) For each tolerance value checkthe number of performed iterations (iter value) _Exercise 35Create the script solve cos2 which is equal to the one given replacing the while-loop condition bywhile (abs (x - xold) gt tolerance) | (iter lt max_iter)Try to understand the difference and confirm your expectations by running solve cos2 What happens toiter _optional

65 Numerical analysis and the control flow structuresTake a look at the problem of a Taylor expansion The series will be determined numerically until the additionalterms are smaller than a defined precision Look at the Taylor expansion of 11minusx = 1 + x + x2 + withx = 042s = 0 x = 1 s = 0 x = 1x0 = 042 x0 = 042while (x gt 1e-6) or while (x gt (1e-6)s)s = s + x s = s + xx = x x0 x = x x0end endThe approximation of 11minusx is returned in s (first letter of sum) In the first case (on the left) the iteration

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 4: Introduction to Programming Using Matlab

At the beginning you should exercise once again with operations on matrices (section 25) Since they areessential in Matlab be sure that you fully understand how to perform themAt the end you should be able to

bull understand better the operations on vectors and matricesbull create and manipulate Matlab polynomialsbull fit a polynomial to databull evaluate a function integrate and differentiate itbull use relational operators lt lt= gt gt= == ~= and logical operators amp | and ~bull use if end if elseif end and if elseif else end and switch constructionsbull use for-loops and while-loops and know the difference between thembull understand how logical expressions are evaluated in the control flow structuresbull optional understand how to make approximations of Taylor expansions with the given precision

DAY 3 SECTIONS 7 ndash 9

At the beginning you should exercise once again with the control flow structures (section 61-64) since they are rsquobuilding blocksrsquo of programs that you will have to createAt the end you should be able to

bull understand better the control flow structuresbull create and manipulate string variables eg compare two strings concatenate them find a substring in a string convert a numberstring into a stringnumber etcbull use freely and with understanding the text inputoutput commands input disp and fprintfbull optional operate on cell arrays and structuresbull edit and run an m-file (both functions and scripts)bull identify the differences between scripts and functionsbull understand the concept of local and global variablesbull create a function with one or more input arguments and one or more output argumentsbull use comment statements to document scripts and functionsbull optional use the feval command - know how to pass a function name as an input argument to another function

DAY 4 SECTIONS 10 - 12 + EXERCISING ON WRITING FUNCTION M-FILES

At the end you should be able tobull understand better how to build function m-filesbull preallocate memory for vectors or matrices and know why and when this is beneficialbull replace basic loops with vectorized operationsbull use colon notation to perform vectorized operationsbull advanced use array indexing instead of loops to select elements from a matrixbull advanced use logical indexing and logical functions instead of loops to select elements from matricesbull perform low level input and output with fopen fscanf and fclosebull understand how to operate on text files (inputoutput operations)bull get more understanding on the use of fprintf while writing to a filebull optional understand how to operate on binary files (inputoutput operations)bull know and understand the importance of structural programming and debuggingbull know how to debug your programbull advanced write programs using the recommended programming style

Day 5

Polishing the knowledge and experiences gained with Matlab asking questions etc First steps in the directionof the final assignment

Day 6 - 7

The final assignment

PRELIMINARIES

Below you find a few basic definitions on computers and programming Please get acquainted with them since they introduce key concepts needed in the coming sections

bull A BIT (short for binary digit) is the smallest unit of information on a computer A single bit can hold only one of two values 0 or 1 More meaningful information is obtained by combining consecutive bits into larger units such as byte

bull A BYTE - a unit of 8 bits being capable of holding a single character Large amounts of memory are indicated in terms of kilobytes (1024 bytes) megabytes (1024 kilobytes) and gigabytes (1024 megabytes)

bull BINARY SYSTEM - a number system that has two unique digits 0 and 1 Computers are based on such a system because of its electrical nature (charged versus uncharged) Each digit position represents a different power of 2 The powers of 2 increase while moving from the right most to the left most position starting from 20 = 1 Here is an example of a binary number and its representation in the decimal system

10110 = 1 _ 24 + 0 _ 23 + 1 _ 22 + 1 _ 21 + 0 _ 20 = 16 + 0 + 4 + 2 + 0 = 24

bull DATA is information represented with symbols eg numbers words signals or images

bull A COMMAND is an instruction to do a specific task

bull An ALGORITHM is a sequence of instructions for the solution of a specific task in a finite number of steps

bull A PROGRAM is the implementation of an algorithm suitable for execution by a computer

bull A VARIABLE is a container that can hold a value For example in the expression x+y x and y are variables They can represent numeric values like 255 characters like rsquocrsquo or character strings like rsquoMatlabrsquoVariables make programs more flexible When a program is executed the variables are then replaced with real data That is why the same program can process different sets of data Every variable has a name (called the variable name) and a data type A variablersquos data type indicates the sort of value that the variable represents (see below)

bull A CONSTANT is a value that never changes That makes it the opposite of a variable It can be a numeric value a character or a string

bull A DATA TYPE is a classification of a particular type of information The most basic data types are- integer a whole number a number that has no fractional part eg 3- floating-point a number with a decimal point eg 35 or 12e-16 (this stands for 12 _ 10minus16)- character readable text character eg rsquoprsquo

bull A BUG is an error in a program causing the program to stop running not to run at all or to provide wrong results Some bugs can be very subtle and hard to find The process of finding and removing bugs is called debugging

bull A FILE is a collection of data or information that has a name stored in a computer There are many different types of files data files program files text files etc

bull An ASCII FILE is a standardized readable and editable plain text file

bull A BINARY FILE is a file stored in a format which is computer-readable but not human-readable Most numeric data and all executable programs are stored in binary files Matlab binary files are those with the extension rsquomatrsquo

1 How to work with Matlab

Matlab is a tool for mathematical (technical) calculations First it can be used as a scientific calculator it provides simple mathematical operations but handles complex numbers powers logarithms trigonometric operations as well Next it allows you to plot or visualize data in many different ways perform matrix algebra work with polynomials or integrate functions Like in a programmable calculator you can create execute and save a sequence of commands in order to make your computational process automatic It can be used to

store or retrieve data In the end Matlab can also be treated as a user-friendly programming language which gives the possibility to handle mathematical calculations in an easy wayRunning Matlab creates one or more windows on your screen The most important is the Matlab Command Window which is the place where you interact with Matlab The string gtgt is the Matlab prompt (except for the Student Edition that has the EDUgtgt prompt) When the Command window is active a cursor appears after the prompt indicating that Matlab is waiting for your command which can be eg 173 or cos(x)

11 Input via the command-line2-10 Matlab is an interactive system commands followed by Enter are executed immediately The results are ifdesired displayed on screen However execution of a command will not be possible or will go wrong when thecommand is not typed according to the rules Table 1 shows a list of commands used to solve the indicatedmathematical equation (a b x and y are numbers)There are also commands that perform a specific task such as help work with a file-system like cd or workwith matrices like rank Below you find basic information that is important when starting with Matlabbull Commands in Matlab are executed by pressing Enter or Return The output will be displayed onscreen immediately Try the followinggtgt 3 + 75gtgt 184gtgt 3 7Note that spaces are not important in Matlabbull The result of the last execution is called ans It can be used on the next command line Try for instancegtgt 144ans =35000gtgt ans^(-6)ans =54399e-0454399e-04 is a computer notation of 54399 _ 10minus4 (see Preliminaries) Note that ans is always overwrittenby the last commandbull ans is an example of a Matlab built-in variable It stores the result of the recently performed computationYou can also define your own variables Look how the information is stored in the variables aand bgtgt a = 144a =35000gtgt b = a^(-6)b =54399e-04Read Preliminaries to better understand the concept of variables You will learn more on Matlabvariables in section 23bull When the command is followed by a semicolon () the output is suppressed Check the differencebetween the following expressionsgtgt 3 + 75gtgt 3 + 75gtgt x = 34bull It is possible to execute more than one command at the same time the separate commands should thenbe divided by commas (to display the output) or by semicolons (to suppress the output display) eggtgt sin(pi4) cos(pi) sin(0)ans =07071ans =0Note that the value of cos(pi) is not printedbull The output may contain some empty lines this can be suppressed by the command format compactIn contrast the command format loose will insert extra empty lines4Mathematical notation Matlab-commanda + b a + ba minus b a - bab a b3xy 3 x ya

b a b or b a

ab a^bpx sqrt(x) or x^05_ pie exp(1)i i4 middot 103 4e3 or 410^33 minus 4i 3 - 4i or 3 - 4jsin x arctan x sin(x) atan(x) ex exp(x)ln x log(x)log x log10(x)|x| abs(x)Table 1 Translation of mathematical notation to Matlab commandsbull Matlab is case sensitive There is a difference between capital and normal letters for example a iswritten as a in Matlab A will result then in an errorbull All text after a percent sign until the end of a line is treated as a comment Enter eg the followinggtgt sin(314159) this is an approximation of sin(pi)You will notice that some examples in this text are followed by comments They are meant for you andyou should skip them while typing those examplesbull Previous commands can be fetched back with the -key The command can also be changed the and -keys may be used to move around in a line and edit itKeep in mind that Matlab executes the command immediately it might be useful to have an idea of theexpected outcome12 help-facilitiesMatlab provides assistance through extensive online help The help command is the simplest way to get349-359 help that is if you know the topic or command on which you want help For examplegtgt help elfungives information on the elementary math functions of Matlab The command help displays a list of allpossible topics The topic you want help on must be exact and spelled correctly The commando lookfor ismore useful if you do not know the exact name of the command or topic For examplegtgt lookfor inversedisplays all commands for which the word inverse is included in its help-text This command results in a list ofcommands with a short description Besides the help and lookfor commands there is also a separate mousedriven help The helpwin command opens a new window on screen which can be browsed in an interactiveway To learn more read pages 353-354 from rdquoThe Student Edition of Matlabrdquobook13 Interrupting a command or programSometimes you might spot an error in your command or program Due to this error it can happen that thecommand or program does not stop Pressing Ctrl-C forces Matlab to stop the process After this theMatlab-prompt (gtgt) re-appears This may take a while though514 PathIn Matlab commands or programs are contained in m-files which are just plain text files and have an37-39 extension rsquomrsquo The m-file must be located in one of the directories which Matlab automatically searchesThe list of these directories can be listed by the command path One of the directories that is always takeninto account is the current working directory which can be identified by the command pwd Use path addpathand rmpath functions to modify the path Here is an examplegtgt pathcmatlabcmatlabtoolboxmatlabgeneralcmatlabtoolboxmatlabopsgtgt addpath hpersonal assume that this is your directorygtgt pathhpersonalcmatlabcmatlabtoolboxmatlabgeneralcmatlabtoolboxmatlabopsIt is also possible to access the path browser from the File menu-bar instead15 Workspace issuesIf you work in the Command Window Matlab memorizes all commands that you entered (as you alreadyknow - to recall previous commands the -key is useful) and all variables that you created This can be6

2425verified with the commands who which gives a list of variables present in the workspace and whos whichincludes information on name number of allocated bytes and class of the variables For example assuming thatyou performed all commands given in the beginning after typing who you should get the following informationgtgt whoYour variables area ans b xThe command clear ltnamegt deletes the variable ltnamegt from the Matlab workspace clear or clear allremoves all variables This is useful when starting a new exercise For examplegtgt clear a xgtgt whoYour variables areans b16 Saving and loading dataThe easiest way to save or load Matlab variables is by using (clicking) the File menu-bar and then the Save26 Workspace as and Load Workspace items Also Matlab commands exist which allow you to saveand load data from filesThe command save allows for saving your workspace variables either into a binary file or an ASCII file (checkPreliminaries on binary and ASCII files) Binary files automatically get the rsquomatrsquo extension which is nottrue for ASCII files However it is recommended to add a rsquotxtrsquo or dat extensionExercise 1Learn how to use the save command by exercisinggtgt s1 = sin(pi4) s2 = sin(pi2)gtgt c1 = cos(pi4) c2 = cos(pi2)gtgt str = rsquohello worldrsquo this is a string example you will learn about strings latergtgt save saves all variables in binary format to the file matlabmatgtgt save data saves all variables in binary format to the file datamat6gtgt save numdata s1 c1 saves numeric variables s1 and c1 to the file numdatamatgtgt save strdata str saves a string variable str to the file strdatamatgtgtgtgt save allsin s saves all variables that match the pattern to allsinmatgtgt save allcosdat c -ascii saves c1c2 in 8-digit ascii format to allcosdat_The load command allows for loading variables into the workspace It uses the same syntax as saveExercise 2Assuming that you have done the previous exercise try to load variables from the created filesImportant before each load command clear the workspace and after loading check which variables arepresent in the workspace (using who)gtgt load loads all variables from the file matlabmatgtgt load data s1 c1 loads only specified variables from the file datamatgtgt load strdata loads all variables from the file strdatamatIt is also possible to read ASCII files that contain rows of space separated values Such a file may containcomments that begin with a percent character The resulting data is placed into a variable with the samename as the ASCII file (without the extension) Check for examplegtgt load allcosdat loads data from the file allcosdat into variable allcosgtgt who lists variables present in the workspace now_

2 Mathematics with numbers vectors and matricesThe basic element of Matlab is a matrix (or an array) Special cases arebull a 1 times 1-matrix a scalar or a single numberbull a matrix existing only of one row or one column a vector21 Single numbersYou have already got some experience with Matlab and you know that it can be used as a calculator To do4-614-1727that you can for example simply typegtgt 31256The result will beans =55714By default Matlab displays only 5 digits The command format long increases this number to 15 format

short reduces it to 5 again For examplegtgt format longgtgt 31256ans =557142857142857Exercise 3Define the format Matlab such that empty lines are suppressed and the output is given with 5 digitsCalculategtgt pigtgt sin(pi)Note that the answer is not exactly 0 _Use the command format to put Matlab in its standard-format ie short and loose7intermezzo

22 An introduction to floating-point numbersIn a computer numbers can be represented only in a discrete form It means that numbers are stored286 within a limited range and with a finite precision Integers can be represented exactly with the base of 2(read Preliminaries on bits and the binary system) The typical size of an integer is 16 bits so the largestpositive integer which can be stored is 216 = 65536 If negative integers are permitted then 16 bits allow forrepresenting integers between minus32768 and 32767 Within this range operations defined on the set of integerscan be performed exactlyHowever this is not valid for other real numbers In practice computers are integer machines and are capableof representing real numbers only by using complicated codes The most popular code is the floating pointstandard The term floating point is derived from the fact that there is no fixed number of digits before andafter the decimal point meaning that the decimal point can float Note that most floating-point numbers thata computer can represent are just approximations Therefore care should be taken that these approximationslead to reasonable results If a programmer is not careful small discrepancies in the approximations can causemeaningless results Note the difference between eg the integer arithmetic and floating-point arithmeticInteger arithmetic Floating-point arithmetic2 + 4 = 6 187 = 257143 4 = 12 25714 7 = 1799982511 = 2 100003 = 33333e+03When describing floating-point numbers precision refers to the number of bits used for the fractional partThe larger the precision the more exact fractional quantities can be represented Floating-point numbers areoften classified as single precision or double precision A double-precision number uses twice as many bits asa single-precision value so it can represent fractional values much better However the precision itself is notdouble The extra bits are also used to increase the range of magnitudes that can be representedMatlab relies on a computerrsquos floating point arithmetic You could have already noticed that in the last408-410 exercise since the value of sin(_) was almost zero and not completely zero It came from the fact that boththe value of _ is represented with a finite precision and the sin function is also approximatedThe fundamental type in Matlab is double which stands for a representation with a double precision It uses64 bits The single precision obtained by using the single type offers 32 bits Since most numeric operationsrequire high accuracy the double type is used by defaultThe exact machine precision might be defined as the smallest positive number _ that added to 1 does notchange the result so 1 + _ = 1 in floating-point arithmetic this value is larger than zero (in exact arithmeticof course _ = 0 holds) Matlab machine precision is stored in the built-in variable eps _ 22204e-16 Thismeans that the relative accuracy of individual arithmetic operations is about 16 digitsend intermezzo

23 Assignments and variablesWorking with complex numbers is easily done with MatlabExercise 4Choose two complex numbers for example -3 + 2i and 5 - 7i Try to add subtract multiply and dividethese two numbers _During this exercise the complex numbers had to be typed four times To reduce this assign each number to4-610-12a variable For the previous exercise this results ingtgt z = -3 + 2igtgt w = 5 - 7igtgt y1 = z + w y2 = z - w y3 = z w y4 = z w y5 = w zFormally there is no need to declare (ie define the name size and the type of) a new variable in Matlab Avariable is simply created by an assignment (the way it has been done above) Each newly created numerical

variable is always of the double type You can change this type by converting it into eg the single type 11a variable a is converted into a different type by performing eg a = single(a) a = int16(a) etc8In some cases when huge matrices should be handled and precision is not very important this might be a wayto proceed Also when only integers are taken into consideration it might be useful to convert the doublerepresentations into eg int16 or int321 integer types Since most computations should be performed with ahigh accuracy Matlab automatically chooses the double type It means that real numbers are approximatedwith the highest possible precision However it is important to emphasize that integer numbers are alwaysrepresented exactly no matter which numeric type is usedBear in mind that undefined values cannot be assigned to a variable So the following is not possiblegtgt clear x to make sure that x does not existgtgt fun = x^2 + 4 sin (x)It becomes possible bygtgt x = pi 3 fun = x^2 + 4 sin (x)Exercise 5Predict the result ofx = pi 3 x = x - 1 x = x + 5 x = abs(x) xCheck your prediction by performing these commands in Matlab _Exercise 6Here are some examples of different types of Matlab variables You do not need to understand them all nowsince you will learn more about them during the course Create them manually in Matlabgtgt this_is_my_very_simple_variable_today = 5 a number check what happens since thegtgt name is very long (gt 31 characters)gtgt 2t = 8 what is the problem with this commandgtgt this_is_a_matrix = [1 2 3 4 5 6] a matrixgtgt c = rsquoErsquo a charactergtgt str = rsquoHello worldrsquo a stringgtgt m = [rsquoJrsquorsquoorsquorsquohrsquorsquonrsquo] try to guess what it isCheck the types by using the command whos Use clear ltnamegt to remove a variable from the workspace _Exercise 7In addition to creating variables by assigning values to them a few other ways exist For instance there is anumber of built-in variables eg ans pi eps i inf or nan Find out what value is assigned to each of these74584 built-in variables _24 VectorsRow vectors are lists of numbers separated either by commas or by spaces They are examples of simple arrays41-49 The number of entries is known as the length of the vector (the command length exists as well) Their entitiesare referred to as elements or components The entries must be enclosed in [ ]gtgt v = [-1 sin(3) 7]v =-10000 01411 70000gtgt length(v)ans =3A number of operations can be done on vectors A vector can be multiplied by a scalar or addedsubtractedtofrom another vector with the same length or a number can be addedsubtracted tofrom a vector Allthese operations are carried out element-by-element Vectors can be also built from the already existing onesgtgt v = [-1 2 7] w = [2 3 4]gtgt z = v + w an element-by-element sumz =1 5 119gtgt v3 = v + 2 add 2 to all elements of vector v3v3 =1 4 9gtgt t = [2v -w]ans =-2 4 14 -2 -3 -4Also a particular value can be changed or displayedgtgt v(2) = -1 w(2) change the 2nd value of v display the 2nd value of wv =-1 -1 7ans =

3A colon notation is an important shortcut used when producing row vectors (see Table 3 and help colon)gtgt 25ans =2 3 4 5gtgt -23ans =-2 -1 0 1 2 3In general firststeplast produces a vector of entities with the value first incrementing by the stepuntil it reaches lastgtgt 020524ans =02000 07000 12000 17000 22000gtgt -3310ans =-3 0 3 6 9gtgt 15-05-05 negative step is also possibleans =15000 10000 05000 0 -05000Parts of vectors can be extracted by using a colon notationgtgt r = [-126 2 3 -2] -126 =gt -1 1 3 5r =-1 1 3 5 2 3 -2gtgt r(36) get elements of r which are on the positions from 3 to 6ans =3 5 2 3gtgt r(125) get elements of r which are on the positions from 1 to 5 taken with the step of 2ans =-1 3 2gtgt r(5-12) what will you get hereTo create column vectors you should separate entries by a semicolon () or by new linesgtgt f = [-1 3 5]f =-135The same operations as on row vectors can be done on column vectors However you cannot for exampleadd a column vector to a row vector To do that you need an operation called transposing which converts acolumn vector into a row vector and vice versa10gtgt f = [-1 3 5] a column vectorgtgt frsquo frsquo is a row vectorans =-1 3 5gtgt v = [-1 2 7] a row vectorgtgt f + v you cannot add a column vector f to a row vector v Error using ==gt +Matrix dimensions must agreegtgt frsquo + vans =-2 5 12gtgt f + vrsquoans =-2512If x is a complex vector than xrsquo gives the conjugate transpose of x eggtgt x = [1+2i -1+i]x =10000 + 20000i -10000 + 10000igtgt xrsquo this is the conjugate transposeans =10000 - 20000i-10000 - 10000i

gtgt xrsquo this is the rsquonormalrsquo transposeans =10000 + 20000i-10000 + 10000iExercise 8Exercise to become acquainted with operating on row and column vectors Enter all examples given in thissection and make new variations yourself Exercise with the colon notation approach as well _25 MatricesAn ntimesk matrix is a rectangular array of numbers having n rows and k columns Defining a matrix in Matlabis similar to defining a vector The generalization is straightforward if you know that a matrix consists of row49-6175-86vectors (or column vectors) Commas or spaces are used to separate elements in a row and semicolons areused to separate individual rows For example the matrix A =01 2 34 5 67 8 91Ais defined asgtgt A = [1 2 3 4 5 6 7 8 9] row by row inputA =1 2 34 5 67 8 9Another examples are for instancegtgt A2 = [14 -125]A2 =1 2 3 4-1 1 3 5gtgt A3 = [1 3-4 7]A3 =1 3-4 711Command ResultA(ij) Aij

A(j) j-th column of AA(i) i-th row of AA(klmn) (l minus k + 1) times (n minus m + 1) matrix with elements Aij with k _ i _ l m _ j _ nv(ij)rsquo rsquovector-partrsquo (vi vi+1 vj) of vector vTable 2 Manipulation of (groups of) matrix-elementsCommand Resultn = rank (A) n becomes the rank of matrix Ax = det (A) x becomes the determinant of matrix AC = size (A) C becomes a row-vector with 2 elements the number of rows and columns of Ax = trace (A) x becomes the trace (sum of diagonal elements) of matrix Ax = norm (v) x becomes the length of vector vC = A + B sum of two matricesC = A - B subtraction of two matricesC = A B multiplication of two matricesC = A B rdquoelement-by-elementrdquo multiplication (A and B are of equal size)C = A ^ k power of a matrix (k 2 Z can also be used for Aminus1)C = A ^ k rdquoelement-by-elementrdquo power of a matrixC = Arsquo the transposed of a matrix AT

C = A B rdquoelement-by-elementrdquo division (A and B are of equal size)U = A B finds the solution that minimizes the squared error in Ax minus BU = B A solution of XA = B analogous to the previous commandC = inv (A) C becomes the inverse of AC = null (A) C is an orthonormal basis for the null space of Aobtained from the singular value decompositionC = orth (A) C is an orthonormal basis for the range of AC = rref (A) C is the reduced row echelon form of AL = eig (A) L is a vector containing the -possibly complex- eigenvalues of a square matrix A[X D] = eig (A) produces a diagonal matrix D of eigenvalues and a full matrix X

whose columns are the corresponding eigenvectors of AS = svd (A) S is a vector containing the singular values of A[U S V] = svd (A) S is a diagonal matrix of the same dimension as Awith nonnegative diagonal elements in decreasing orderThe columns U and V are the accompanying singular vectorsx = linspace(a b n) generates a vector x of n equally spaced points between a and bx = logspace(a b n) generates a vector x starting at 10a and ended at 10b containing n valuesA = diag (v) gives a diagonal matrix with the elements v1 v2 vn on the diagonalA = eye (n) A is a n times n identity matrixA = zeros (n m) A is a n times m matrix with zeros (default m = n)A = rand (n m) A is a n times m matrix with elements uniformly distributed between 0 and 1A = randn (n m) ditto - with elements standard normal distributedv = max (A) v becomes a vector with the maximum value of the elements in each column of Aor v is the maximum of all elements if A is a vectorv = min (A) ditto - with minimumv = sum (A) ditto - with sumTable 3 Frequently used matrix operations and functions12Transposing a vector changes it from a row to a column or the other way around This idea can be extendedto a matrix where transposing interchanges rows with the corresponding columns as in the examplegtgt A2 A2rsquoA2 =1 2 3 4-1 1 3 5ans =1 -12 13 34 5gtgt size(A2) returns the size (dimensions) of a matrixans =2 4gtgt size(A2rsquo)ans =4 2There exists also some built-in matrices of size specified by the user (see Table 2) A few examples are givenbelowgtgt E = [] an empty matrix of 0-by-0 elementsE =[]gtgt I = eye(3) the identity matrixI =1 0 00 1 00 0 1gtgt B = rand(23) a matrix of random numbers you will get a different one00227 09101 0922200299 00640 03309gtgt O = ones(32)O =1 11 11 1gtgt r = [1 3 -2] R = diag(r) create a diagonal matrix with r on the diagonalR =1 0 00 3 00 0 -2gtgt v = linspace(124) a vector is also an example of a matrixv =10000 13333 16667 20000It is often needed to build a larger matrix from the smaller onesgtgt x = [4 -1] y = [-1 4]x =4

-1y =-1 4gtgt X = [x yrsquo] X consists of the columns x and yrsquoX =4 -1-1 4gtgt T = [ -1 3 4 4 5 6] t = 1313gtgt T2 = [T t] add to T a new row namely the row vector t getting T2T2 =-1 3 44 5 61 2 3gtgt G = [1 5 4 5 0 2] G is a matrix of the 3-by-2 size check size(G)gtgt T3 = [T2 G] T3 consists of T2 and new columns being the colums of GT3 = added at the end of T2-1 3 4 1 54 5 6 4 51 2 3 0 2gtgt [diag(56) ones(32)]ans =5 00 61 11 11 1A part can be extract from a matrix in a similar way as from a vector Each element in the matrix is indexedby a row and a column to which it belongs Mathematically the element from the i-th row and the j-thcolumn of the matrix A is denoted by Aij Matlab provides the A(ij) notationgtgt A = [13 46 79]A =1 2 34 5 67 8 9gtgt A(12) A(23) A(31)ans =2ans =6ans =7gtgt A(43) A is a 3-by-3 matrix Index exceeds matrix dimensionsgtgt A(23) = A(23) + 2A(11)A =1 2 34 5 87 8 9Having defined a matrix it is easy to extended it automatically For the matrix A it can be done eg asfollowsgtgt A(52) = 5 assign 5 to the position (52) the uninitializedA = elements become zeros1 2 34 5 87 8 90 0 00 5 0Different parts of the matrix A can be now extractedgtgt A(2) extract the 2nd column of Aans =25814

05gtgtgt A(34) extract the rows 3rd and 4th of Aans =7 8 90 0 0gtgt A(2312) extract a part of Aans =4 57 8If needed the other zero elements of the matrix A can be also defined by eggtgt A(4) = [1 2 3] assign vector [1 2 3] to the 4th row of Agtgt A(5[13]) = [4 5] a rsquoshortcutrsquo when assigning A(51) = 4 and A(53) = 5gtgt A how does the matrix A look like nowAs you have seen in the examples above it is possible to manipulate (groups of) matrix-elements Thecommands are shortly explained in Table 2Exercise 9Define the matrix A = [14 58 1 1 1 1] Predict and check the result ofgtgt B = A(3)gtgt C = A(1322)gtgt A(11) = 9gtgt A(2313) = [0 0 0 0 0 0]gtgt A(l212) = [l l 3 3]gtgt A = A(3314)_Exercise 10Define the matrices T=[ 3 4 1 8 -4 3] A = [diag(-123) T -4 4 1 2 1] Perform the followingoperations on the matrix Abull extract a vector consisting of the 2nd and 4th elements of the 3rd rowbull find the minimum of the 3rd columnbull find the maximum of the 2nd rowbull compute the sum of the 2nd columbull compute the mean of the 1st and 4th rowsbull extract the submatrix consisting of the 1st and 3rd rows and all columnsbull extract the submatrix consisting of the 1st and 2nd rows and the 3rd 4th and 5th columnsbull compute the total sum of the 1st and 2nd rowsbull add 3 to all elements of the 2nd and 3rd colums_Table 3 shows some frequently used matrix operations and functions A few examples are provided belowgtgt B = rand(23) a matrix of random numbers you will get a different oneB =09501 06068 0891302311 04860 07621gtgt B2 = [1 2 5 1 5 6]gtgt B + B2rsquo add two matrices why B2rsquo is needed instead of B2ans =19501 56068 5891322311 14860 67621gtgt S = ans4 divide all elements of the matrix ans by 4S =04875 14017 1472805578 03715 1690515gtgt C = [1 -1 4 7 0 -1]gtgt B C matrix multiplication is not defined for B and C Error using ==gt Inner matrix dimensions must agreegtgt B C but you can multiply element-by-elementans =09501 -06068 3565216180 0 -07621gtgt D = B Crsquo or you can make the multiplication legal Crsquo is now 3-by-2D =39085 5759627935 08559

gtgt D^3 this is equivalent to D D Dans =1992503 2041413990133 910548gtgt D^3 - 2 do for all elements raise to the power 3 and subtract 2ans =577069 1890638198005 -13731gtgtgtgt r = [1 3 -2]r B2 this is a legal operation r is a 1-by-3 matrix and B2 isans = 3-by-2 matrix B2 r is an illegal operation6 -7Remind that an n-by-k matrix A (having n rows and k columns) can be multiply by another matrix B onlyif B has k rows ie S is of the k-by-m size (m is arbitrary) As a result you get an n-by-m matrixA ˙B = C A 2 Rntimesk B 2 Rktimesm C 2 Rntimesm

RemarkYou can now compute the inner product between two vectors x and y xT y = Pi xi yi in a simple waygtgt f = [-1 3 5] a column vectorgtgt v = [-1 2 7] a column vectorgtgt frsquo v this is the inner productans =42gtgt f vrsquo be careful now a 3-by-1 matrix is multiplied by a 1-by-3gtgt matrix which results in a 3-by-3 matrix (the outer product)ans =1 -2 -7-3 6 21-5 10 35gtgt f v this is an element-by-element multiplication1635gtgt sum (f v) this is an another way to compute the inner productans =42Exercise 11Perform all operations from Table 3 using chosen matrices A and B vector v and scalars k a b n and m _Exercise 12Let A be a random 3 times 3 matrix and b a random 3 times 1 vector Given that Ax = b then x = Aminus1b Find x(there exist at least two possible commands to do this look at Table 3) _optionalThe concept of an empty matrix [] is also very useful in Matlab For instance a few columns or rows canbe removed from a matrix by assigning an empty matrix to it Try for example16Symbol Color Symbol Styley yellow dotted liner red o circlesg green - solid lineb blue - dashdotted lineTable 4 Plot colors and stylesgtgt C = [1 2 3 4 5 6 7 8 1 1 1 1]gtgt D = C D(2) = [] now a copy of C is in D remove the 2nd column of Dgtgt C ([13]) = [] remove the rows 1 and 3 from Cend optional

3 VisualizationMatlab can be used to visualize the results of an experiment Therefore you should define variables each ofthem containing all values of one parameter to plot31 Simple plotsWith the command plot a graphical display can be made plot(y) draws the points (1 y(1)) (2 y(2)) 184 (n y(n)) and connects the points with a straight line plot(xy) does the same for (x(1) y(1)) (x(2) y(2)) (x(n) y(n)) x and y have to be row- or column vectors of equal lengthThe commands loglog semilogx and semilogy are similar to plot except that they use logarithmic axesExercise 13Type the following commands after predicting the resultgtgt x = 0330

gtgt y = 2^[010] this is the same as y = [1 2 4 8 16 32 64 128 256 512 1024]gtgt plot(xy) to get a graphic representationgtgt semilogy(xy) to get logarithmic axesAs you can see the same figure is used for both plot commands The previous function is removed as soonas the next is displayed The command figure gives you an extra figure Repeat the previous commandsbut generate a new figure before plotting the second function so that you can see both functions in separatewindows You can also switch back to a figure using figure(n) where n is its number _Exercise 14Make a plot such that the coordinates (2 6) (25 18) (5 175) (42 125) and (212) are connected by aline _Exercise 15Plot the function y = sin(x) + x minus x cos(x) in two separate figures for the intervals 0 lt x lt 30 andminus100 lt x lt 100 _32 Several functions in one figureWhen more than one function is plotted in one figure it might be useful to use different markers and colors184-188197-201Table 4 shows a few possibilities help plot shows allThere are different ways to get more than one function into a figure The first one is with the command holdon After this command all functions will be plotted in the same figure until the command hold off is usedAn examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt plot (x1 y1 rsquordrsquo)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)17gtgt hold ongtgt plot (x2 y2 rsquoy-rsquo)gtgt plot (x1y1rsquok-rsquo)gtgt hold offA second method to display more than one function in one figure is to plot several functions at the same timeThe next commands will have the same results as the commands in the previous examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt plot (x1 y1rsquordrsquo x2 y2 rsquoy-rsquo x1 y1 rsquok-rsquo)It is also possible to get more than one figure in one figure window With the command subplot the windowcan be horizontally and vertically divided into any number of subfiguresgtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt subplot(131) plot (x1 y1rsquordrsquo)gtgt subplot(132) plot (x2 y2 rsquoy-rsquo)gtgt subplot(133) plot (x1 y1 rsquok-rsquo)optional

33 Other 2D plotting featuresIn the introduction of this chapter some commands similar to plot loglog semilogx and semilogy were201-211 mentioned There are however more ways to display dataExercise 16To get an impression of other visualizations type the following commands and describe the result (note thatthe command figure creates a new figure window)gtgt figure bar plot of a bell shaped curvegtgt x = -290229gtgt bar (x exp (-xx))gtgt figure stairstep plot of a sine wavegtgt x = 002510gtgt stairs (x sin (x))gtgt figure errorbar plotgtgt x = -2012gtgt y = erf (x) error function check help if you are interestedgtgt e = rand (size (x)) 10gtgt errorbar (x y e)

_end optional

34 PrintingBefore printing a figure you made you might want to add some information such as a title or change the189-196 lay-out a little Table 5 shows some of the commands that can be usedExercise 17Plot the functions y1 = sin(4x) y2 = x cos(x) y3 = (x + 1)minus1px for x = 0 025 10 and a single point(x y) = (4 5) in one figure with different colors and styles Make a legend containing the three functionsMake labels for both axes and a title Add a text to the single point saying single point Change the minimumand maximum values of the axes such that function y3 can be looked at in more detail _When the displayed figure is to your liking you can print it to paper The easiest way to do this is to click onFile in the menu-bar and to choose Print If in the print window you click OK your figure will be printed onthe printer indicated in the print window18Command Resultgrid onoff adds a grid to the plot at the tick marks or removes itaxis([xmin xmax ymin ymax]) sets the minimum and maximum values of the axesbox offon removes the axes box or shows itxlabel(rsquotextrsquo) plots the label text on the x axisylabel(rsquotextrsquo) plots the label text on the y axistitle(rsquotextrsquo) plots a title above the graphtext(xyrsquotextrsquo) adds text at the point (xy)gtext(rsquotextrsquo) adds text at a manually (with a mouse) indicated pointlegend(rsquofun1rsquorsquofun2rsquo) plots a legend box (move it with your mouse) to name your functionslegend off deletes the legend boxTable 5 Plot-manipulationsThere is also a print command which can be used to send a figure to a printer or output it to a file Youcan optionally specify a print device (ie an output format such as tiff or postscript) and options that controlvarious characteristics of the printed file (ie which Figure to print etc) You can also print to a file if youspecify the file name If you do not provide an extension print adds one Since they are many parametersthey will not be explained here (check help print to learn more) Instead try to understand the examplesgtgt print -dwinc print the current Figure to the current printer in colorgtgt print -f1 -deps myfileeps print Figure no1 to the file myfileeps in blackgtgt print -f1 -depsc myfileceps print Figure no1 to the file myfilecoleps in colorgtgt print -dtiff myfile1tiff print the current Figure to the file myfile1tiffgtgt print -dpsc myfile1cps print the current Figure to the file myfile1ps in colorgtgt print -f2 -djpeg myfile2 print Figure no2 to the file myfile2jpgExercise 18Exercise with printing (especially to a file) the figure from Exercise 16 _

4 Curve fitting and interpolationThere are two ways to describe data with an analytical function- curve fitting or regression finding a smooth curve that best fits (approximates) the data accordingto a criterion (eg best least square fit) The curve does not have to go through any of the data points- interpolation the data are assumed to be correct desired in a way to describe what happens betweenthe data points In other words given a finite set of points the goal of interpolation is to find a functionfrom a given class of functions (eg polynomials) which passes through the specified pointsThe figure below illustrates the difference between regression (curve fitting) and interpolationminus5 0 5minus6minus4minus20246810fiting a 3rd order polynomialinterpolation

41 Curve fittingMatlab interprets the best fit of a curve by the lsquoleast squares curve fittingrsquo The curve used is restricted153-15619to polynomials With the command polyfit any polynomial can be fitted to the data polyfit (x y n)finds the coefficients of a polynomial of degree n that fits the data (finds the linear relation between x and y)Letrsquos start with finding a linear regression of some datagtgt x = 010gtgt y = [-10 24 102 158 284 276 299 405 483 522 751]gtgt p = polyfit (x y 1) find the fitting polynomial of order 1p = 06772 -03914

The output of polyfit is a row vector of the polynomial coefficients the solution of this example is thereforey = 06772x minus 03914Exercise 19Execute the above example Plot the data and the fitted curve in a figure Determine the 2nd and 9th orderpolynomial of these data as well and display the solution in a figureHint x1 = linspace (xmin xmax n) results in a vector with n element evenly distributed from xmintill xmax z = polyval (p x1) calculates the values of the polynomial for every element of x1 _Exercise 20Define x and y as followsgtgt x = -55gtgt y = 02x^3 - x + 2 a 3rd order polynomialgtgt y = y + randn(111) add some noise to yDetermine the 3rd order polynomial fitting y (note that because of added noise the coefficients are differentthat originally chosen) Try some other polynomials as well Plot the results in a figure _42 InterpolationThe simplest way to examine an interpolation is by displaying the function plots with the command plot157-161 The neighboring data points are connected with straight lines This is called a linear interpolation Whenmore data-points are taken into account the effect of interpolation becomes less visible Analyzegtgt x1 = linspace(0 2pi2)gtgt x2 = linspace(0 2pi4)gtgt x3 = linspace(0 2pi16)gtgt x4 = linspace(0 2pi256)gtgt plot(x1sin(x1)x2sin(x2)x3sin(x3)x4sin(x4))gtgt legend(rsquo2 pointsrsquorsquo4 pointsrsquorsquo16 pointsrsquorsquo256 pointsrsquo)

5 Numerical analysisNumerical analysis can be used whenever it is impossible or very difficult to determine the analytical solutionMatlab can be used to find for example the minimum maximum or integral of a certain function51 Evaluation of a functionAs said before the command plot plots a function by connecting defined data points Sometimes however a168-173 function is constant and not very interesting over some range and then acts unexpectedly wildly over anotherWith plot this function might be misinterpreted The command fplot is then useful An examplegtgt x = 0pi82pigtgt y = sin (8x)gtgt plot (x y rsquobrsquo)gtgt hold ongtgt fplot (rsquosin (8z)rsquo [0 2pi] rsquorrsquo)gtgt title (rsquosin (8z)rsquo)gtgt hold off20Command Resultfplot (rsquofunrsquo [min x max x]) plots the function fun for min x till max xfmin (rsquofunrsquo min x max x) gives the x-value of the miminum of thefunction fun between min x and max xfzero (rsquofunrsquo x0) gives the x-value for which the functionfun is zero in the neighborhood of x0Table 6 Evaluation of a functionExecution of these commands results in a figure with an almost straight blue line and a red sine fplot canalso be used to plot a defined functiongtgt f = rsquosin (8z)rsquogtgt fplot (f [0 2pi] rsquorrsquo)gtgt title (f)Other useful commands for a detailed study of a range of a function are listed in Table 6Exercise 21The command fmax does not exist Use one or more of the commands from Table 6 to determine the maximumof the function x cos(x) for 10 lt x lt 15 _52 Integration and differentiationThe integral- or the surface underneath a 2D function- can be determined with the command trapz trapz173-182 does this by measuring the surface between the x-axis and the -by a straight line connected- data points Theaccuracy of this method depends on the distance between the data pointsgtgt x = 00510 y = 05 sqrt (x) + x sin (x) area1 = trapz (x y)

area1 =181655gtgt x = 000510 y = 05 sqrt (x) + x sin (x) area2 = trapz (x y)area2 =183846Differentiation is done by determining the slope in each data point Numerically this is done by first fitting apolynomial followed by differentiating this functiongtgt x = 010gtgt y = [-10 24 102 -158 284 276 775 35 483 522 751]gtgt p = polyfit (x y 5)p = 00026 -00554 03634 -06888 02747 00877gtgt dp = polyder (p)dp = 00132 -02216 10903 -13776 02747gtgt x1 = linspace (0 10 200)gtgt z = polyval (p x1)gtgt dz = polyval (dp x1)gtgt plot (x y rsquog-rsquo x1 z rsquobrsquo x1 dz rsquorrsquo)gtgt legend (rsquodata pointsrsquo rsquocurve fitrsquo rsquoderivativersquo)Exercise 22Determine the integral and derivative of the 4th polynomial fitted through (xy) with x = [4 5 6 7 8 9 1011 12 13] y = [1284 1200 724 -096 -1116 -2096 -2700 -2496 -956 2544] _

6 Control flowAs you know it is possible to execute more than one command at the same time (see section 11) Theseparate commands should then be divided by commarsquos (to display the output) or by semicolons (to suppress21output display) Control flow loops increase the number of possibilities A control flow structure is a block ofcommands that allows conditional code execution and making loops61 Logical and relational operatorsTo use control flow commands it is necessary to perform operations that result in logical values TRUE or88-91 FALSE In Matlab the result of a logical operation is 1 if it is true and 0 if it is false Table 7 shows therelational and logical operations2 Another way to get to know more about them is to type help relop Therelational operators lt lt= gt gt= == and ~= can be used to compare two arrays of the same size or anarray to a scalar The logical operators amp | and ~ allow for the logical combination or negation of relationaloperators In addition three functions are also available xor any and all (use help to find out more)Important The logical amp and | have the equal precedence in Matlab which means that those operatorsassociate from left to right A common situation isgtgt b = 10gtgt 1 | b gt 0 amp 0ans =0gtgt (1 | b gt 0) amp 0 this indicates the same as aboveans =0gtgt 1 | (b gt 0 amp 0)ans =1This shows that you should always use brackets to indicate in which way the operators should be evaluatedCommand Resulta = (b gt c) a is 1 if b is larger than c Similar are lt gt= and lt=a = (b == c) a is 1 if b is equal to ca = (b ~= c) a is 1 if b is not equal ca = ~b logical complement a is 1 if b is 0a = (b amp c) logical AND a is 1 if b = TRUE AND c = TRUEa = (b | c) logical OR a is 1 if b = TRUE OR c = TRUETable 7 Relational and logical operationsExercise 23Predict and check the result of each of the operations of Table 7 for b = 0 and c = -1 _Exercise 24Define two vectors with seven elements (randn(17)) and perform all logical operations including xor anyand all _Exercise 25While doing logical operations between a vector and a scalar each element of the vector is compared to thescalar Predict and check the result of each logical operator for the vector b = [2 31 -40 0] and the scalarc = 0 _Before moving on check whether you now understand the following relations

gtgt a = randperm(10) a random permutation of the numbers from 1 to 10gtgt b = 110gtgt b - (a lt= 7) subtracts from b a 0-1 vector taking 1 for a lt= 7 and 0 otherwisegtgt (a gt= 2) amp (a lt 4) returns ones at positions where 2 lt= a lt 4gtgt ~(b gt 4) returns ones at positions where b lt= 4gtgt (a == b) | b == 3 returns ones at positions where a is equal to b or b is equal to 3gtgt any (a gt 5) returns 1 when ANY of the a elements are larger than 5gtgt any (b lt 5 amp a gt 8) returns 1 when there in the evaluated expressiongtgt (b lt 5 amp a gt 8) appears at least one 1gtgt all (b gt 2) returns 1 when ALL b elements are larger than 22rdquoequal tordquo in the table on page 88 of rdquoThe Student Edition of Matlabrdquo must be rdquo==rdquo instead of rdquo=rdquo2262 Conditional code executionSelection control structures if-blocks are used to decide which instruction to execute next depending whether117-119 expression is TRUE or not The general description is given below In the examples below the command dispis frequently used This command displays on the screen the text between the quotesbull if endSyntaxif logical_expressionstatement1statement2endExampleif (a gt 0)b = adisp (rsquoa is positiversquo)endbull if else endSyntaxif logical_expressionblock of statementsevaluated if TRUEelseblock of statementsevaluated if FALSEendExampleif (temperature gt 100)disp (rsquoAbove boilingrsquo)toohigh = 1elsedisp (rsquoTemperature is OKrsquo)toohigh = 0endbull if elseif else endSyntaxif logical_expression1block of statements evaluatedif logical_expression1 is TRUEelseif logical_expression2block of statements evaluatedif logical_expression2 is TRUEelseblock of statements evaluatedif no other expression is TRUEendExampleif (height gt 190)disp (rsquovery tallrsquo)elseif (height gt 170)disp (rsquotallrsquo)elseif (height lt 150)disp (rsquosmallrsquo)

elsedisp (rsquoaveragersquo)endRemark To do the exercises below a script m-file will be useful It is an external file that contains asequence of Matlab commands What you need to do is to open an editor enter all commands needed forthe solution of a task save it with the extension rsquomrsquo (eg mytaskm) and then run it from the CommandWindow by typing mytask To open the Matlab editor go to the File menu-bar choose the Open optionand then m-file A new window will appear where you can write your scripts and save them on the disk Allcommands in the script will be executed in Matlab You will learn more on script m-files in section 91Important m-script file must be saved in one of the directories in Matlabrsquos pathAn example A script shortm can be created from the two lines given below and run by calling shortx = 0054plot (x sin(x) rsquo-rsquo)Exercise 26Create a script that asks for a number N and computes the drag coefficient C depending on the Reynoldrsquos23number N (make use of the if elseif construction) The command input might be useful here(read pages 32-33 from rdquoThe Student Edition of Matlabrdquoor use help)C =8gtgtgtltgtgtgt0 N _ 024N N 2 (0 01]24N (1 + 014N07) N 2 (01 1e3]043 N 2 (1e3 5e5]019 minus 8e4N N gt 5e5Check whether your script works correctly Compute the drag coefficient for eg N = -3e3 001 56 1e3 3e6(remember that eg 3e3 is a Matlab notation of 3 _ 103) _Exercise 27Write a script that asks for an integer and checks whether it can be divided by 2 or 3 Consider all possibilitiessuch as divisible by both 2 and 3 divisible by 2 and not by 3 etc (use the command rem) _Another selection structure is switch which switches between several cases depending on an expression which119-120 is either a scalar or a stringSyntaxswitch expressioncase choice1block of commands1case choice2a choice2bblock of commands2otherwiseblock of commandsendExamplemethod = 2switch methodcase 12disp(rsquoMethod is linearrsquo)case 3disp(rsquoMethod is cubicrsquo)case 4disp(rsquoMethod is nearestrsquo)otherwisedisp(rsquoUnknown methodrsquo)endThe statements following the first case where the expression matches the choice are executed Thisconstruction can be very handy to avoid long if elseif else end constructions Theexpression can be a scalar or a string A scalar expression matches a choice if expression == choice Astring expression matches a choice if strcmp(expression choice) returns 1 (is true) (strcmp is a commandcomparing two strings)Important Note that the switch-construction only allows the execution of one group of commandsExercise 28Assume that the months are represented by numbers from 1 to 12 Write a script that asks you to provide a

month and returns the number of days in that particular month Alternatively write a script that asks youto provide a month name (eg rsquoJunersquo) instead of a number Use the switch-construction _63 LoopsIteration control structures loops are used to repeat a block of statements until some condition is met Two114-117 types of loops existbull the for loop that repeats a group of statements a fixed number of timesSyntaxfor index = firststeplastblock of statementsendExamplesumx = 0for i=1length(x)sumx = sumx + x(i)end24You can specify any step including a negative value The index of the for-loop can be also a vectorSee some examples of possible variationsExample 1for i=12nendExample 2for i=n-13endExample 3for x=0054disp(x^2)endExample 4for x=[25 9 81]disp(sqrt(x))endbull while loop which evaluates a group of commands as long as expression is TRUESyntaxwhile expressionstatement1statement2statement3endExampleN = 100iter = 1msum = 0while iter lt= Nmsum = msum + iteriter = iter + 1endExercise 29Given the vectors x and y write a script computing the a matrix whose elements should be created accordingto a formula given below (make use of the length command to check the number of elements in both vectors)- aij = yixj (make sure that a division by zero will not occur)- bij = xi _ yj

- cij = 1 max (xi yj)_Exercise 30Determine the sum of the first 50 squared numbers with a control loop _Exercise 31Write a script to find the largest value n such that the sum p13 + p23 + + pn3 is less than 1000 _optionalExercise 32Write a script that transposes a matrix A Check its correctness with the Matlab operation Arsquo _Exercise 33

Write a script that asks for a temperature in degrees Celsius tc and computes the equivalent temperature indegrees Fahrenheit tf (use the formula tf = 95 _ tc + 32) The script should keep running until no numberis provided to convert The functions input and isempty (use help to learn more) should be useful here _end optional

64 Evaluation of logical and relational expressions in the control flow structuresThe relational and logical expressions may become more complicated It is not difficult to operate on them ifyou understand how they are evaluated To explain more details let us consider the following exampleif (~isempty(data)) amp (max(data) lt 5)endThis construction of the if-block is necessary to avoid comparison if data happens to be an empty matrix Insuch a case you cannot evaluate any expression and Matlab gives an error The amp operator returns 1 only ifboth expressions ~isempty (data) and max(data) lt 5 are true and 0 otherwise When data is an emptymatrix the next expression is not evaluated since the whole amp-expression is already known to be false Thesecond expression is checked only if data is a non-empty matrix Remember to put logical expression unitsbetween brackets to avoid wrong evaluations25Important The fact that computers make use of floating-point arithmetic means that often you should becareful when comparing two floating-point numbers just byif (x == y)end(Of course such a construction is allowed eg when you know that x and y represent integers) Instead of theabove construction you may try using thisif (abs (x - y) lt tolerance) eg tolerance = 1e-10endExercise 34Consider the following examplemax_iter = 50tolerance = 1e-4iter = 0xold = 01x = 1while (abs (x - xold) gt tolerance) amp (iter lt max_iter)xold = xx = cos(xold)iter = iter + 1endThis short program tries to solve the equation cos(x) = x (x is the solution found) Make the script solve cosfrom the presented code Note that the while-loop is repeated as long as both conditions are true If eitherthe condition (|x - xold| lt= tolerance) or (iter gt= max iter) is fulfilled then the loop is quitted Runthe script solve cos for different tolerance parameters eg 1e-3 1e-6 1e-8 1e-10 etc Use format long tocheck more precisely how much the found x is really different from cos(x) For each tolerance value checkthe number of performed iterations (iter value) _Exercise 35Create the script solve cos2 which is equal to the one given replacing the while-loop condition bywhile (abs (x - xold) gt tolerance) | (iter lt max_iter)Try to understand the difference and confirm your expectations by running solve cos2 What happens toiter _optional

65 Numerical analysis and the control flow structuresTake a look at the problem of a Taylor expansion The series will be determined numerically until the additionalterms are smaller than a defined precision Look at the Taylor expansion of 11minusx = 1 + x + x2 + withx = 042s = 0 x = 1 s = 0 x = 1x0 = 042 x0 = 042while (x gt 1e-6) or while (x gt (1e-6)s)s = s + x s = s + xx = x x0 x = x x0end endThe approximation of 11minusx is returned in s (first letter of sum) In the first case (on the left) the iteration

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 5: Introduction to Programming Using Matlab

PRELIMINARIES

Below you find a few basic definitions on computers and programming Please get acquainted with them since they introduce key concepts needed in the coming sections

bull A BIT (short for binary digit) is the smallest unit of information on a computer A single bit can hold only one of two values 0 or 1 More meaningful information is obtained by combining consecutive bits into larger units such as byte

bull A BYTE - a unit of 8 bits being capable of holding a single character Large amounts of memory are indicated in terms of kilobytes (1024 bytes) megabytes (1024 kilobytes) and gigabytes (1024 megabytes)

bull BINARY SYSTEM - a number system that has two unique digits 0 and 1 Computers are based on such a system because of its electrical nature (charged versus uncharged) Each digit position represents a different power of 2 The powers of 2 increase while moving from the right most to the left most position starting from 20 = 1 Here is an example of a binary number and its representation in the decimal system

10110 = 1 _ 24 + 0 _ 23 + 1 _ 22 + 1 _ 21 + 0 _ 20 = 16 + 0 + 4 + 2 + 0 = 24

bull DATA is information represented with symbols eg numbers words signals or images

bull A COMMAND is an instruction to do a specific task

bull An ALGORITHM is a sequence of instructions for the solution of a specific task in a finite number of steps

bull A PROGRAM is the implementation of an algorithm suitable for execution by a computer

bull A VARIABLE is a container that can hold a value For example in the expression x+y x and y are variables They can represent numeric values like 255 characters like rsquocrsquo or character strings like rsquoMatlabrsquoVariables make programs more flexible When a program is executed the variables are then replaced with real data That is why the same program can process different sets of data Every variable has a name (called the variable name) and a data type A variablersquos data type indicates the sort of value that the variable represents (see below)

bull A CONSTANT is a value that never changes That makes it the opposite of a variable It can be a numeric value a character or a string

bull A DATA TYPE is a classification of a particular type of information The most basic data types are- integer a whole number a number that has no fractional part eg 3- floating-point a number with a decimal point eg 35 or 12e-16 (this stands for 12 _ 10minus16)- character readable text character eg rsquoprsquo

bull A BUG is an error in a program causing the program to stop running not to run at all or to provide wrong results Some bugs can be very subtle and hard to find The process of finding and removing bugs is called debugging

bull A FILE is a collection of data or information that has a name stored in a computer There are many different types of files data files program files text files etc

bull An ASCII FILE is a standardized readable and editable plain text file

bull A BINARY FILE is a file stored in a format which is computer-readable but not human-readable Most numeric data and all executable programs are stored in binary files Matlab binary files are those with the extension rsquomatrsquo

1 How to work with Matlab

Matlab is a tool for mathematical (technical) calculations First it can be used as a scientific calculator it provides simple mathematical operations but handles complex numbers powers logarithms trigonometric operations as well Next it allows you to plot or visualize data in many different ways perform matrix algebra work with polynomials or integrate functions Like in a programmable calculator you can create execute and save a sequence of commands in order to make your computational process automatic It can be used to

store or retrieve data In the end Matlab can also be treated as a user-friendly programming language which gives the possibility to handle mathematical calculations in an easy wayRunning Matlab creates one or more windows on your screen The most important is the Matlab Command Window which is the place where you interact with Matlab The string gtgt is the Matlab prompt (except for the Student Edition that has the EDUgtgt prompt) When the Command window is active a cursor appears after the prompt indicating that Matlab is waiting for your command which can be eg 173 or cos(x)

11 Input via the command-line2-10 Matlab is an interactive system commands followed by Enter are executed immediately The results are ifdesired displayed on screen However execution of a command will not be possible or will go wrong when thecommand is not typed according to the rules Table 1 shows a list of commands used to solve the indicatedmathematical equation (a b x and y are numbers)There are also commands that perform a specific task such as help work with a file-system like cd or workwith matrices like rank Below you find basic information that is important when starting with Matlabbull Commands in Matlab are executed by pressing Enter or Return The output will be displayed onscreen immediately Try the followinggtgt 3 + 75gtgt 184gtgt 3 7Note that spaces are not important in Matlabbull The result of the last execution is called ans It can be used on the next command line Try for instancegtgt 144ans =35000gtgt ans^(-6)ans =54399e-0454399e-04 is a computer notation of 54399 _ 10minus4 (see Preliminaries) Note that ans is always overwrittenby the last commandbull ans is an example of a Matlab built-in variable It stores the result of the recently performed computationYou can also define your own variables Look how the information is stored in the variables aand bgtgt a = 144a =35000gtgt b = a^(-6)b =54399e-04Read Preliminaries to better understand the concept of variables You will learn more on Matlabvariables in section 23bull When the command is followed by a semicolon () the output is suppressed Check the differencebetween the following expressionsgtgt 3 + 75gtgt 3 + 75gtgt x = 34bull It is possible to execute more than one command at the same time the separate commands should thenbe divided by commas (to display the output) or by semicolons (to suppress the output display) eggtgt sin(pi4) cos(pi) sin(0)ans =07071ans =0Note that the value of cos(pi) is not printedbull The output may contain some empty lines this can be suppressed by the command format compactIn contrast the command format loose will insert extra empty lines4Mathematical notation Matlab-commanda + b a + ba minus b a - bab a b3xy 3 x ya

b a b or b a

ab a^bpx sqrt(x) or x^05_ pie exp(1)i i4 middot 103 4e3 or 410^33 minus 4i 3 - 4i or 3 - 4jsin x arctan x sin(x) atan(x) ex exp(x)ln x log(x)log x log10(x)|x| abs(x)Table 1 Translation of mathematical notation to Matlab commandsbull Matlab is case sensitive There is a difference between capital and normal letters for example a iswritten as a in Matlab A will result then in an errorbull All text after a percent sign until the end of a line is treated as a comment Enter eg the followinggtgt sin(314159) this is an approximation of sin(pi)You will notice that some examples in this text are followed by comments They are meant for you andyou should skip them while typing those examplesbull Previous commands can be fetched back with the -key The command can also be changed the and -keys may be used to move around in a line and edit itKeep in mind that Matlab executes the command immediately it might be useful to have an idea of theexpected outcome12 help-facilitiesMatlab provides assistance through extensive online help The help command is the simplest way to get349-359 help that is if you know the topic or command on which you want help For examplegtgt help elfungives information on the elementary math functions of Matlab The command help displays a list of allpossible topics The topic you want help on must be exact and spelled correctly The commando lookfor ismore useful if you do not know the exact name of the command or topic For examplegtgt lookfor inversedisplays all commands for which the word inverse is included in its help-text This command results in a list ofcommands with a short description Besides the help and lookfor commands there is also a separate mousedriven help The helpwin command opens a new window on screen which can be browsed in an interactiveway To learn more read pages 353-354 from rdquoThe Student Edition of Matlabrdquobook13 Interrupting a command or programSometimes you might spot an error in your command or program Due to this error it can happen that thecommand or program does not stop Pressing Ctrl-C forces Matlab to stop the process After this theMatlab-prompt (gtgt) re-appears This may take a while though514 PathIn Matlab commands or programs are contained in m-files which are just plain text files and have an37-39 extension rsquomrsquo The m-file must be located in one of the directories which Matlab automatically searchesThe list of these directories can be listed by the command path One of the directories that is always takeninto account is the current working directory which can be identified by the command pwd Use path addpathand rmpath functions to modify the path Here is an examplegtgt pathcmatlabcmatlabtoolboxmatlabgeneralcmatlabtoolboxmatlabopsgtgt addpath hpersonal assume that this is your directorygtgt pathhpersonalcmatlabcmatlabtoolboxmatlabgeneralcmatlabtoolboxmatlabopsIt is also possible to access the path browser from the File menu-bar instead15 Workspace issuesIf you work in the Command Window Matlab memorizes all commands that you entered (as you alreadyknow - to recall previous commands the -key is useful) and all variables that you created This can be6

2425verified with the commands who which gives a list of variables present in the workspace and whos whichincludes information on name number of allocated bytes and class of the variables For example assuming thatyou performed all commands given in the beginning after typing who you should get the following informationgtgt whoYour variables area ans b xThe command clear ltnamegt deletes the variable ltnamegt from the Matlab workspace clear or clear allremoves all variables This is useful when starting a new exercise For examplegtgt clear a xgtgt whoYour variables areans b16 Saving and loading dataThe easiest way to save or load Matlab variables is by using (clicking) the File menu-bar and then the Save26 Workspace as and Load Workspace items Also Matlab commands exist which allow you to saveand load data from filesThe command save allows for saving your workspace variables either into a binary file or an ASCII file (checkPreliminaries on binary and ASCII files) Binary files automatically get the rsquomatrsquo extension which is nottrue for ASCII files However it is recommended to add a rsquotxtrsquo or dat extensionExercise 1Learn how to use the save command by exercisinggtgt s1 = sin(pi4) s2 = sin(pi2)gtgt c1 = cos(pi4) c2 = cos(pi2)gtgt str = rsquohello worldrsquo this is a string example you will learn about strings latergtgt save saves all variables in binary format to the file matlabmatgtgt save data saves all variables in binary format to the file datamat6gtgt save numdata s1 c1 saves numeric variables s1 and c1 to the file numdatamatgtgt save strdata str saves a string variable str to the file strdatamatgtgtgtgt save allsin s saves all variables that match the pattern to allsinmatgtgt save allcosdat c -ascii saves c1c2 in 8-digit ascii format to allcosdat_The load command allows for loading variables into the workspace It uses the same syntax as saveExercise 2Assuming that you have done the previous exercise try to load variables from the created filesImportant before each load command clear the workspace and after loading check which variables arepresent in the workspace (using who)gtgt load loads all variables from the file matlabmatgtgt load data s1 c1 loads only specified variables from the file datamatgtgt load strdata loads all variables from the file strdatamatIt is also possible to read ASCII files that contain rows of space separated values Such a file may containcomments that begin with a percent character The resulting data is placed into a variable with the samename as the ASCII file (without the extension) Check for examplegtgt load allcosdat loads data from the file allcosdat into variable allcosgtgt who lists variables present in the workspace now_

2 Mathematics with numbers vectors and matricesThe basic element of Matlab is a matrix (or an array) Special cases arebull a 1 times 1-matrix a scalar or a single numberbull a matrix existing only of one row or one column a vector21 Single numbersYou have already got some experience with Matlab and you know that it can be used as a calculator To do4-614-1727that you can for example simply typegtgt 31256The result will beans =55714By default Matlab displays only 5 digits The command format long increases this number to 15 format

short reduces it to 5 again For examplegtgt format longgtgt 31256ans =557142857142857Exercise 3Define the format Matlab such that empty lines are suppressed and the output is given with 5 digitsCalculategtgt pigtgt sin(pi)Note that the answer is not exactly 0 _Use the command format to put Matlab in its standard-format ie short and loose7intermezzo

22 An introduction to floating-point numbersIn a computer numbers can be represented only in a discrete form It means that numbers are stored286 within a limited range and with a finite precision Integers can be represented exactly with the base of 2(read Preliminaries on bits and the binary system) The typical size of an integer is 16 bits so the largestpositive integer which can be stored is 216 = 65536 If negative integers are permitted then 16 bits allow forrepresenting integers between minus32768 and 32767 Within this range operations defined on the set of integerscan be performed exactlyHowever this is not valid for other real numbers In practice computers are integer machines and are capableof representing real numbers only by using complicated codes The most popular code is the floating pointstandard The term floating point is derived from the fact that there is no fixed number of digits before andafter the decimal point meaning that the decimal point can float Note that most floating-point numbers thata computer can represent are just approximations Therefore care should be taken that these approximationslead to reasonable results If a programmer is not careful small discrepancies in the approximations can causemeaningless results Note the difference between eg the integer arithmetic and floating-point arithmeticInteger arithmetic Floating-point arithmetic2 + 4 = 6 187 = 257143 4 = 12 25714 7 = 1799982511 = 2 100003 = 33333e+03When describing floating-point numbers precision refers to the number of bits used for the fractional partThe larger the precision the more exact fractional quantities can be represented Floating-point numbers areoften classified as single precision or double precision A double-precision number uses twice as many bits asa single-precision value so it can represent fractional values much better However the precision itself is notdouble The extra bits are also used to increase the range of magnitudes that can be representedMatlab relies on a computerrsquos floating point arithmetic You could have already noticed that in the last408-410 exercise since the value of sin(_) was almost zero and not completely zero It came from the fact that boththe value of _ is represented with a finite precision and the sin function is also approximatedThe fundamental type in Matlab is double which stands for a representation with a double precision It uses64 bits The single precision obtained by using the single type offers 32 bits Since most numeric operationsrequire high accuracy the double type is used by defaultThe exact machine precision might be defined as the smallest positive number _ that added to 1 does notchange the result so 1 + _ = 1 in floating-point arithmetic this value is larger than zero (in exact arithmeticof course _ = 0 holds) Matlab machine precision is stored in the built-in variable eps _ 22204e-16 Thismeans that the relative accuracy of individual arithmetic operations is about 16 digitsend intermezzo

23 Assignments and variablesWorking with complex numbers is easily done with MatlabExercise 4Choose two complex numbers for example -3 + 2i and 5 - 7i Try to add subtract multiply and dividethese two numbers _During this exercise the complex numbers had to be typed four times To reduce this assign each number to4-610-12a variable For the previous exercise this results ingtgt z = -3 + 2igtgt w = 5 - 7igtgt y1 = z + w y2 = z - w y3 = z w y4 = z w y5 = w zFormally there is no need to declare (ie define the name size and the type of) a new variable in Matlab Avariable is simply created by an assignment (the way it has been done above) Each newly created numerical

variable is always of the double type You can change this type by converting it into eg the single type 11a variable a is converted into a different type by performing eg a = single(a) a = int16(a) etc8In some cases when huge matrices should be handled and precision is not very important this might be a wayto proceed Also when only integers are taken into consideration it might be useful to convert the doublerepresentations into eg int16 or int321 integer types Since most computations should be performed with ahigh accuracy Matlab automatically chooses the double type It means that real numbers are approximatedwith the highest possible precision However it is important to emphasize that integer numbers are alwaysrepresented exactly no matter which numeric type is usedBear in mind that undefined values cannot be assigned to a variable So the following is not possiblegtgt clear x to make sure that x does not existgtgt fun = x^2 + 4 sin (x)It becomes possible bygtgt x = pi 3 fun = x^2 + 4 sin (x)Exercise 5Predict the result ofx = pi 3 x = x - 1 x = x + 5 x = abs(x) xCheck your prediction by performing these commands in Matlab _Exercise 6Here are some examples of different types of Matlab variables You do not need to understand them all nowsince you will learn more about them during the course Create them manually in Matlabgtgt this_is_my_very_simple_variable_today = 5 a number check what happens since thegtgt name is very long (gt 31 characters)gtgt 2t = 8 what is the problem with this commandgtgt this_is_a_matrix = [1 2 3 4 5 6] a matrixgtgt c = rsquoErsquo a charactergtgt str = rsquoHello worldrsquo a stringgtgt m = [rsquoJrsquorsquoorsquorsquohrsquorsquonrsquo] try to guess what it isCheck the types by using the command whos Use clear ltnamegt to remove a variable from the workspace _Exercise 7In addition to creating variables by assigning values to them a few other ways exist For instance there is anumber of built-in variables eg ans pi eps i inf or nan Find out what value is assigned to each of these74584 built-in variables _24 VectorsRow vectors are lists of numbers separated either by commas or by spaces They are examples of simple arrays41-49 The number of entries is known as the length of the vector (the command length exists as well) Their entitiesare referred to as elements or components The entries must be enclosed in [ ]gtgt v = [-1 sin(3) 7]v =-10000 01411 70000gtgt length(v)ans =3A number of operations can be done on vectors A vector can be multiplied by a scalar or addedsubtractedtofrom another vector with the same length or a number can be addedsubtracted tofrom a vector Allthese operations are carried out element-by-element Vectors can be also built from the already existing onesgtgt v = [-1 2 7] w = [2 3 4]gtgt z = v + w an element-by-element sumz =1 5 119gtgt v3 = v + 2 add 2 to all elements of vector v3v3 =1 4 9gtgt t = [2v -w]ans =-2 4 14 -2 -3 -4Also a particular value can be changed or displayedgtgt v(2) = -1 w(2) change the 2nd value of v display the 2nd value of wv =-1 -1 7ans =

3A colon notation is an important shortcut used when producing row vectors (see Table 3 and help colon)gtgt 25ans =2 3 4 5gtgt -23ans =-2 -1 0 1 2 3In general firststeplast produces a vector of entities with the value first incrementing by the stepuntil it reaches lastgtgt 020524ans =02000 07000 12000 17000 22000gtgt -3310ans =-3 0 3 6 9gtgt 15-05-05 negative step is also possibleans =15000 10000 05000 0 -05000Parts of vectors can be extracted by using a colon notationgtgt r = [-126 2 3 -2] -126 =gt -1 1 3 5r =-1 1 3 5 2 3 -2gtgt r(36) get elements of r which are on the positions from 3 to 6ans =3 5 2 3gtgt r(125) get elements of r which are on the positions from 1 to 5 taken with the step of 2ans =-1 3 2gtgt r(5-12) what will you get hereTo create column vectors you should separate entries by a semicolon () or by new linesgtgt f = [-1 3 5]f =-135The same operations as on row vectors can be done on column vectors However you cannot for exampleadd a column vector to a row vector To do that you need an operation called transposing which converts acolumn vector into a row vector and vice versa10gtgt f = [-1 3 5] a column vectorgtgt frsquo frsquo is a row vectorans =-1 3 5gtgt v = [-1 2 7] a row vectorgtgt f + v you cannot add a column vector f to a row vector v Error using ==gt +Matrix dimensions must agreegtgt frsquo + vans =-2 5 12gtgt f + vrsquoans =-2512If x is a complex vector than xrsquo gives the conjugate transpose of x eggtgt x = [1+2i -1+i]x =10000 + 20000i -10000 + 10000igtgt xrsquo this is the conjugate transposeans =10000 - 20000i-10000 - 10000i

gtgt xrsquo this is the rsquonormalrsquo transposeans =10000 + 20000i-10000 + 10000iExercise 8Exercise to become acquainted with operating on row and column vectors Enter all examples given in thissection and make new variations yourself Exercise with the colon notation approach as well _25 MatricesAn ntimesk matrix is a rectangular array of numbers having n rows and k columns Defining a matrix in Matlabis similar to defining a vector The generalization is straightforward if you know that a matrix consists of row49-6175-86vectors (or column vectors) Commas or spaces are used to separate elements in a row and semicolons areused to separate individual rows For example the matrix A =01 2 34 5 67 8 91Ais defined asgtgt A = [1 2 3 4 5 6 7 8 9] row by row inputA =1 2 34 5 67 8 9Another examples are for instancegtgt A2 = [14 -125]A2 =1 2 3 4-1 1 3 5gtgt A3 = [1 3-4 7]A3 =1 3-4 711Command ResultA(ij) Aij

A(j) j-th column of AA(i) i-th row of AA(klmn) (l minus k + 1) times (n minus m + 1) matrix with elements Aij with k _ i _ l m _ j _ nv(ij)rsquo rsquovector-partrsquo (vi vi+1 vj) of vector vTable 2 Manipulation of (groups of) matrix-elementsCommand Resultn = rank (A) n becomes the rank of matrix Ax = det (A) x becomes the determinant of matrix AC = size (A) C becomes a row-vector with 2 elements the number of rows and columns of Ax = trace (A) x becomes the trace (sum of diagonal elements) of matrix Ax = norm (v) x becomes the length of vector vC = A + B sum of two matricesC = A - B subtraction of two matricesC = A B multiplication of two matricesC = A B rdquoelement-by-elementrdquo multiplication (A and B are of equal size)C = A ^ k power of a matrix (k 2 Z can also be used for Aminus1)C = A ^ k rdquoelement-by-elementrdquo power of a matrixC = Arsquo the transposed of a matrix AT

C = A B rdquoelement-by-elementrdquo division (A and B are of equal size)U = A B finds the solution that minimizes the squared error in Ax minus BU = B A solution of XA = B analogous to the previous commandC = inv (A) C becomes the inverse of AC = null (A) C is an orthonormal basis for the null space of Aobtained from the singular value decompositionC = orth (A) C is an orthonormal basis for the range of AC = rref (A) C is the reduced row echelon form of AL = eig (A) L is a vector containing the -possibly complex- eigenvalues of a square matrix A[X D] = eig (A) produces a diagonal matrix D of eigenvalues and a full matrix X

whose columns are the corresponding eigenvectors of AS = svd (A) S is a vector containing the singular values of A[U S V] = svd (A) S is a diagonal matrix of the same dimension as Awith nonnegative diagonal elements in decreasing orderThe columns U and V are the accompanying singular vectorsx = linspace(a b n) generates a vector x of n equally spaced points between a and bx = logspace(a b n) generates a vector x starting at 10a and ended at 10b containing n valuesA = diag (v) gives a diagonal matrix with the elements v1 v2 vn on the diagonalA = eye (n) A is a n times n identity matrixA = zeros (n m) A is a n times m matrix with zeros (default m = n)A = rand (n m) A is a n times m matrix with elements uniformly distributed between 0 and 1A = randn (n m) ditto - with elements standard normal distributedv = max (A) v becomes a vector with the maximum value of the elements in each column of Aor v is the maximum of all elements if A is a vectorv = min (A) ditto - with minimumv = sum (A) ditto - with sumTable 3 Frequently used matrix operations and functions12Transposing a vector changes it from a row to a column or the other way around This idea can be extendedto a matrix where transposing interchanges rows with the corresponding columns as in the examplegtgt A2 A2rsquoA2 =1 2 3 4-1 1 3 5ans =1 -12 13 34 5gtgt size(A2) returns the size (dimensions) of a matrixans =2 4gtgt size(A2rsquo)ans =4 2There exists also some built-in matrices of size specified by the user (see Table 2) A few examples are givenbelowgtgt E = [] an empty matrix of 0-by-0 elementsE =[]gtgt I = eye(3) the identity matrixI =1 0 00 1 00 0 1gtgt B = rand(23) a matrix of random numbers you will get a different one00227 09101 0922200299 00640 03309gtgt O = ones(32)O =1 11 11 1gtgt r = [1 3 -2] R = diag(r) create a diagonal matrix with r on the diagonalR =1 0 00 3 00 0 -2gtgt v = linspace(124) a vector is also an example of a matrixv =10000 13333 16667 20000It is often needed to build a larger matrix from the smaller onesgtgt x = [4 -1] y = [-1 4]x =4

-1y =-1 4gtgt X = [x yrsquo] X consists of the columns x and yrsquoX =4 -1-1 4gtgt T = [ -1 3 4 4 5 6] t = 1313gtgt T2 = [T t] add to T a new row namely the row vector t getting T2T2 =-1 3 44 5 61 2 3gtgt G = [1 5 4 5 0 2] G is a matrix of the 3-by-2 size check size(G)gtgt T3 = [T2 G] T3 consists of T2 and new columns being the colums of GT3 = added at the end of T2-1 3 4 1 54 5 6 4 51 2 3 0 2gtgt [diag(56) ones(32)]ans =5 00 61 11 11 1A part can be extract from a matrix in a similar way as from a vector Each element in the matrix is indexedby a row and a column to which it belongs Mathematically the element from the i-th row and the j-thcolumn of the matrix A is denoted by Aij Matlab provides the A(ij) notationgtgt A = [13 46 79]A =1 2 34 5 67 8 9gtgt A(12) A(23) A(31)ans =2ans =6ans =7gtgt A(43) A is a 3-by-3 matrix Index exceeds matrix dimensionsgtgt A(23) = A(23) + 2A(11)A =1 2 34 5 87 8 9Having defined a matrix it is easy to extended it automatically For the matrix A it can be done eg asfollowsgtgt A(52) = 5 assign 5 to the position (52) the uninitializedA = elements become zeros1 2 34 5 87 8 90 0 00 5 0Different parts of the matrix A can be now extractedgtgt A(2) extract the 2nd column of Aans =25814

05gtgtgt A(34) extract the rows 3rd and 4th of Aans =7 8 90 0 0gtgt A(2312) extract a part of Aans =4 57 8If needed the other zero elements of the matrix A can be also defined by eggtgt A(4) = [1 2 3] assign vector [1 2 3] to the 4th row of Agtgt A(5[13]) = [4 5] a rsquoshortcutrsquo when assigning A(51) = 4 and A(53) = 5gtgt A how does the matrix A look like nowAs you have seen in the examples above it is possible to manipulate (groups of) matrix-elements Thecommands are shortly explained in Table 2Exercise 9Define the matrix A = [14 58 1 1 1 1] Predict and check the result ofgtgt B = A(3)gtgt C = A(1322)gtgt A(11) = 9gtgt A(2313) = [0 0 0 0 0 0]gtgt A(l212) = [l l 3 3]gtgt A = A(3314)_Exercise 10Define the matrices T=[ 3 4 1 8 -4 3] A = [diag(-123) T -4 4 1 2 1] Perform the followingoperations on the matrix Abull extract a vector consisting of the 2nd and 4th elements of the 3rd rowbull find the minimum of the 3rd columnbull find the maximum of the 2nd rowbull compute the sum of the 2nd columbull compute the mean of the 1st and 4th rowsbull extract the submatrix consisting of the 1st and 3rd rows and all columnsbull extract the submatrix consisting of the 1st and 2nd rows and the 3rd 4th and 5th columnsbull compute the total sum of the 1st and 2nd rowsbull add 3 to all elements of the 2nd and 3rd colums_Table 3 shows some frequently used matrix operations and functions A few examples are provided belowgtgt B = rand(23) a matrix of random numbers you will get a different oneB =09501 06068 0891302311 04860 07621gtgt B2 = [1 2 5 1 5 6]gtgt B + B2rsquo add two matrices why B2rsquo is needed instead of B2ans =19501 56068 5891322311 14860 67621gtgt S = ans4 divide all elements of the matrix ans by 4S =04875 14017 1472805578 03715 1690515gtgt C = [1 -1 4 7 0 -1]gtgt B C matrix multiplication is not defined for B and C Error using ==gt Inner matrix dimensions must agreegtgt B C but you can multiply element-by-elementans =09501 -06068 3565216180 0 -07621gtgt D = B Crsquo or you can make the multiplication legal Crsquo is now 3-by-2D =39085 5759627935 08559

gtgt D^3 this is equivalent to D D Dans =1992503 2041413990133 910548gtgt D^3 - 2 do for all elements raise to the power 3 and subtract 2ans =577069 1890638198005 -13731gtgtgtgt r = [1 3 -2]r B2 this is a legal operation r is a 1-by-3 matrix and B2 isans = 3-by-2 matrix B2 r is an illegal operation6 -7Remind that an n-by-k matrix A (having n rows and k columns) can be multiply by another matrix B onlyif B has k rows ie S is of the k-by-m size (m is arbitrary) As a result you get an n-by-m matrixA ˙B = C A 2 Rntimesk B 2 Rktimesm C 2 Rntimesm

RemarkYou can now compute the inner product between two vectors x and y xT y = Pi xi yi in a simple waygtgt f = [-1 3 5] a column vectorgtgt v = [-1 2 7] a column vectorgtgt frsquo v this is the inner productans =42gtgt f vrsquo be careful now a 3-by-1 matrix is multiplied by a 1-by-3gtgt matrix which results in a 3-by-3 matrix (the outer product)ans =1 -2 -7-3 6 21-5 10 35gtgt f v this is an element-by-element multiplication1635gtgt sum (f v) this is an another way to compute the inner productans =42Exercise 11Perform all operations from Table 3 using chosen matrices A and B vector v and scalars k a b n and m _Exercise 12Let A be a random 3 times 3 matrix and b a random 3 times 1 vector Given that Ax = b then x = Aminus1b Find x(there exist at least two possible commands to do this look at Table 3) _optionalThe concept of an empty matrix [] is also very useful in Matlab For instance a few columns or rows canbe removed from a matrix by assigning an empty matrix to it Try for example16Symbol Color Symbol Styley yellow dotted liner red o circlesg green - solid lineb blue - dashdotted lineTable 4 Plot colors and stylesgtgt C = [1 2 3 4 5 6 7 8 1 1 1 1]gtgt D = C D(2) = [] now a copy of C is in D remove the 2nd column of Dgtgt C ([13]) = [] remove the rows 1 and 3 from Cend optional

3 VisualizationMatlab can be used to visualize the results of an experiment Therefore you should define variables each ofthem containing all values of one parameter to plot31 Simple plotsWith the command plot a graphical display can be made plot(y) draws the points (1 y(1)) (2 y(2)) 184 (n y(n)) and connects the points with a straight line plot(xy) does the same for (x(1) y(1)) (x(2) y(2)) (x(n) y(n)) x and y have to be row- or column vectors of equal lengthThe commands loglog semilogx and semilogy are similar to plot except that they use logarithmic axesExercise 13Type the following commands after predicting the resultgtgt x = 0330

gtgt y = 2^[010] this is the same as y = [1 2 4 8 16 32 64 128 256 512 1024]gtgt plot(xy) to get a graphic representationgtgt semilogy(xy) to get logarithmic axesAs you can see the same figure is used for both plot commands The previous function is removed as soonas the next is displayed The command figure gives you an extra figure Repeat the previous commandsbut generate a new figure before plotting the second function so that you can see both functions in separatewindows You can also switch back to a figure using figure(n) where n is its number _Exercise 14Make a plot such that the coordinates (2 6) (25 18) (5 175) (42 125) and (212) are connected by aline _Exercise 15Plot the function y = sin(x) + x minus x cos(x) in two separate figures for the intervals 0 lt x lt 30 andminus100 lt x lt 100 _32 Several functions in one figureWhen more than one function is plotted in one figure it might be useful to use different markers and colors184-188197-201Table 4 shows a few possibilities help plot shows allThere are different ways to get more than one function into a figure The first one is with the command holdon After this command all functions will be plotted in the same figure until the command hold off is usedAn examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt plot (x1 y1 rsquordrsquo)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)17gtgt hold ongtgt plot (x2 y2 rsquoy-rsquo)gtgt plot (x1y1rsquok-rsquo)gtgt hold offA second method to display more than one function in one figure is to plot several functions at the same timeThe next commands will have the same results as the commands in the previous examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt plot (x1 y1rsquordrsquo x2 y2 rsquoy-rsquo x1 y1 rsquok-rsquo)It is also possible to get more than one figure in one figure window With the command subplot the windowcan be horizontally and vertically divided into any number of subfiguresgtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt subplot(131) plot (x1 y1rsquordrsquo)gtgt subplot(132) plot (x2 y2 rsquoy-rsquo)gtgt subplot(133) plot (x1 y1 rsquok-rsquo)optional

33 Other 2D plotting featuresIn the introduction of this chapter some commands similar to plot loglog semilogx and semilogy were201-211 mentioned There are however more ways to display dataExercise 16To get an impression of other visualizations type the following commands and describe the result (note thatthe command figure creates a new figure window)gtgt figure bar plot of a bell shaped curvegtgt x = -290229gtgt bar (x exp (-xx))gtgt figure stairstep plot of a sine wavegtgt x = 002510gtgt stairs (x sin (x))gtgt figure errorbar plotgtgt x = -2012gtgt y = erf (x) error function check help if you are interestedgtgt e = rand (size (x)) 10gtgt errorbar (x y e)

_end optional

34 PrintingBefore printing a figure you made you might want to add some information such as a title or change the189-196 lay-out a little Table 5 shows some of the commands that can be usedExercise 17Plot the functions y1 = sin(4x) y2 = x cos(x) y3 = (x + 1)minus1px for x = 0 025 10 and a single point(x y) = (4 5) in one figure with different colors and styles Make a legend containing the three functionsMake labels for both axes and a title Add a text to the single point saying single point Change the minimumand maximum values of the axes such that function y3 can be looked at in more detail _When the displayed figure is to your liking you can print it to paper The easiest way to do this is to click onFile in the menu-bar and to choose Print If in the print window you click OK your figure will be printed onthe printer indicated in the print window18Command Resultgrid onoff adds a grid to the plot at the tick marks or removes itaxis([xmin xmax ymin ymax]) sets the minimum and maximum values of the axesbox offon removes the axes box or shows itxlabel(rsquotextrsquo) plots the label text on the x axisylabel(rsquotextrsquo) plots the label text on the y axistitle(rsquotextrsquo) plots a title above the graphtext(xyrsquotextrsquo) adds text at the point (xy)gtext(rsquotextrsquo) adds text at a manually (with a mouse) indicated pointlegend(rsquofun1rsquorsquofun2rsquo) plots a legend box (move it with your mouse) to name your functionslegend off deletes the legend boxTable 5 Plot-manipulationsThere is also a print command which can be used to send a figure to a printer or output it to a file Youcan optionally specify a print device (ie an output format such as tiff or postscript) and options that controlvarious characteristics of the printed file (ie which Figure to print etc) You can also print to a file if youspecify the file name If you do not provide an extension print adds one Since they are many parametersthey will not be explained here (check help print to learn more) Instead try to understand the examplesgtgt print -dwinc print the current Figure to the current printer in colorgtgt print -f1 -deps myfileeps print Figure no1 to the file myfileeps in blackgtgt print -f1 -depsc myfileceps print Figure no1 to the file myfilecoleps in colorgtgt print -dtiff myfile1tiff print the current Figure to the file myfile1tiffgtgt print -dpsc myfile1cps print the current Figure to the file myfile1ps in colorgtgt print -f2 -djpeg myfile2 print Figure no2 to the file myfile2jpgExercise 18Exercise with printing (especially to a file) the figure from Exercise 16 _

4 Curve fitting and interpolationThere are two ways to describe data with an analytical function- curve fitting or regression finding a smooth curve that best fits (approximates) the data accordingto a criterion (eg best least square fit) The curve does not have to go through any of the data points- interpolation the data are assumed to be correct desired in a way to describe what happens betweenthe data points In other words given a finite set of points the goal of interpolation is to find a functionfrom a given class of functions (eg polynomials) which passes through the specified pointsThe figure below illustrates the difference between regression (curve fitting) and interpolationminus5 0 5minus6minus4minus20246810fiting a 3rd order polynomialinterpolation

41 Curve fittingMatlab interprets the best fit of a curve by the lsquoleast squares curve fittingrsquo The curve used is restricted153-15619to polynomials With the command polyfit any polynomial can be fitted to the data polyfit (x y n)finds the coefficients of a polynomial of degree n that fits the data (finds the linear relation between x and y)Letrsquos start with finding a linear regression of some datagtgt x = 010gtgt y = [-10 24 102 158 284 276 299 405 483 522 751]gtgt p = polyfit (x y 1) find the fitting polynomial of order 1p = 06772 -03914

The output of polyfit is a row vector of the polynomial coefficients the solution of this example is thereforey = 06772x minus 03914Exercise 19Execute the above example Plot the data and the fitted curve in a figure Determine the 2nd and 9th orderpolynomial of these data as well and display the solution in a figureHint x1 = linspace (xmin xmax n) results in a vector with n element evenly distributed from xmintill xmax z = polyval (p x1) calculates the values of the polynomial for every element of x1 _Exercise 20Define x and y as followsgtgt x = -55gtgt y = 02x^3 - x + 2 a 3rd order polynomialgtgt y = y + randn(111) add some noise to yDetermine the 3rd order polynomial fitting y (note that because of added noise the coefficients are differentthat originally chosen) Try some other polynomials as well Plot the results in a figure _42 InterpolationThe simplest way to examine an interpolation is by displaying the function plots with the command plot157-161 The neighboring data points are connected with straight lines This is called a linear interpolation Whenmore data-points are taken into account the effect of interpolation becomes less visible Analyzegtgt x1 = linspace(0 2pi2)gtgt x2 = linspace(0 2pi4)gtgt x3 = linspace(0 2pi16)gtgt x4 = linspace(0 2pi256)gtgt plot(x1sin(x1)x2sin(x2)x3sin(x3)x4sin(x4))gtgt legend(rsquo2 pointsrsquorsquo4 pointsrsquorsquo16 pointsrsquorsquo256 pointsrsquo)

5 Numerical analysisNumerical analysis can be used whenever it is impossible or very difficult to determine the analytical solutionMatlab can be used to find for example the minimum maximum or integral of a certain function51 Evaluation of a functionAs said before the command plot plots a function by connecting defined data points Sometimes however a168-173 function is constant and not very interesting over some range and then acts unexpectedly wildly over anotherWith plot this function might be misinterpreted The command fplot is then useful An examplegtgt x = 0pi82pigtgt y = sin (8x)gtgt plot (x y rsquobrsquo)gtgt hold ongtgt fplot (rsquosin (8z)rsquo [0 2pi] rsquorrsquo)gtgt title (rsquosin (8z)rsquo)gtgt hold off20Command Resultfplot (rsquofunrsquo [min x max x]) plots the function fun for min x till max xfmin (rsquofunrsquo min x max x) gives the x-value of the miminum of thefunction fun between min x and max xfzero (rsquofunrsquo x0) gives the x-value for which the functionfun is zero in the neighborhood of x0Table 6 Evaluation of a functionExecution of these commands results in a figure with an almost straight blue line and a red sine fplot canalso be used to plot a defined functiongtgt f = rsquosin (8z)rsquogtgt fplot (f [0 2pi] rsquorrsquo)gtgt title (f)Other useful commands for a detailed study of a range of a function are listed in Table 6Exercise 21The command fmax does not exist Use one or more of the commands from Table 6 to determine the maximumof the function x cos(x) for 10 lt x lt 15 _52 Integration and differentiationThe integral- or the surface underneath a 2D function- can be determined with the command trapz trapz173-182 does this by measuring the surface between the x-axis and the -by a straight line connected- data points Theaccuracy of this method depends on the distance between the data pointsgtgt x = 00510 y = 05 sqrt (x) + x sin (x) area1 = trapz (x y)

area1 =181655gtgt x = 000510 y = 05 sqrt (x) + x sin (x) area2 = trapz (x y)area2 =183846Differentiation is done by determining the slope in each data point Numerically this is done by first fitting apolynomial followed by differentiating this functiongtgt x = 010gtgt y = [-10 24 102 -158 284 276 775 35 483 522 751]gtgt p = polyfit (x y 5)p = 00026 -00554 03634 -06888 02747 00877gtgt dp = polyder (p)dp = 00132 -02216 10903 -13776 02747gtgt x1 = linspace (0 10 200)gtgt z = polyval (p x1)gtgt dz = polyval (dp x1)gtgt plot (x y rsquog-rsquo x1 z rsquobrsquo x1 dz rsquorrsquo)gtgt legend (rsquodata pointsrsquo rsquocurve fitrsquo rsquoderivativersquo)Exercise 22Determine the integral and derivative of the 4th polynomial fitted through (xy) with x = [4 5 6 7 8 9 1011 12 13] y = [1284 1200 724 -096 -1116 -2096 -2700 -2496 -956 2544] _

6 Control flowAs you know it is possible to execute more than one command at the same time (see section 11) Theseparate commands should then be divided by commarsquos (to display the output) or by semicolons (to suppress21output display) Control flow loops increase the number of possibilities A control flow structure is a block ofcommands that allows conditional code execution and making loops61 Logical and relational operatorsTo use control flow commands it is necessary to perform operations that result in logical values TRUE or88-91 FALSE In Matlab the result of a logical operation is 1 if it is true and 0 if it is false Table 7 shows therelational and logical operations2 Another way to get to know more about them is to type help relop Therelational operators lt lt= gt gt= == and ~= can be used to compare two arrays of the same size or anarray to a scalar The logical operators amp | and ~ allow for the logical combination or negation of relationaloperators In addition three functions are also available xor any and all (use help to find out more)Important The logical amp and | have the equal precedence in Matlab which means that those operatorsassociate from left to right A common situation isgtgt b = 10gtgt 1 | b gt 0 amp 0ans =0gtgt (1 | b gt 0) amp 0 this indicates the same as aboveans =0gtgt 1 | (b gt 0 amp 0)ans =1This shows that you should always use brackets to indicate in which way the operators should be evaluatedCommand Resulta = (b gt c) a is 1 if b is larger than c Similar are lt gt= and lt=a = (b == c) a is 1 if b is equal to ca = (b ~= c) a is 1 if b is not equal ca = ~b logical complement a is 1 if b is 0a = (b amp c) logical AND a is 1 if b = TRUE AND c = TRUEa = (b | c) logical OR a is 1 if b = TRUE OR c = TRUETable 7 Relational and logical operationsExercise 23Predict and check the result of each of the operations of Table 7 for b = 0 and c = -1 _Exercise 24Define two vectors with seven elements (randn(17)) and perform all logical operations including xor anyand all _Exercise 25While doing logical operations between a vector and a scalar each element of the vector is compared to thescalar Predict and check the result of each logical operator for the vector b = [2 31 -40 0] and the scalarc = 0 _Before moving on check whether you now understand the following relations

gtgt a = randperm(10) a random permutation of the numbers from 1 to 10gtgt b = 110gtgt b - (a lt= 7) subtracts from b a 0-1 vector taking 1 for a lt= 7 and 0 otherwisegtgt (a gt= 2) amp (a lt 4) returns ones at positions where 2 lt= a lt 4gtgt ~(b gt 4) returns ones at positions where b lt= 4gtgt (a == b) | b == 3 returns ones at positions where a is equal to b or b is equal to 3gtgt any (a gt 5) returns 1 when ANY of the a elements are larger than 5gtgt any (b lt 5 amp a gt 8) returns 1 when there in the evaluated expressiongtgt (b lt 5 amp a gt 8) appears at least one 1gtgt all (b gt 2) returns 1 when ALL b elements are larger than 22rdquoequal tordquo in the table on page 88 of rdquoThe Student Edition of Matlabrdquo must be rdquo==rdquo instead of rdquo=rdquo2262 Conditional code executionSelection control structures if-blocks are used to decide which instruction to execute next depending whether117-119 expression is TRUE or not The general description is given below In the examples below the command dispis frequently used This command displays on the screen the text between the quotesbull if endSyntaxif logical_expressionstatement1statement2endExampleif (a gt 0)b = adisp (rsquoa is positiversquo)endbull if else endSyntaxif logical_expressionblock of statementsevaluated if TRUEelseblock of statementsevaluated if FALSEendExampleif (temperature gt 100)disp (rsquoAbove boilingrsquo)toohigh = 1elsedisp (rsquoTemperature is OKrsquo)toohigh = 0endbull if elseif else endSyntaxif logical_expression1block of statements evaluatedif logical_expression1 is TRUEelseif logical_expression2block of statements evaluatedif logical_expression2 is TRUEelseblock of statements evaluatedif no other expression is TRUEendExampleif (height gt 190)disp (rsquovery tallrsquo)elseif (height gt 170)disp (rsquotallrsquo)elseif (height lt 150)disp (rsquosmallrsquo)

elsedisp (rsquoaveragersquo)endRemark To do the exercises below a script m-file will be useful It is an external file that contains asequence of Matlab commands What you need to do is to open an editor enter all commands needed forthe solution of a task save it with the extension rsquomrsquo (eg mytaskm) and then run it from the CommandWindow by typing mytask To open the Matlab editor go to the File menu-bar choose the Open optionand then m-file A new window will appear where you can write your scripts and save them on the disk Allcommands in the script will be executed in Matlab You will learn more on script m-files in section 91Important m-script file must be saved in one of the directories in Matlabrsquos pathAn example A script shortm can be created from the two lines given below and run by calling shortx = 0054plot (x sin(x) rsquo-rsquo)Exercise 26Create a script that asks for a number N and computes the drag coefficient C depending on the Reynoldrsquos23number N (make use of the if elseif construction) The command input might be useful here(read pages 32-33 from rdquoThe Student Edition of Matlabrdquoor use help)C =8gtgtgtltgtgtgt0 N _ 024N N 2 (0 01]24N (1 + 014N07) N 2 (01 1e3]043 N 2 (1e3 5e5]019 minus 8e4N N gt 5e5Check whether your script works correctly Compute the drag coefficient for eg N = -3e3 001 56 1e3 3e6(remember that eg 3e3 is a Matlab notation of 3 _ 103) _Exercise 27Write a script that asks for an integer and checks whether it can be divided by 2 or 3 Consider all possibilitiessuch as divisible by both 2 and 3 divisible by 2 and not by 3 etc (use the command rem) _Another selection structure is switch which switches between several cases depending on an expression which119-120 is either a scalar or a stringSyntaxswitch expressioncase choice1block of commands1case choice2a choice2bblock of commands2otherwiseblock of commandsendExamplemethod = 2switch methodcase 12disp(rsquoMethod is linearrsquo)case 3disp(rsquoMethod is cubicrsquo)case 4disp(rsquoMethod is nearestrsquo)otherwisedisp(rsquoUnknown methodrsquo)endThe statements following the first case where the expression matches the choice are executed Thisconstruction can be very handy to avoid long if elseif else end constructions Theexpression can be a scalar or a string A scalar expression matches a choice if expression == choice Astring expression matches a choice if strcmp(expression choice) returns 1 (is true) (strcmp is a commandcomparing two strings)Important Note that the switch-construction only allows the execution of one group of commandsExercise 28Assume that the months are represented by numbers from 1 to 12 Write a script that asks you to provide a

month and returns the number of days in that particular month Alternatively write a script that asks youto provide a month name (eg rsquoJunersquo) instead of a number Use the switch-construction _63 LoopsIteration control structures loops are used to repeat a block of statements until some condition is met Two114-117 types of loops existbull the for loop that repeats a group of statements a fixed number of timesSyntaxfor index = firststeplastblock of statementsendExamplesumx = 0for i=1length(x)sumx = sumx + x(i)end24You can specify any step including a negative value The index of the for-loop can be also a vectorSee some examples of possible variationsExample 1for i=12nendExample 2for i=n-13endExample 3for x=0054disp(x^2)endExample 4for x=[25 9 81]disp(sqrt(x))endbull while loop which evaluates a group of commands as long as expression is TRUESyntaxwhile expressionstatement1statement2statement3endExampleN = 100iter = 1msum = 0while iter lt= Nmsum = msum + iteriter = iter + 1endExercise 29Given the vectors x and y write a script computing the a matrix whose elements should be created accordingto a formula given below (make use of the length command to check the number of elements in both vectors)- aij = yixj (make sure that a division by zero will not occur)- bij = xi _ yj

- cij = 1 max (xi yj)_Exercise 30Determine the sum of the first 50 squared numbers with a control loop _Exercise 31Write a script to find the largest value n such that the sum p13 + p23 + + pn3 is less than 1000 _optionalExercise 32Write a script that transposes a matrix A Check its correctness with the Matlab operation Arsquo _Exercise 33

Write a script that asks for a temperature in degrees Celsius tc and computes the equivalent temperature indegrees Fahrenheit tf (use the formula tf = 95 _ tc + 32) The script should keep running until no numberis provided to convert The functions input and isempty (use help to learn more) should be useful here _end optional

64 Evaluation of logical and relational expressions in the control flow structuresThe relational and logical expressions may become more complicated It is not difficult to operate on them ifyou understand how they are evaluated To explain more details let us consider the following exampleif (~isempty(data)) amp (max(data) lt 5)endThis construction of the if-block is necessary to avoid comparison if data happens to be an empty matrix Insuch a case you cannot evaluate any expression and Matlab gives an error The amp operator returns 1 only ifboth expressions ~isempty (data) and max(data) lt 5 are true and 0 otherwise When data is an emptymatrix the next expression is not evaluated since the whole amp-expression is already known to be false Thesecond expression is checked only if data is a non-empty matrix Remember to put logical expression unitsbetween brackets to avoid wrong evaluations25Important The fact that computers make use of floating-point arithmetic means that often you should becareful when comparing two floating-point numbers just byif (x == y)end(Of course such a construction is allowed eg when you know that x and y represent integers) Instead of theabove construction you may try using thisif (abs (x - y) lt tolerance) eg tolerance = 1e-10endExercise 34Consider the following examplemax_iter = 50tolerance = 1e-4iter = 0xold = 01x = 1while (abs (x - xold) gt tolerance) amp (iter lt max_iter)xold = xx = cos(xold)iter = iter + 1endThis short program tries to solve the equation cos(x) = x (x is the solution found) Make the script solve cosfrom the presented code Note that the while-loop is repeated as long as both conditions are true If eitherthe condition (|x - xold| lt= tolerance) or (iter gt= max iter) is fulfilled then the loop is quitted Runthe script solve cos for different tolerance parameters eg 1e-3 1e-6 1e-8 1e-10 etc Use format long tocheck more precisely how much the found x is really different from cos(x) For each tolerance value checkthe number of performed iterations (iter value) _Exercise 35Create the script solve cos2 which is equal to the one given replacing the while-loop condition bywhile (abs (x - xold) gt tolerance) | (iter lt max_iter)Try to understand the difference and confirm your expectations by running solve cos2 What happens toiter _optional

65 Numerical analysis and the control flow structuresTake a look at the problem of a Taylor expansion The series will be determined numerically until the additionalterms are smaller than a defined precision Look at the Taylor expansion of 11minusx = 1 + x + x2 + withx = 042s = 0 x = 1 s = 0 x = 1x0 = 042 x0 = 042while (x gt 1e-6) or while (x gt (1e-6)s)s = s + x s = s + xx = x x0 x = x x0end endThe approximation of 11minusx is returned in s (first letter of sum) In the first case (on the left) the iteration

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 6: Introduction to Programming Using Matlab

store or retrieve data In the end Matlab can also be treated as a user-friendly programming language which gives the possibility to handle mathematical calculations in an easy wayRunning Matlab creates one or more windows on your screen The most important is the Matlab Command Window which is the place where you interact with Matlab The string gtgt is the Matlab prompt (except for the Student Edition that has the EDUgtgt prompt) When the Command window is active a cursor appears after the prompt indicating that Matlab is waiting for your command which can be eg 173 or cos(x)

11 Input via the command-line2-10 Matlab is an interactive system commands followed by Enter are executed immediately The results are ifdesired displayed on screen However execution of a command will not be possible or will go wrong when thecommand is not typed according to the rules Table 1 shows a list of commands used to solve the indicatedmathematical equation (a b x and y are numbers)There are also commands that perform a specific task such as help work with a file-system like cd or workwith matrices like rank Below you find basic information that is important when starting with Matlabbull Commands in Matlab are executed by pressing Enter or Return The output will be displayed onscreen immediately Try the followinggtgt 3 + 75gtgt 184gtgt 3 7Note that spaces are not important in Matlabbull The result of the last execution is called ans It can be used on the next command line Try for instancegtgt 144ans =35000gtgt ans^(-6)ans =54399e-0454399e-04 is a computer notation of 54399 _ 10minus4 (see Preliminaries) Note that ans is always overwrittenby the last commandbull ans is an example of a Matlab built-in variable It stores the result of the recently performed computationYou can also define your own variables Look how the information is stored in the variables aand bgtgt a = 144a =35000gtgt b = a^(-6)b =54399e-04Read Preliminaries to better understand the concept of variables You will learn more on Matlabvariables in section 23bull When the command is followed by a semicolon () the output is suppressed Check the differencebetween the following expressionsgtgt 3 + 75gtgt 3 + 75gtgt x = 34bull It is possible to execute more than one command at the same time the separate commands should thenbe divided by commas (to display the output) or by semicolons (to suppress the output display) eggtgt sin(pi4) cos(pi) sin(0)ans =07071ans =0Note that the value of cos(pi) is not printedbull The output may contain some empty lines this can be suppressed by the command format compactIn contrast the command format loose will insert extra empty lines4Mathematical notation Matlab-commanda + b a + ba minus b a - bab a b3xy 3 x ya

b a b or b a

ab a^bpx sqrt(x) or x^05_ pie exp(1)i i4 middot 103 4e3 or 410^33 minus 4i 3 - 4i or 3 - 4jsin x arctan x sin(x) atan(x) ex exp(x)ln x log(x)log x log10(x)|x| abs(x)Table 1 Translation of mathematical notation to Matlab commandsbull Matlab is case sensitive There is a difference between capital and normal letters for example a iswritten as a in Matlab A will result then in an errorbull All text after a percent sign until the end of a line is treated as a comment Enter eg the followinggtgt sin(314159) this is an approximation of sin(pi)You will notice that some examples in this text are followed by comments They are meant for you andyou should skip them while typing those examplesbull Previous commands can be fetched back with the -key The command can also be changed the and -keys may be used to move around in a line and edit itKeep in mind that Matlab executes the command immediately it might be useful to have an idea of theexpected outcome12 help-facilitiesMatlab provides assistance through extensive online help The help command is the simplest way to get349-359 help that is if you know the topic or command on which you want help For examplegtgt help elfungives information on the elementary math functions of Matlab The command help displays a list of allpossible topics The topic you want help on must be exact and spelled correctly The commando lookfor ismore useful if you do not know the exact name of the command or topic For examplegtgt lookfor inversedisplays all commands for which the word inverse is included in its help-text This command results in a list ofcommands with a short description Besides the help and lookfor commands there is also a separate mousedriven help The helpwin command opens a new window on screen which can be browsed in an interactiveway To learn more read pages 353-354 from rdquoThe Student Edition of Matlabrdquobook13 Interrupting a command or programSometimes you might spot an error in your command or program Due to this error it can happen that thecommand or program does not stop Pressing Ctrl-C forces Matlab to stop the process After this theMatlab-prompt (gtgt) re-appears This may take a while though514 PathIn Matlab commands or programs are contained in m-files which are just plain text files and have an37-39 extension rsquomrsquo The m-file must be located in one of the directories which Matlab automatically searchesThe list of these directories can be listed by the command path One of the directories that is always takeninto account is the current working directory which can be identified by the command pwd Use path addpathand rmpath functions to modify the path Here is an examplegtgt pathcmatlabcmatlabtoolboxmatlabgeneralcmatlabtoolboxmatlabopsgtgt addpath hpersonal assume that this is your directorygtgt pathhpersonalcmatlabcmatlabtoolboxmatlabgeneralcmatlabtoolboxmatlabopsIt is also possible to access the path browser from the File menu-bar instead15 Workspace issuesIf you work in the Command Window Matlab memorizes all commands that you entered (as you alreadyknow - to recall previous commands the -key is useful) and all variables that you created This can be6

2425verified with the commands who which gives a list of variables present in the workspace and whos whichincludes information on name number of allocated bytes and class of the variables For example assuming thatyou performed all commands given in the beginning after typing who you should get the following informationgtgt whoYour variables area ans b xThe command clear ltnamegt deletes the variable ltnamegt from the Matlab workspace clear or clear allremoves all variables This is useful when starting a new exercise For examplegtgt clear a xgtgt whoYour variables areans b16 Saving and loading dataThe easiest way to save or load Matlab variables is by using (clicking) the File menu-bar and then the Save26 Workspace as and Load Workspace items Also Matlab commands exist which allow you to saveand load data from filesThe command save allows for saving your workspace variables either into a binary file or an ASCII file (checkPreliminaries on binary and ASCII files) Binary files automatically get the rsquomatrsquo extension which is nottrue for ASCII files However it is recommended to add a rsquotxtrsquo or dat extensionExercise 1Learn how to use the save command by exercisinggtgt s1 = sin(pi4) s2 = sin(pi2)gtgt c1 = cos(pi4) c2 = cos(pi2)gtgt str = rsquohello worldrsquo this is a string example you will learn about strings latergtgt save saves all variables in binary format to the file matlabmatgtgt save data saves all variables in binary format to the file datamat6gtgt save numdata s1 c1 saves numeric variables s1 and c1 to the file numdatamatgtgt save strdata str saves a string variable str to the file strdatamatgtgtgtgt save allsin s saves all variables that match the pattern to allsinmatgtgt save allcosdat c -ascii saves c1c2 in 8-digit ascii format to allcosdat_The load command allows for loading variables into the workspace It uses the same syntax as saveExercise 2Assuming that you have done the previous exercise try to load variables from the created filesImportant before each load command clear the workspace and after loading check which variables arepresent in the workspace (using who)gtgt load loads all variables from the file matlabmatgtgt load data s1 c1 loads only specified variables from the file datamatgtgt load strdata loads all variables from the file strdatamatIt is also possible to read ASCII files that contain rows of space separated values Such a file may containcomments that begin with a percent character The resulting data is placed into a variable with the samename as the ASCII file (without the extension) Check for examplegtgt load allcosdat loads data from the file allcosdat into variable allcosgtgt who lists variables present in the workspace now_

2 Mathematics with numbers vectors and matricesThe basic element of Matlab is a matrix (or an array) Special cases arebull a 1 times 1-matrix a scalar or a single numberbull a matrix existing only of one row or one column a vector21 Single numbersYou have already got some experience with Matlab and you know that it can be used as a calculator To do4-614-1727that you can for example simply typegtgt 31256The result will beans =55714By default Matlab displays only 5 digits The command format long increases this number to 15 format

short reduces it to 5 again For examplegtgt format longgtgt 31256ans =557142857142857Exercise 3Define the format Matlab such that empty lines are suppressed and the output is given with 5 digitsCalculategtgt pigtgt sin(pi)Note that the answer is not exactly 0 _Use the command format to put Matlab in its standard-format ie short and loose7intermezzo

22 An introduction to floating-point numbersIn a computer numbers can be represented only in a discrete form It means that numbers are stored286 within a limited range and with a finite precision Integers can be represented exactly with the base of 2(read Preliminaries on bits and the binary system) The typical size of an integer is 16 bits so the largestpositive integer which can be stored is 216 = 65536 If negative integers are permitted then 16 bits allow forrepresenting integers between minus32768 and 32767 Within this range operations defined on the set of integerscan be performed exactlyHowever this is not valid for other real numbers In practice computers are integer machines and are capableof representing real numbers only by using complicated codes The most popular code is the floating pointstandard The term floating point is derived from the fact that there is no fixed number of digits before andafter the decimal point meaning that the decimal point can float Note that most floating-point numbers thata computer can represent are just approximations Therefore care should be taken that these approximationslead to reasonable results If a programmer is not careful small discrepancies in the approximations can causemeaningless results Note the difference between eg the integer arithmetic and floating-point arithmeticInteger arithmetic Floating-point arithmetic2 + 4 = 6 187 = 257143 4 = 12 25714 7 = 1799982511 = 2 100003 = 33333e+03When describing floating-point numbers precision refers to the number of bits used for the fractional partThe larger the precision the more exact fractional quantities can be represented Floating-point numbers areoften classified as single precision or double precision A double-precision number uses twice as many bits asa single-precision value so it can represent fractional values much better However the precision itself is notdouble The extra bits are also used to increase the range of magnitudes that can be representedMatlab relies on a computerrsquos floating point arithmetic You could have already noticed that in the last408-410 exercise since the value of sin(_) was almost zero and not completely zero It came from the fact that boththe value of _ is represented with a finite precision and the sin function is also approximatedThe fundamental type in Matlab is double which stands for a representation with a double precision It uses64 bits The single precision obtained by using the single type offers 32 bits Since most numeric operationsrequire high accuracy the double type is used by defaultThe exact machine precision might be defined as the smallest positive number _ that added to 1 does notchange the result so 1 + _ = 1 in floating-point arithmetic this value is larger than zero (in exact arithmeticof course _ = 0 holds) Matlab machine precision is stored in the built-in variable eps _ 22204e-16 Thismeans that the relative accuracy of individual arithmetic operations is about 16 digitsend intermezzo

23 Assignments and variablesWorking with complex numbers is easily done with MatlabExercise 4Choose two complex numbers for example -3 + 2i and 5 - 7i Try to add subtract multiply and dividethese two numbers _During this exercise the complex numbers had to be typed four times To reduce this assign each number to4-610-12a variable For the previous exercise this results ingtgt z = -3 + 2igtgt w = 5 - 7igtgt y1 = z + w y2 = z - w y3 = z w y4 = z w y5 = w zFormally there is no need to declare (ie define the name size and the type of) a new variable in Matlab Avariable is simply created by an assignment (the way it has been done above) Each newly created numerical

variable is always of the double type You can change this type by converting it into eg the single type 11a variable a is converted into a different type by performing eg a = single(a) a = int16(a) etc8In some cases when huge matrices should be handled and precision is not very important this might be a wayto proceed Also when only integers are taken into consideration it might be useful to convert the doublerepresentations into eg int16 or int321 integer types Since most computations should be performed with ahigh accuracy Matlab automatically chooses the double type It means that real numbers are approximatedwith the highest possible precision However it is important to emphasize that integer numbers are alwaysrepresented exactly no matter which numeric type is usedBear in mind that undefined values cannot be assigned to a variable So the following is not possiblegtgt clear x to make sure that x does not existgtgt fun = x^2 + 4 sin (x)It becomes possible bygtgt x = pi 3 fun = x^2 + 4 sin (x)Exercise 5Predict the result ofx = pi 3 x = x - 1 x = x + 5 x = abs(x) xCheck your prediction by performing these commands in Matlab _Exercise 6Here are some examples of different types of Matlab variables You do not need to understand them all nowsince you will learn more about them during the course Create them manually in Matlabgtgt this_is_my_very_simple_variable_today = 5 a number check what happens since thegtgt name is very long (gt 31 characters)gtgt 2t = 8 what is the problem with this commandgtgt this_is_a_matrix = [1 2 3 4 5 6] a matrixgtgt c = rsquoErsquo a charactergtgt str = rsquoHello worldrsquo a stringgtgt m = [rsquoJrsquorsquoorsquorsquohrsquorsquonrsquo] try to guess what it isCheck the types by using the command whos Use clear ltnamegt to remove a variable from the workspace _Exercise 7In addition to creating variables by assigning values to them a few other ways exist For instance there is anumber of built-in variables eg ans pi eps i inf or nan Find out what value is assigned to each of these74584 built-in variables _24 VectorsRow vectors are lists of numbers separated either by commas or by spaces They are examples of simple arrays41-49 The number of entries is known as the length of the vector (the command length exists as well) Their entitiesare referred to as elements or components The entries must be enclosed in [ ]gtgt v = [-1 sin(3) 7]v =-10000 01411 70000gtgt length(v)ans =3A number of operations can be done on vectors A vector can be multiplied by a scalar or addedsubtractedtofrom another vector with the same length or a number can be addedsubtracted tofrom a vector Allthese operations are carried out element-by-element Vectors can be also built from the already existing onesgtgt v = [-1 2 7] w = [2 3 4]gtgt z = v + w an element-by-element sumz =1 5 119gtgt v3 = v + 2 add 2 to all elements of vector v3v3 =1 4 9gtgt t = [2v -w]ans =-2 4 14 -2 -3 -4Also a particular value can be changed or displayedgtgt v(2) = -1 w(2) change the 2nd value of v display the 2nd value of wv =-1 -1 7ans =

3A colon notation is an important shortcut used when producing row vectors (see Table 3 and help colon)gtgt 25ans =2 3 4 5gtgt -23ans =-2 -1 0 1 2 3In general firststeplast produces a vector of entities with the value first incrementing by the stepuntil it reaches lastgtgt 020524ans =02000 07000 12000 17000 22000gtgt -3310ans =-3 0 3 6 9gtgt 15-05-05 negative step is also possibleans =15000 10000 05000 0 -05000Parts of vectors can be extracted by using a colon notationgtgt r = [-126 2 3 -2] -126 =gt -1 1 3 5r =-1 1 3 5 2 3 -2gtgt r(36) get elements of r which are on the positions from 3 to 6ans =3 5 2 3gtgt r(125) get elements of r which are on the positions from 1 to 5 taken with the step of 2ans =-1 3 2gtgt r(5-12) what will you get hereTo create column vectors you should separate entries by a semicolon () or by new linesgtgt f = [-1 3 5]f =-135The same operations as on row vectors can be done on column vectors However you cannot for exampleadd a column vector to a row vector To do that you need an operation called transposing which converts acolumn vector into a row vector and vice versa10gtgt f = [-1 3 5] a column vectorgtgt frsquo frsquo is a row vectorans =-1 3 5gtgt v = [-1 2 7] a row vectorgtgt f + v you cannot add a column vector f to a row vector v Error using ==gt +Matrix dimensions must agreegtgt frsquo + vans =-2 5 12gtgt f + vrsquoans =-2512If x is a complex vector than xrsquo gives the conjugate transpose of x eggtgt x = [1+2i -1+i]x =10000 + 20000i -10000 + 10000igtgt xrsquo this is the conjugate transposeans =10000 - 20000i-10000 - 10000i

gtgt xrsquo this is the rsquonormalrsquo transposeans =10000 + 20000i-10000 + 10000iExercise 8Exercise to become acquainted with operating on row and column vectors Enter all examples given in thissection and make new variations yourself Exercise with the colon notation approach as well _25 MatricesAn ntimesk matrix is a rectangular array of numbers having n rows and k columns Defining a matrix in Matlabis similar to defining a vector The generalization is straightforward if you know that a matrix consists of row49-6175-86vectors (or column vectors) Commas or spaces are used to separate elements in a row and semicolons areused to separate individual rows For example the matrix A =01 2 34 5 67 8 91Ais defined asgtgt A = [1 2 3 4 5 6 7 8 9] row by row inputA =1 2 34 5 67 8 9Another examples are for instancegtgt A2 = [14 -125]A2 =1 2 3 4-1 1 3 5gtgt A3 = [1 3-4 7]A3 =1 3-4 711Command ResultA(ij) Aij

A(j) j-th column of AA(i) i-th row of AA(klmn) (l minus k + 1) times (n minus m + 1) matrix with elements Aij with k _ i _ l m _ j _ nv(ij)rsquo rsquovector-partrsquo (vi vi+1 vj) of vector vTable 2 Manipulation of (groups of) matrix-elementsCommand Resultn = rank (A) n becomes the rank of matrix Ax = det (A) x becomes the determinant of matrix AC = size (A) C becomes a row-vector with 2 elements the number of rows and columns of Ax = trace (A) x becomes the trace (sum of diagonal elements) of matrix Ax = norm (v) x becomes the length of vector vC = A + B sum of two matricesC = A - B subtraction of two matricesC = A B multiplication of two matricesC = A B rdquoelement-by-elementrdquo multiplication (A and B are of equal size)C = A ^ k power of a matrix (k 2 Z can also be used for Aminus1)C = A ^ k rdquoelement-by-elementrdquo power of a matrixC = Arsquo the transposed of a matrix AT

C = A B rdquoelement-by-elementrdquo division (A and B are of equal size)U = A B finds the solution that minimizes the squared error in Ax minus BU = B A solution of XA = B analogous to the previous commandC = inv (A) C becomes the inverse of AC = null (A) C is an orthonormal basis for the null space of Aobtained from the singular value decompositionC = orth (A) C is an orthonormal basis for the range of AC = rref (A) C is the reduced row echelon form of AL = eig (A) L is a vector containing the -possibly complex- eigenvalues of a square matrix A[X D] = eig (A) produces a diagonal matrix D of eigenvalues and a full matrix X

whose columns are the corresponding eigenvectors of AS = svd (A) S is a vector containing the singular values of A[U S V] = svd (A) S is a diagonal matrix of the same dimension as Awith nonnegative diagonal elements in decreasing orderThe columns U and V are the accompanying singular vectorsx = linspace(a b n) generates a vector x of n equally spaced points between a and bx = logspace(a b n) generates a vector x starting at 10a and ended at 10b containing n valuesA = diag (v) gives a diagonal matrix with the elements v1 v2 vn on the diagonalA = eye (n) A is a n times n identity matrixA = zeros (n m) A is a n times m matrix with zeros (default m = n)A = rand (n m) A is a n times m matrix with elements uniformly distributed between 0 and 1A = randn (n m) ditto - with elements standard normal distributedv = max (A) v becomes a vector with the maximum value of the elements in each column of Aor v is the maximum of all elements if A is a vectorv = min (A) ditto - with minimumv = sum (A) ditto - with sumTable 3 Frequently used matrix operations and functions12Transposing a vector changes it from a row to a column or the other way around This idea can be extendedto a matrix where transposing interchanges rows with the corresponding columns as in the examplegtgt A2 A2rsquoA2 =1 2 3 4-1 1 3 5ans =1 -12 13 34 5gtgt size(A2) returns the size (dimensions) of a matrixans =2 4gtgt size(A2rsquo)ans =4 2There exists also some built-in matrices of size specified by the user (see Table 2) A few examples are givenbelowgtgt E = [] an empty matrix of 0-by-0 elementsE =[]gtgt I = eye(3) the identity matrixI =1 0 00 1 00 0 1gtgt B = rand(23) a matrix of random numbers you will get a different one00227 09101 0922200299 00640 03309gtgt O = ones(32)O =1 11 11 1gtgt r = [1 3 -2] R = diag(r) create a diagonal matrix with r on the diagonalR =1 0 00 3 00 0 -2gtgt v = linspace(124) a vector is also an example of a matrixv =10000 13333 16667 20000It is often needed to build a larger matrix from the smaller onesgtgt x = [4 -1] y = [-1 4]x =4

-1y =-1 4gtgt X = [x yrsquo] X consists of the columns x and yrsquoX =4 -1-1 4gtgt T = [ -1 3 4 4 5 6] t = 1313gtgt T2 = [T t] add to T a new row namely the row vector t getting T2T2 =-1 3 44 5 61 2 3gtgt G = [1 5 4 5 0 2] G is a matrix of the 3-by-2 size check size(G)gtgt T3 = [T2 G] T3 consists of T2 and new columns being the colums of GT3 = added at the end of T2-1 3 4 1 54 5 6 4 51 2 3 0 2gtgt [diag(56) ones(32)]ans =5 00 61 11 11 1A part can be extract from a matrix in a similar way as from a vector Each element in the matrix is indexedby a row and a column to which it belongs Mathematically the element from the i-th row and the j-thcolumn of the matrix A is denoted by Aij Matlab provides the A(ij) notationgtgt A = [13 46 79]A =1 2 34 5 67 8 9gtgt A(12) A(23) A(31)ans =2ans =6ans =7gtgt A(43) A is a 3-by-3 matrix Index exceeds matrix dimensionsgtgt A(23) = A(23) + 2A(11)A =1 2 34 5 87 8 9Having defined a matrix it is easy to extended it automatically For the matrix A it can be done eg asfollowsgtgt A(52) = 5 assign 5 to the position (52) the uninitializedA = elements become zeros1 2 34 5 87 8 90 0 00 5 0Different parts of the matrix A can be now extractedgtgt A(2) extract the 2nd column of Aans =25814

05gtgtgt A(34) extract the rows 3rd and 4th of Aans =7 8 90 0 0gtgt A(2312) extract a part of Aans =4 57 8If needed the other zero elements of the matrix A can be also defined by eggtgt A(4) = [1 2 3] assign vector [1 2 3] to the 4th row of Agtgt A(5[13]) = [4 5] a rsquoshortcutrsquo when assigning A(51) = 4 and A(53) = 5gtgt A how does the matrix A look like nowAs you have seen in the examples above it is possible to manipulate (groups of) matrix-elements Thecommands are shortly explained in Table 2Exercise 9Define the matrix A = [14 58 1 1 1 1] Predict and check the result ofgtgt B = A(3)gtgt C = A(1322)gtgt A(11) = 9gtgt A(2313) = [0 0 0 0 0 0]gtgt A(l212) = [l l 3 3]gtgt A = A(3314)_Exercise 10Define the matrices T=[ 3 4 1 8 -4 3] A = [diag(-123) T -4 4 1 2 1] Perform the followingoperations on the matrix Abull extract a vector consisting of the 2nd and 4th elements of the 3rd rowbull find the minimum of the 3rd columnbull find the maximum of the 2nd rowbull compute the sum of the 2nd columbull compute the mean of the 1st and 4th rowsbull extract the submatrix consisting of the 1st and 3rd rows and all columnsbull extract the submatrix consisting of the 1st and 2nd rows and the 3rd 4th and 5th columnsbull compute the total sum of the 1st and 2nd rowsbull add 3 to all elements of the 2nd and 3rd colums_Table 3 shows some frequently used matrix operations and functions A few examples are provided belowgtgt B = rand(23) a matrix of random numbers you will get a different oneB =09501 06068 0891302311 04860 07621gtgt B2 = [1 2 5 1 5 6]gtgt B + B2rsquo add two matrices why B2rsquo is needed instead of B2ans =19501 56068 5891322311 14860 67621gtgt S = ans4 divide all elements of the matrix ans by 4S =04875 14017 1472805578 03715 1690515gtgt C = [1 -1 4 7 0 -1]gtgt B C matrix multiplication is not defined for B and C Error using ==gt Inner matrix dimensions must agreegtgt B C but you can multiply element-by-elementans =09501 -06068 3565216180 0 -07621gtgt D = B Crsquo or you can make the multiplication legal Crsquo is now 3-by-2D =39085 5759627935 08559

gtgt D^3 this is equivalent to D D Dans =1992503 2041413990133 910548gtgt D^3 - 2 do for all elements raise to the power 3 and subtract 2ans =577069 1890638198005 -13731gtgtgtgt r = [1 3 -2]r B2 this is a legal operation r is a 1-by-3 matrix and B2 isans = 3-by-2 matrix B2 r is an illegal operation6 -7Remind that an n-by-k matrix A (having n rows and k columns) can be multiply by another matrix B onlyif B has k rows ie S is of the k-by-m size (m is arbitrary) As a result you get an n-by-m matrixA ˙B = C A 2 Rntimesk B 2 Rktimesm C 2 Rntimesm

RemarkYou can now compute the inner product between two vectors x and y xT y = Pi xi yi in a simple waygtgt f = [-1 3 5] a column vectorgtgt v = [-1 2 7] a column vectorgtgt frsquo v this is the inner productans =42gtgt f vrsquo be careful now a 3-by-1 matrix is multiplied by a 1-by-3gtgt matrix which results in a 3-by-3 matrix (the outer product)ans =1 -2 -7-3 6 21-5 10 35gtgt f v this is an element-by-element multiplication1635gtgt sum (f v) this is an another way to compute the inner productans =42Exercise 11Perform all operations from Table 3 using chosen matrices A and B vector v and scalars k a b n and m _Exercise 12Let A be a random 3 times 3 matrix and b a random 3 times 1 vector Given that Ax = b then x = Aminus1b Find x(there exist at least two possible commands to do this look at Table 3) _optionalThe concept of an empty matrix [] is also very useful in Matlab For instance a few columns or rows canbe removed from a matrix by assigning an empty matrix to it Try for example16Symbol Color Symbol Styley yellow dotted liner red o circlesg green - solid lineb blue - dashdotted lineTable 4 Plot colors and stylesgtgt C = [1 2 3 4 5 6 7 8 1 1 1 1]gtgt D = C D(2) = [] now a copy of C is in D remove the 2nd column of Dgtgt C ([13]) = [] remove the rows 1 and 3 from Cend optional

3 VisualizationMatlab can be used to visualize the results of an experiment Therefore you should define variables each ofthem containing all values of one parameter to plot31 Simple plotsWith the command plot a graphical display can be made plot(y) draws the points (1 y(1)) (2 y(2)) 184 (n y(n)) and connects the points with a straight line plot(xy) does the same for (x(1) y(1)) (x(2) y(2)) (x(n) y(n)) x and y have to be row- or column vectors of equal lengthThe commands loglog semilogx and semilogy are similar to plot except that they use logarithmic axesExercise 13Type the following commands after predicting the resultgtgt x = 0330

gtgt y = 2^[010] this is the same as y = [1 2 4 8 16 32 64 128 256 512 1024]gtgt plot(xy) to get a graphic representationgtgt semilogy(xy) to get logarithmic axesAs you can see the same figure is used for both plot commands The previous function is removed as soonas the next is displayed The command figure gives you an extra figure Repeat the previous commandsbut generate a new figure before plotting the second function so that you can see both functions in separatewindows You can also switch back to a figure using figure(n) where n is its number _Exercise 14Make a plot such that the coordinates (2 6) (25 18) (5 175) (42 125) and (212) are connected by aline _Exercise 15Plot the function y = sin(x) + x minus x cos(x) in two separate figures for the intervals 0 lt x lt 30 andminus100 lt x lt 100 _32 Several functions in one figureWhen more than one function is plotted in one figure it might be useful to use different markers and colors184-188197-201Table 4 shows a few possibilities help plot shows allThere are different ways to get more than one function into a figure The first one is with the command holdon After this command all functions will be plotted in the same figure until the command hold off is usedAn examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt plot (x1 y1 rsquordrsquo)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)17gtgt hold ongtgt plot (x2 y2 rsquoy-rsquo)gtgt plot (x1y1rsquok-rsquo)gtgt hold offA second method to display more than one function in one figure is to plot several functions at the same timeThe next commands will have the same results as the commands in the previous examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt plot (x1 y1rsquordrsquo x2 y2 rsquoy-rsquo x1 y1 rsquok-rsquo)It is also possible to get more than one figure in one figure window With the command subplot the windowcan be horizontally and vertically divided into any number of subfiguresgtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt subplot(131) plot (x1 y1rsquordrsquo)gtgt subplot(132) plot (x2 y2 rsquoy-rsquo)gtgt subplot(133) plot (x1 y1 rsquok-rsquo)optional

33 Other 2D plotting featuresIn the introduction of this chapter some commands similar to plot loglog semilogx and semilogy were201-211 mentioned There are however more ways to display dataExercise 16To get an impression of other visualizations type the following commands and describe the result (note thatthe command figure creates a new figure window)gtgt figure bar plot of a bell shaped curvegtgt x = -290229gtgt bar (x exp (-xx))gtgt figure stairstep plot of a sine wavegtgt x = 002510gtgt stairs (x sin (x))gtgt figure errorbar plotgtgt x = -2012gtgt y = erf (x) error function check help if you are interestedgtgt e = rand (size (x)) 10gtgt errorbar (x y e)

_end optional

34 PrintingBefore printing a figure you made you might want to add some information such as a title or change the189-196 lay-out a little Table 5 shows some of the commands that can be usedExercise 17Plot the functions y1 = sin(4x) y2 = x cos(x) y3 = (x + 1)minus1px for x = 0 025 10 and a single point(x y) = (4 5) in one figure with different colors and styles Make a legend containing the three functionsMake labels for both axes and a title Add a text to the single point saying single point Change the minimumand maximum values of the axes such that function y3 can be looked at in more detail _When the displayed figure is to your liking you can print it to paper The easiest way to do this is to click onFile in the menu-bar and to choose Print If in the print window you click OK your figure will be printed onthe printer indicated in the print window18Command Resultgrid onoff adds a grid to the plot at the tick marks or removes itaxis([xmin xmax ymin ymax]) sets the minimum and maximum values of the axesbox offon removes the axes box or shows itxlabel(rsquotextrsquo) plots the label text on the x axisylabel(rsquotextrsquo) plots the label text on the y axistitle(rsquotextrsquo) plots a title above the graphtext(xyrsquotextrsquo) adds text at the point (xy)gtext(rsquotextrsquo) adds text at a manually (with a mouse) indicated pointlegend(rsquofun1rsquorsquofun2rsquo) plots a legend box (move it with your mouse) to name your functionslegend off deletes the legend boxTable 5 Plot-manipulationsThere is also a print command which can be used to send a figure to a printer or output it to a file Youcan optionally specify a print device (ie an output format such as tiff or postscript) and options that controlvarious characteristics of the printed file (ie which Figure to print etc) You can also print to a file if youspecify the file name If you do not provide an extension print adds one Since they are many parametersthey will not be explained here (check help print to learn more) Instead try to understand the examplesgtgt print -dwinc print the current Figure to the current printer in colorgtgt print -f1 -deps myfileeps print Figure no1 to the file myfileeps in blackgtgt print -f1 -depsc myfileceps print Figure no1 to the file myfilecoleps in colorgtgt print -dtiff myfile1tiff print the current Figure to the file myfile1tiffgtgt print -dpsc myfile1cps print the current Figure to the file myfile1ps in colorgtgt print -f2 -djpeg myfile2 print Figure no2 to the file myfile2jpgExercise 18Exercise with printing (especially to a file) the figure from Exercise 16 _

4 Curve fitting and interpolationThere are two ways to describe data with an analytical function- curve fitting or regression finding a smooth curve that best fits (approximates) the data accordingto a criterion (eg best least square fit) The curve does not have to go through any of the data points- interpolation the data are assumed to be correct desired in a way to describe what happens betweenthe data points In other words given a finite set of points the goal of interpolation is to find a functionfrom a given class of functions (eg polynomials) which passes through the specified pointsThe figure below illustrates the difference between regression (curve fitting) and interpolationminus5 0 5minus6minus4minus20246810fiting a 3rd order polynomialinterpolation

41 Curve fittingMatlab interprets the best fit of a curve by the lsquoleast squares curve fittingrsquo The curve used is restricted153-15619to polynomials With the command polyfit any polynomial can be fitted to the data polyfit (x y n)finds the coefficients of a polynomial of degree n that fits the data (finds the linear relation between x and y)Letrsquos start with finding a linear regression of some datagtgt x = 010gtgt y = [-10 24 102 158 284 276 299 405 483 522 751]gtgt p = polyfit (x y 1) find the fitting polynomial of order 1p = 06772 -03914

The output of polyfit is a row vector of the polynomial coefficients the solution of this example is thereforey = 06772x minus 03914Exercise 19Execute the above example Plot the data and the fitted curve in a figure Determine the 2nd and 9th orderpolynomial of these data as well and display the solution in a figureHint x1 = linspace (xmin xmax n) results in a vector with n element evenly distributed from xmintill xmax z = polyval (p x1) calculates the values of the polynomial for every element of x1 _Exercise 20Define x and y as followsgtgt x = -55gtgt y = 02x^3 - x + 2 a 3rd order polynomialgtgt y = y + randn(111) add some noise to yDetermine the 3rd order polynomial fitting y (note that because of added noise the coefficients are differentthat originally chosen) Try some other polynomials as well Plot the results in a figure _42 InterpolationThe simplest way to examine an interpolation is by displaying the function plots with the command plot157-161 The neighboring data points are connected with straight lines This is called a linear interpolation Whenmore data-points are taken into account the effect of interpolation becomes less visible Analyzegtgt x1 = linspace(0 2pi2)gtgt x2 = linspace(0 2pi4)gtgt x3 = linspace(0 2pi16)gtgt x4 = linspace(0 2pi256)gtgt plot(x1sin(x1)x2sin(x2)x3sin(x3)x4sin(x4))gtgt legend(rsquo2 pointsrsquorsquo4 pointsrsquorsquo16 pointsrsquorsquo256 pointsrsquo)

5 Numerical analysisNumerical analysis can be used whenever it is impossible or very difficult to determine the analytical solutionMatlab can be used to find for example the minimum maximum or integral of a certain function51 Evaluation of a functionAs said before the command plot plots a function by connecting defined data points Sometimes however a168-173 function is constant and not very interesting over some range and then acts unexpectedly wildly over anotherWith plot this function might be misinterpreted The command fplot is then useful An examplegtgt x = 0pi82pigtgt y = sin (8x)gtgt plot (x y rsquobrsquo)gtgt hold ongtgt fplot (rsquosin (8z)rsquo [0 2pi] rsquorrsquo)gtgt title (rsquosin (8z)rsquo)gtgt hold off20Command Resultfplot (rsquofunrsquo [min x max x]) plots the function fun for min x till max xfmin (rsquofunrsquo min x max x) gives the x-value of the miminum of thefunction fun between min x and max xfzero (rsquofunrsquo x0) gives the x-value for which the functionfun is zero in the neighborhood of x0Table 6 Evaluation of a functionExecution of these commands results in a figure with an almost straight blue line and a red sine fplot canalso be used to plot a defined functiongtgt f = rsquosin (8z)rsquogtgt fplot (f [0 2pi] rsquorrsquo)gtgt title (f)Other useful commands for a detailed study of a range of a function are listed in Table 6Exercise 21The command fmax does not exist Use one or more of the commands from Table 6 to determine the maximumof the function x cos(x) for 10 lt x lt 15 _52 Integration and differentiationThe integral- or the surface underneath a 2D function- can be determined with the command trapz trapz173-182 does this by measuring the surface between the x-axis and the -by a straight line connected- data points Theaccuracy of this method depends on the distance between the data pointsgtgt x = 00510 y = 05 sqrt (x) + x sin (x) area1 = trapz (x y)

area1 =181655gtgt x = 000510 y = 05 sqrt (x) + x sin (x) area2 = trapz (x y)area2 =183846Differentiation is done by determining the slope in each data point Numerically this is done by first fitting apolynomial followed by differentiating this functiongtgt x = 010gtgt y = [-10 24 102 -158 284 276 775 35 483 522 751]gtgt p = polyfit (x y 5)p = 00026 -00554 03634 -06888 02747 00877gtgt dp = polyder (p)dp = 00132 -02216 10903 -13776 02747gtgt x1 = linspace (0 10 200)gtgt z = polyval (p x1)gtgt dz = polyval (dp x1)gtgt plot (x y rsquog-rsquo x1 z rsquobrsquo x1 dz rsquorrsquo)gtgt legend (rsquodata pointsrsquo rsquocurve fitrsquo rsquoderivativersquo)Exercise 22Determine the integral and derivative of the 4th polynomial fitted through (xy) with x = [4 5 6 7 8 9 1011 12 13] y = [1284 1200 724 -096 -1116 -2096 -2700 -2496 -956 2544] _

6 Control flowAs you know it is possible to execute more than one command at the same time (see section 11) Theseparate commands should then be divided by commarsquos (to display the output) or by semicolons (to suppress21output display) Control flow loops increase the number of possibilities A control flow structure is a block ofcommands that allows conditional code execution and making loops61 Logical and relational operatorsTo use control flow commands it is necessary to perform operations that result in logical values TRUE or88-91 FALSE In Matlab the result of a logical operation is 1 if it is true and 0 if it is false Table 7 shows therelational and logical operations2 Another way to get to know more about them is to type help relop Therelational operators lt lt= gt gt= == and ~= can be used to compare two arrays of the same size or anarray to a scalar The logical operators amp | and ~ allow for the logical combination or negation of relationaloperators In addition three functions are also available xor any and all (use help to find out more)Important The logical amp and | have the equal precedence in Matlab which means that those operatorsassociate from left to right A common situation isgtgt b = 10gtgt 1 | b gt 0 amp 0ans =0gtgt (1 | b gt 0) amp 0 this indicates the same as aboveans =0gtgt 1 | (b gt 0 amp 0)ans =1This shows that you should always use brackets to indicate in which way the operators should be evaluatedCommand Resulta = (b gt c) a is 1 if b is larger than c Similar are lt gt= and lt=a = (b == c) a is 1 if b is equal to ca = (b ~= c) a is 1 if b is not equal ca = ~b logical complement a is 1 if b is 0a = (b amp c) logical AND a is 1 if b = TRUE AND c = TRUEa = (b | c) logical OR a is 1 if b = TRUE OR c = TRUETable 7 Relational and logical operationsExercise 23Predict and check the result of each of the operations of Table 7 for b = 0 and c = -1 _Exercise 24Define two vectors with seven elements (randn(17)) and perform all logical operations including xor anyand all _Exercise 25While doing logical operations between a vector and a scalar each element of the vector is compared to thescalar Predict and check the result of each logical operator for the vector b = [2 31 -40 0] and the scalarc = 0 _Before moving on check whether you now understand the following relations

gtgt a = randperm(10) a random permutation of the numbers from 1 to 10gtgt b = 110gtgt b - (a lt= 7) subtracts from b a 0-1 vector taking 1 for a lt= 7 and 0 otherwisegtgt (a gt= 2) amp (a lt 4) returns ones at positions where 2 lt= a lt 4gtgt ~(b gt 4) returns ones at positions where b lt= 4gtgt (a == b) | b == 3 returns ones at positions where a is equal to b or b is equal to 3gtgt any (a gt 5) returns 1 when ANY of the a elements are larger than 5gtgt any (b lt 5 amp a gt 8) returns 1 when there in the evaluated expressiongtgt (b lt 5 amp a gt 8) appears at least one 1gtgt all (b gt 2) returns 1 when ALL b elements are larger than 22rdquoequal tordquo in the table on page 88 of rdquoThe Student Edition of Matlabrdquo must be rdquo==rdquo instead of rdquo=rdquo2262 Conditional code executionSelection control structures if-blocks are used to decide which instruction to execute next depending whether117-119 expression is TRUE or not The general description is given below In the examples below the command dispis frequently used This command displays on the screen the text between the quotesbull if endSyntaxif logical_expressionstatement1statement2endExampleif (a gt 0)b = adisp (rsquoa is positiversquo)endbull if else endSyntaxif logical_expressionblock of statementsevaluated if TRUEelseblock of statementsevaluated if FALSEendExampleif (temperature gt 100)disp (rsquoAbove boilingrsquo)toohigh = 1elsedisp (rsquoTemperature is OKrsquo)toohigh = 0endbull if elseif else endSyntaxif logical_expression1block of statements evaluatedif logical_expression1 is TRUEelseif logical_expression2block of statements evaluatedif logical_expression2 is TRUEelseblock of statements evaluatedif no other expression is TRUEendExampleif (height gt 190)disp (rsquovery tallrsquo)elseif (height gt 170)disp (rsquotallrsquo)elseif (height lt 150)disp (rsquosmallrsquo)

elsedisp (rsquoaveragersquo)endRemark To do the exercises below a script m-file will be useful It is an external file that contains asequence of Matlab commands What you need to do is to open an editor enter all commands needed forthe solution of a task save it with the extension rsquomrsquo (eg mytaskm) and then run it from the CommandWindow by typing mytask To open the Matlab editor go to the File menu-bar choose the Open optionand then m-file A new window will appear where you can write your scripts and save them on the disk Allcommands in the script will be executed in Matlab You will learn more on script m-files in section 91Important m-script file must be saved in one of the directories in Matlabrsquos pathAn example A script shortm can be created from the two lines given below and run by calling shortx = 0054plot (x sin(x) rsquo-rsquo)Exercise 26Create a script that asks for a number N and computes the drag coefficient C depending on the Reynoldrsquos23number N (make use of the if elseif construction) The command input might be useful here(read pages 32-33 from rdquoThe Student Edition of Matlabrdquoor use help)C =8gtgtgtltgtgtgt0 N _ 024N N 2 (0 01]24N (1 + 014N07) N 2 (01 1e3]043 N 2 (1e3 5e5]019 minus 8e4N N gt 5e5Check whether your script works correctly Compute the drag coefficient for eg N = -3e3 001 56 1e3 3e6(remember that eg 3e3 is a Matlab notation of 3 _ 103) _Exercise 27Write a script that asks for an integer and checks whether it can be divided by 2 or 3 Consider all possibilitiessuch as divisible by both 2 and 3 divisible by 2 and not by 3 etc (use the command rem) _Another selection structure is switch which switches between several cases depending on an expression which119-120 is either a scalar or a stringSyntaxswitch expressioncase choice1block of commands1case choice2a choice2bblock of commands2otherwiseblock of commandsendExamplemethod = 2switch methodcase 12disp(rsquoMethod is linearrsquo)case 3disp(rsquoMethod is cubicrsquo)case 4disp(rsquoMethod is nearestrsquo)otherwisedisp(rsquoUnknown methodrsquo)endThe statements following the first case where the expression matches the choice are executed Thisconstruction can be very handy to avoid long if elseif else end constructions Theexpression can be a scalar or a string A scalar expression matches a choice if expression == choice Astring expression matches a choice if strcmp(expression choice) returns 1 (is true) (strcmp is a commandcomparing two strings)Important Note that the switch-construction only allows the execution of one group of commandsExercise 28Assume that the months are represented by numbers from 1 to 12 Write a script that asks you to provide a

month and returns the number of days in that particular month Alternatively write a script that asks youto provide a month name (eg rsquoJunersquo) instead of a number Use the switch-construction _63 LoopsIteration control structures loops are used to repeat a block of statements until some condition is met Two114-117 types of loops existbull the for loop that repeats a group of statements a fixed number of timesSyntaxfor index = firststeplastblock of statementsendExamplesumx = 0for i=1length(x)sumx = sumx + x(i)end24You can specify any step including a negative value The index of the for-loop can be also a vectorSee some examples of possible variationsExample 1for i=12nendExample 2for i=n-13endExample 3for x=0054disp(x^2)endExample 4for x=[25 9 81]disp(sqrt(x))endbull while loop which evaluates a group of commands as long as expression is TRUESyntaxwhile expressionstatement1statement2statement3endExampleN = 100iter = 1msum = 0while iter lt= Nmsum = msum + iteriter = iter + 1endExercise 29Given the vectors x and y write a script computing the a matrix whose elements should be created accordingto a formula given below (make use of the length command to check the number of elements in both vectors)- aij = yixj (make sure that a division by zero will not occur)- bij = xi _ yj

- cij = 1 max (xi yj)_Exercise 30Determine the sum of the first 50 squared numbers with a control loop _Exercise 31Write a script to find the largest value n such that the sum p13 + p23 + + pn3 is less than 1000 _optionalExercise 32Write a script that transposes a matrix A Check its correctness with the Matlab operation Arsquo _Exercise 33

Write a script that asks for a temperature in degrees Celsius tc and computes the equivalent temperature indegrees Fahrenheit tf (use the formula tf = 95 _ tc + 32) The script should keep running until no numberis provided to convert The functions input and isempty (use help to learn more) should be useful here _end optional

64 Evaluation of logical and relational expressions in the control flow structuresThe relational and logical expressions may become more complicated It is not difficult to operate on them ifyou understand how they are evaluated To explain more details let us consider the following exampleif (~isempty(data)) amp (max(data) lt 5)endThis construction of the if-block is necessary to avoid comparison if data happens to be an empty matrix Insuch a case you cannot evaluate any expression and Matlab gives an error The amp operator returns 1 only ifboth expressions ~isempty (data) and max(data) lt 5 are true and 0 otherwise When data is an emptymatrix the next expression is not evaluated since the whole amp-expression is already known to be false Thesecond expression is checked only if data is a non-empty matrix Remember to put logical expression unitsbetween brackets to avoid wrong evaluations25Important The fact that computers make use of floating-point arithmetic means that often you should becareful when comparing two floating-point numbers just byif (x == y)end(Of course such a construction is allowed eg when you know that x and y represent integers) Instead of theabove construction you may try using thisif (abs (x - y) lt tolerance) eg tolerance = 1e-10endExercise 34Consider the following examplemax_iter = 50tolerance = 1e-4iter = 0xold = 01x = 1while (abs (x - xold) gt tolerance) amp (iter lt max_iter)xold = xx = cos(xold)iter = iter + 1endThis short program tries to solve the equation cos(x) = x (x is the solution found) Make the script solve cosfrom the presented code Note that the while-loop is repeated as long as both conditions are true If eitherthe condition (|x - xold| lt= tolerance) or (iter gt= max iter) is fulfilled then the loop is quitted Runthe script solve cos for different tolerance parameters eg 1e-3 1e-6 1e-8 1e-10 etc Use format long tocheck more precisely how much the found x is really different from cos(x) For each tolerance value checkthe number of performed iterations (iter value) _Exercise 35Create the script solve cos2 which is equal to the one given replacing the while-loop condition bywhile (abs (x - xold) gt tolerance) | (iter lt max_iter)Try to understand the difference and confirm your expectations by running solve cos2 What happens toiter _optional

65 Numerical analysis and the control flow structuresTake a look at the problem of a Taylor expansion The series will be determined numerically until the additionalterms are smaller than a defined precision Look at the Taylor expansion of 11minusx = 1 + x + x2 + withx = 042s = 0 x = 1 s = 0 x = 1x0 = 042 x0 = 042while (x gt 1e-6) or while (x gt (1e-6)s)s = s + x s = s + xx = x x0 x = x x0end endThe approximation of 11minusx is returned in s (first letter of sum) In the first case (on the left) the iteration

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 7: Introduction to Programming Using Matlab

ab a^bpx sqrt(x) or x^05_ pie exp(1)i i4 middot 103 4e3 or 410^33 minus 4i 3 - 4i or 3 - 4jsin x arctan x sin(x) atan(x) ex exp(x)ln x log(x)log x log10(x)|x| abs(x)Table 1 Translation of mathematical notation to Matlab commandsbull Matlab is case sensitive There is a difference between capital and normal letters for example a iswritten as a in Matlab A will result then in an errorbull All text after a percent sign until the end of a line is treated as a comment Enter eg the followinggtgt sin(314159) this is an approximation of sin(pi)You will notice that some examples in this text are followed by comments They are meant for you andyou should skip them while typing those examplesbull Previous commands can be fetched back with the -key The command can also be changed the and -keys may be used to move around in a line and edit itKeep in mind that Matlab executes the command immediately it might be useful to have an idea of theexpected outcome12 help-facilitiesMatlab provides assistance through extensive online help The help command is the simplest way to get349-359 help that is if you know the topic or command on which you want help For examplegtgt help elfungives information on the elementary math functions of Matlab The command help displays a list of allpossible topics The topic you want help on must be exact and spelled correctly The commando lookfor ismore useful if you do not know the exact name of the command or topic For examplegtgt lookfor inversedisplays all commands for which the word inverse is included in its help-text This command results in a list ofcommands with a short description Besides the help and lookfor commands there is also a separate mousedriven help The helpwin command opens a new window on screen which can be browsed in an interactiveway To learn more read pages 353-354 from rdquoThe Student Edition of Matlabrdquobook13 Interrupting a command or programSometimes you might spot an error in your command or program Due to this error it can happen that thecommand or program does not stop Pressing Ctrl-C forces Matlab to stop the process After this theMatlab-prompt (gtgt) re-appears This may take a while though514 PathIn Matlab commands or programs are contained in m-files which are just plain text files and have an37-39 extension rsquomrsquo The m-file must be located in one of the directories which Matlab automatically searchesThe list of these directories can be listed by the command path One of the directories that is always takeninto account is the current working directory which can be identified by the command pwd Use path addpathand rmpath functions to modify the path Here is an examplegtgt pathcmatlabcmatlabtoolboxmatlabgeneralcmatlabtoolboxmatlabopsgtgt addpath hpersonal assume that this is your directorygtgt pathhpersonalcmatlabcmatlabtoolboxmatlabgeneralcmatlabtoolboxmatlabopsIt is also possible to access the path browser from the File menu-bar instead15 Workspace issuesIf you work in the Command Window Matlab memorizes all commands that you entered (as you alreadyknow - to recall previous commands the -key is useful) and all variables that you created This can be6

2425verified with the commands who which gives a list of variables present in the workspace and whos whichincludes information on name number of allocated bytes and class of the variables For example assuming thatyou performed all commands given in the beginning after typing who you should get the following informationgtgt whoYour variables area ans b xThe command clear ltnamegt deletes the variable ltnamegt from the Matlab workspace clear or clear allremoves all variables This is useful when starting a new exercise For examplegtgt clear a xgtgt whoYour variables areans b16 Saving and loading dataThe easiest way to save or load Matlab variables is by using (clicking) the File menu-bar and then the Save26 Workspace as and Load Workspace items Also Matlab commands exist which allow you to saveand load data from filesThe command save allows for saving your workspace variables either into a binary file or an ASCII file (checkPreliminaries on binary and ASCII files) Binary files automatically get the rsquomatrsquo extension which is nottrue for ASCII files However it is recommended to add a rsquotxtrsquo or dat extensionExercise 1Learn how to use the save command by exercisinggtgt s1 = sin(pi4) s2 = sin(pi2)gtgt c1 = cos(pi4) c2 = cos(pi2)gtgt str = rsquohello worldrsquo this is a string example you will learn about strings latergtgt save saves all variables in binary format to the file matlabmatgtgt save data saves all variables in binary format to the file datamat6gtgt save numdata s1 c1 saves numeric variables s1 and c1 to the file numdatamatgtgt save strdata str saves a string variable str to the file strdatamatgtgtgtgt save allsin s saves all variables that match the pattern to allsinmatgtgt save allcosdat c -ascii saves c1c2 in 8-digit ascii format to allcosdat_The load command allows for loading variables into the workspace It uses the same syntax as saveExercise 2Assuming that you have done the previous exercise try to load variables from the created filesImportant before each load command clear the workspace and after loading check which variables arepresent in the workspace (using who)gtgt load loads all variables from the file matlabmatgtgt load data s1 c1 loads only specified variables from the file datamatgtgt load strdata loads all variables from the file strdatamatIt is also possible to read ASCII files that contain rows of space separated values Such a file may containcomments that begin with a percent character The resulting data is placed into a variable with the samename as the ASCII file (without the extension) Check for examplegtgt load allcosdat loads data from the file allcosdat into variable allcosgtgt who lists variables present in the workspace now_

2 Mathematics with numbers vectors and matricesThe basic element of Matlab is a matrix (or an array) Special cases arebull a 1 times 1-matrix a scalar or a single numberbull a matrix existing only of one row or one column a vector21 Single numbersYou have already got some experience with Matlab and you know that it can be used as a calculator To do4-614-1727that you can for example simply typegtgt 31256The result will beans =55714By default Matlab displays only 5 digits The command format long increases this number to 15 format

short reduces it to 5 again For examplegtgt format longgtgt 31256ans =557142857142857Exercise 3Define the format Matlab such that empty lines are suppressed and the output is given with 5 digitsCalculategtgt pigtgt sin(pi)Note that the answer is not exactly 0 _Use the command format to put Matlab in its standard-format ie short and loose7intermezzo

22 An introduction to floating-point numbersIn a computer numbers can be represented only in a discrete form It means that numbers are stored286 within a limited range and with a finite precision Integers can be represented exactly with the base of 2(read Preliminaries on bits and the binary system) The typical size of an integer is 16 bits so the largestpositive integer which can be stored is 216 = 65536 If negative integers are permitted then 16 bits allow forrepresenting integers between minus32768 and 32767 Within this range operations defined on the set of integerscan be performed exactlyHowever this is not valid for other real numbers In practice computers are integer machines and are capableof representing real numbers only by using complicated codes The most popular code is the floating pointstandard The term floating point is derived from the fact that there is no fixed number of digits before andafter the decimal point meaning that the decimal point can float Note that most floating-point numbers thata computer can represent are just approximations Therefore care should be taken that these approximationslead to reasonable results If a programmer is not careful small discrepancies in the approximations can causemeaningless results Note the difference between eg the integer arithmetic and floating-point arithmeticInteger arithmetic Floating-point arithmetic2 + 4 = 6 187 = 257143 4 = 12 25714 7 = 1799982511 = 2 100003 = 33333e+03When describing floating-point numbers precision refers to the number of bits used for the fractional partThe larger the precision the more exact fractional quantities can be represented Floating-point numbers areoften classified as single precision or double precision A double-precision number uses twice as many bits asa single-precision value so it can represent fractional values much better However the precision itself is notdouble The extra bits are also used to increase the range of magnitudes that can be representedMatlab relies on a computerrsquos floating point arithmetic You could have already noticed that in the last408-410 exercise since the value of sin(_) was almost zero and not completely zero It came from the fact that boththe value of _ is represented with a finite precision and the sin function is also approximatedThe fundamental type in Matlab is double which stands for a representation with a double precision It uses64 bits The single precision obtained by using the single type offers 32 bits Since most numeric operationsrequire high accuracy the double type is used by defaultThe exact machine precision might be defined as the smallest positive number _ that added to 1 does notchange the result so 1 + _ = 1 in floating-point arithmetic this value is larger than zero (in exact arithmeticof course _ = 0 holds) Matlab machine precision is stored in the built-in variable eps _ 22204e-16 Thismeans that the relative accuracy of individual arithmetic operations is about 16 digitsend intermezzo

23 Assignments and variablesWorking with complex numbers is easily done with MatlabExercise 4Choose two complex numbers for example -3 + 2i and 5 - 7i Try to add subtract multiply and dividethese two numbers _During this exercise the complex numbers had to be typed four times To reduce this assign each number to4-610-12a variable For the previous exercise this results ingtgt z = -3 + 2igtgt w = 5 - 7igtgt y1 = z + w y2 = z - w y3 = z w y4 = z w y5 = w zFormally there is no need to declare (ie define the name size and the type of) a new variable in Matlab Avariable is simply created by an assignment (the way it has been done above) Each newly created numerical

variable is always of the double type You can change this type by converting it into eg the single type 11a variable a is converted into a different type by performing eg a = single(a) a = int16(a) etc8In some cases when huge matrices should be handled and precision is not very important this might be a wayto proceed Also when only integers are taken into consideration it might be useful to convert the doublerepresentations into eg int16 or int321 integer types Since most computations should be performed with ahigh accuracy Matlab automatically chooses the double type It means that real numbers are approximatedwith the highest possible precision However it is important to emphasize that integer numbers are alwaysrepresented exactly no matter which numeric type is usedBear in mind that undefined values cannot be assigned to a variable So the following is not possiblegtgt clear x to make sure that x does not existgtgt fun = x^2 + 4 sin (x)It becomes possible bygtgt x = pi 3 fun = x^2 + 4 sin (x)Exercise 5Predict the result ofx = pi 3 x = x - 1 x = x + 5 x = abs(x) xCheck your prediction by performing these commands in Matlab _Exercise 6Here are some examples of different types of Matlab variables You do not need to understand them all nowsince you will learn more about them during the course Create them manually in Matlabgtgt this_is_my_very_simple_variable_today = 5 a number check what happens since thegtgt name is very long (gt 31 characters)gtgt 2t = 8 what is the problem with this commandgtgt this_is_a_matrix = [1 2 3 4 5 6] a matrixgtgt c = rsquoErsquo a charactergtgt str = rsquoHello worldrsquo a stringgtgt m = [rsquoJrsquorsquoorsquorsquohrsquorsquonrsquo] try to guess what it isCheck the types by using the command whos Use clear ltnamegt to remove a variable from the workspace _Exercise 7In addition to creating variables by assigning values to them a few other ways exist For instance there is anumber of built-in variables eg ans pi eps i inf or nan Find out what value is assigned to each of these74584 built-in variables _24 VectorsRow vectors are lists of numbers separated either by commas or by spaces They are examples of simple arrays41-49 The number of entries is known as the length of the vector (the command length exists as well) Their entitiesare referred to as elements or components The entries must be enclosed in [ ]gtgt v = [-1 sin(3) 7]v =-10000 01411 70000gtgt length(v)ans =3A number of operations can be done on vectors A vector can be multiplied by a scalar or addedsubtractedtofrom another vector with the same length or a number can be addedsubtracted tofrom a vector Allthese operations are carried out element-by-element Vectors can be also built from the already existing onesgtgt v = [-1 2 7] w = [2 3 4]gtgt z = v + w an element-by-element sumz =1 5 119gtgt v3 = v + 2 add 2 to all elements of vector v3v3 =1 4 9gtgt t = [2v -w]ans =-2 4 14 -2 -3 -4Also a particular value can be changed or displayedgtgt v(2) = -1 w(2) change the 2nd value of v display the 2nd value of wv =-1 -1 7ans =

3A colon notation is an important shortcut used when producing row vectors (see Table 3 and help colon)gtgt 25ans =2 3 4 5gtgt -23ans =-2 -1 0 1 2 3In general firststeplast produces a vector of entities with the value first incrementing by the stepuntil it reaches lastgtgt 020524ans =02000 07000 12000 17000 22000gtgt -3310ans =-3 0 3 6 9gtgt 15-05-05 negative step is also possibleans =15000 10000 05000 0 -05000Parts of vectors can be extracted by using a colon notationgtgt r = [-126 2 3 -2] -126 =gt -1 1 3 5r =-1 1 3 5 2 3 -2gtgt r(36) get elements of r which are on the positions from 3 to 6ans =3 5 2 3gtgt r(125) get elements of r which are on the positions from 1 to 5 taken with the step of 2ans =-1 3 2gtgt r(5-12) what will you get hereTo create column vectors you should separate entries by a semicolon () or by new linesgtgt f = [-1 3 5]f =-135The same operations as on row vectors can be done on column vectors However you cannot for exampleadd a column vector to a row vector To do that you need an operation called transposing which converts acolumn vector into a row vector and vice versa10gtgt f = [-1 3 5] a column vectorgtgt frsquo frsquo is a row vectorans =-1 3 5gtgt v = [-1 2 7] a row vectorgtgt f + v you cannot add a column vector f to a row vector v Error using ==gt +Matrix dimensions must agreegtgt frsquo + vans =-2 5 12gtgt f + vrsquoans =-2512If x is a complex vector than xrsquo gives the conjugate transpose of x eggtgt x = [1+2i -1+i]x =10000 + 20000i -10000 + 10000igtgt xrsquo this is the conjugate transposeans =10000 - 20000i-10000 - 10000i

gtgt xrsquo this is the rsquonormalrsquo transposeans =10000 + 20000i-10000 + 10000iExercise 8Exercise to become acquainted with operating on row and column vectors Enter all examples given in thissection and make new variations yourself Exercise with the colon notation approach as well _25 MatricesAn ntimesk matrix is a rectangular array of numbers having n rows and k columns Defining a matrix in Matlabis similar to defining a vector The generalization is straightforward if you know that a matrix consists of row49-6175-86vectors (or column vectors) Commas or spaces are used to separate elements in a row and semicolons areused to separate individual rows For example the matrix A =01 2 34 5 67 8 91Ais defined asgtgt A = [1 2 3 4 5 6 7 8 9] row by row inputA =1 2 34 5 67 8 9Another examples are for instancegtgt A2 = [14 -125]A2 =1 2 3 4-1 1 3 5gtgt A3 = [1 3-4 7]A3 =1 3-4 711Command ResultA(ij) Aij

A(j) j-th column of AA(i) i-th row of AA(klmn) (l minus k + 1) times (n minus m + 1) matrix with elements Aij with k _ i _ l m _ j _ nv(ij)rsquo rsquovector-partrsquo (vi vi+1 vj) of vector vTable 2 Manipulation of (groups of) matrix-elementsCommand Resultn = rank (A) n becomes the rank of matrix Ax = det (A) x becomes the determinant of matrix AC = size (A) C becomes a row-vector with 2 elements the number of rows and columns of Ax = trace (A) x becomes the trace (sum of diagonal elements) of matrix Ax = norm (v) x becomes the length of vector vC = A + B sum of two matricesC = A - B subtraction of two matricesC = A B multiplication of two matricesC = A B rdquoelement-by-elementrdquo multiplication (A and B are of equal size)C = A ^ k power of a matrix (k 2 Z can also be used for Aminus1)C = A ^ k rdquoelement-by-elementrdquo power of a matrixC = Arsquo the transposed of a matrix AT

C = A B rdquoelement-by-elementrdquo division (A and B are of equal size)U = A B finds the solution that minimizes the squared error in Ax minus BU = B A solution of XA = B analogous to the previous commandC = inv (A) C becomes the inverse of AC = null (A) C is an orthonormal basis for the null space of Aobtained from the singular value decompositionC = orth (A) C is an orthonormal basis for the range of AC = rref (A) C is the reduced row echelon form of AL = eig (A) L is a vector containing the -possibly complex- eigenvalues of a square matrix A[X D] = eig (A) produces a diagonal matrix D of eigenvalues and a full matrix X

whose columns are the corresponding eigenvectors of AS = svd (A) S is a vector containing the singular values of A[U S V] = svd (A) S is a diagonal matrix of the same dimension as Awith nonnegative diagonal elements in decreasing orderThe columns U and V are the accompanying singular vectorsx = linspace(a b n) generates a vector x of n equally spaced points between a and bx = logspace(a b n) generates a vector x starting at 10a and ended at 10b containing n valuesA = diag (v) gives a diagonal matrix with the elements v1 v2 vn on the diagonalA = eye (n) A is a n times n identity matrixA = zeros (n m) A is a n times m matrix with zeros (default m = n)A = rand (n m) A is a n times m matrix with elements uniformly distributed between 0 and 1A = randn (n m) ditto - with elements standard normal distributedv = max (A) v becomes a vector with the maximum value of the elements in each column of Aor v is the maximum of all elements if A is a vectorv = min (A) ditto - with minimumv = sum (A) ditto - with sumTable 3 Frequently used matrix operations and functions12Transposing a vector changes it from a row to a column or the other way around This idea can be extendedto a matrix where transposing interchanges rows with the corresponding columns as in the examplegtgt A2 A2rsquoA2 =1 2 3 4-1 1 3 5ans =1 -12 13 34 5gtgt size(A2) returns the size (dimensions) of a matrixans =2 4gtgt size(A2rsquo)ans =4 2There exists also some built-in matrices of size specified by the user (see Table 2) A few examples are givenbelowgtgt E = [] an empty matrix of 0-by-0 elementsE =[]gtgt I = eye(3) the identity matrixI =1 0 00 1 00 0 1gtgt B = rand(23) a matrix of random numbers you will get a different one00227 09101 0922200299 00640 03309gtgt O = ones(32)O =1 11 11 1gtgt r = [1 3 -2] R = diag(r) create a diagonal matrix with r on the diagonalR =1 0 00 3 00 0 -2gtgt v = linspace(124) a vector is also an example of a matrixv =10000 13333 16667 20000It is often needed to build a larger matrix from the smaller onesgtgt x = [4 -1] y = [-1 4]x =4

-1y =-1 4gtgt X = [x yrsquo] X consists of the columns x and yrsquoX =4 -1-1 4gtgt T = [ -1 3 4 4 5 6] t = 1313gtgt T2 = [T t] add to T a new row namely the row vector t getting T2T2 =-1 3 44 5 61 2 3gtgt G = [1 5 4 5 0 2] G is a matrix of the 3-by-2 size check size(G)gtgt T3 = [T2 G] T3 consists of T2 and new columns being the colums of GT3 = added at the end of T2-1 3 4 1 54 5 6 4 51 2 3 0 2gtgt [diag(56) ones(32)]ans =5 00 61 11 11 1A part can be extract from a matrix in a similar way as from a vector Each element in the matrix is indexedby a row and a column to which it belongs Mathematically the element from the i-th row and the j-thcolumn of the matrix A is denoted by Aij Matlab provides the A(ij) notationgtgt A = [13 46 79]A =1 2 34 5 67 8 9gtgt A(12) A(23) A(31)ans =2ans =6ans =7gtgt A(43) A is a 3-by-3 matrix Index exceeds matrix dimensionsgtgt A(23) = A(23) + 2A(11)A =1 2 34 5 87 8 9Having defined a matrix it is easy to extended it automatically For the matrix A it can be done eg asfollowsgtgt A(52) = 5 assign 5 to the position (52) the uninitializedA = elements become zeros1 2 34 5 87 8 90 0 00 5 0Different parts of the matrix A can be now extractedgtgt A(2) extract the 2nd column of Aans =25814

05gtgtgt A(34) extract the rows 3rd and 4th of Aans =7 8 90 0 0gtgt A(2312) extract a part of Aans =4 57 8If needed the other zero elements of the matrix A can be also defined by eggtgt A(4) = [1 2 3] assign vector [1 2 3] to the 4th row of Agtgt A(5[13]) = [4 5] a rsquoshortcutrsquo when assigning A(51) = 4 and A(53) = 5gtgt A how does the matrix A look like nowAs you have seen in the examples above it is possible to manipulate (groups of) matrix-elements Thecommands are shortly explained in Table 2Exercise 9Define the matrix A = [14 58 1 1 1 1] Predict and check the result ofgtgt B = A(3)gtgt C = A(1322)gtgt A(11) = 9gtgt A(2313) = [0 0 0 0 0 0]gtgt A(l212) = [l l 3 3]gtgt A = A(3314)_Exercise 10Define the matrices T=[ 3 4 1 8 -4 3] A = [diag(-123) T -4 4 1 2 1] Perform the followingoperations on the matrix Abull extract a vector consisting of the 2nd and 4th elements of the 3rd rowbull find the minimum of the 3rd columnbull find the maximum of the 2nd rowbull compute the sum of the 2nd columbull compute the mean of the 1st and 4th rowsbull extract the submatrix consisting of the 1st and 3rd rows and all columnsbull extract the submatrix consisting of the 1st and 2nd rows and the 3rd 4th and 5th columnsbull compute the total sum of the 1st and 2nd rowsbull add 3 to all elements of the 2nd and 3rd colums_Table 3 shows some frequently used matrix operations and functions A few examples are provided belowgtgt B = rand(23) a matrix of random numbers you will get a different oneB =09501 06068 0891302311 04860 07621gtgt B2 = [1 2 5 1 5 6]gtgt B + B2rsquo add two matrices why B2rsquo is needed instead of B2ans =19501 56068 5891322311 14860 67621gtgt S = ans4 divide all elements of the matrix ans by 4S =04875 14017 1472805578 03715 1690515gtgt C = [1 -1 4 7 0 -1]gtgt B C matrix multiplication is not defined for B and C Error using ==gt Inner matrix dimensions must agreegtgt B C but you can multiply element-by-elementans =09501 -06068 3565216180 0 -07621gtgt D = B Crsquo or you can make the multiplication legal Crsquo is now 3-by-2D =39085 5759627935 08559

gtgt D^3 this is equivalent to D D Dans =1992503 2041413990133 910548gtgt D^3 - 2 do for all elements raise to the power 3 and subtract 2ans =577069 1890638198005 -13731gtgtgtgt r = [1 3 -2]r B2 this is a legal operation r is a 1-by-3 matrix and B2 isans = 3-by-2 matrix B2 r is an illegal operation6 -7Remind that an n-by-k matrix A (having n rows and k columns) can be multiply by another matrix B onlyif B has k rows ie S is of the k-by-m size (m is arbitrary) As a result you get an n-by-m matrixA ˙B = C A 2 Rntimesk B 2 Rktimesm C 2 Rntimesm

RemarkYou can now compute the inner product between two vectors x and y xT y = Pi xi yi in a simple waygtgt f = [-1 3 5] a column vectorgtgt v = [-1 2 7] a column vectorgtgt frsquo v this is the inner productans =42gtgt f vrsquo be careful now a 3-by-1 matrix is multiplied by a 1-by-3gtgt matrix which results in a 3-by-3 matrix (the outer product)ans =1 -2 -7-3 6 21-5 10 35gtgt f v this is an element-by-element multiplication1635gtgt sum (f v) this is an another way to compute the inner productans =42Exercise 11Perform all operations from Table 3 using chosen matrices A and B vector v and scalars k a b n and m _Exercise 12Let A be a random 3 times 3 matrix and b a random 3 times 1 vector Given that Ax = b then x = Aminus1b Find x(there exist at least two possible commands to do this look at Table 3) _optionalThe concept of an empty matrix [] is also very useful in Matlab For instance a few columns or rows canbe removed from a matrix by assigning an empty matrix to it Try for example16Symbol Color Symbol Styley yellow dotted liner red o circlesg green - solid lineb blue - dashdotted lineTable 4 Plot colors and stylesgtgt C = [1 2 3 4 5 6 7 8 1 1 1 1]gtgt D = C D(2) = [] now a copy of C is in D remove the 2nd column of Dgtgt C ([13]) = [] remove the rows 1 and 3 from Cend optional

3 VisualizationMatlab can be used to visualize the results of an experiment Therefore you should define variables each ofthem containing all values of one parameter to plot31 Simple plotsWith the command plot a graphical display can be made plot(y) draws the points (1 y(1)) (2 y(2)) 184 (n y(n)) and connects the points with a straight line plot(xy) does the same for (x(1) y(1)) (x(2) y(2)) (x(n) y(n)) x and y have to be row- or column vectors of equal lengthThe commands loglog semilogx and semilogy are similar to plot except that they use logarithmic axesExercise 13Type the following commands after predicting the resultgtgt x = 0330

gtgt y = 2^[010] this is the same as y = [1 2 4 8 16 32 64 128 256 512 1024]gtgt plot(xy) to get a graphic representationgtgt semilogy(xy) to get logarithmic axesAs you can see the same figure is used for both plot commands The previous function is removed as soonas the next is displayed The command figure gives you an extra figure Repeat the previous commandsbut generate a new figure before plotting the second function so that you can see both functions in separatewindows You can also switch back to a figure using figure(n) where n is its number _Exercise 14Make a plot such that the coordinates (2 6) (25 18) (5 175) (42 125) and (212) are connected by aline _Exercise 15Plot the function y = sin(x) + x minus x cos(x) in two separate figures for the intervals 0 lt x lt 30 andminus100 lt x lt 100 _32 Several functions in one figureWhen more than one function is plotted in one figure it might be useful to use different markers and colors184-188197-201Table 4 shows a few possibilities help plot shows allThere are different ways to get more than one function into a figure The first one is with the command holdon After this command all functions will be plotted in the same figure until the command hold off is usedAn examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt plot (x1 y1 rsquordrsquo)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)17gtgt hold ongtgt plot (x2 y2 rsquoy-rsquo)gtgt plot (x1y1rsquok-rsquo)gtgt hold offA second method to display more than one function in one figure is to plot several functions at the same timeThe next commands will have the same results as the commands in the previous examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt plot (x1 y1rsquordrsquo x2 y2 rsquoy-rsquo x1 y1 rsquok-rsquo)It is also possible to get more than one figure in one figure window With the command subplot the windowcan be horizontally and vertically divided into any number of subfiguresgtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt subplot(131) plot (x1 y1rsquordrsquo)gtgt subplot(132) plot (x2 y2 rsquoy-rsquo)gtgt subplot(133) plot (x1 y1 rsquok-rsquo)optional

33 Other 2D plotting featuresIn the introduction of this chapter some commands similar to plot loglog semilogx and semilogy were201-211 mentioned There are however more ways to display dataExercise 16To get an impression of other visualizations type the following commands and describe the result (note thatthe command figure creates a new figure window)gtgt figure bar plot of a bell shaped curvegtgt x = -290229gtgt bar (x exp (-xx))gtgt figure stairstep plot of a sine wavegtgt x = 002510gtgt stairs (x sin (x))gtgt figure errorbar plotgtgt x = -2012gtgt y = erf (x) error function check help if you are interestedgtgt e = rand (size (x)) 10gtgt errorbar (x y e)

_end optional

34 PrintingBefore printing a figure you made you might want to add some information such as a title or change the189-196 lay-out a little Table 5 shows some of the commands that can be usedExercise 17Plot the functions y1 = sin(4x) y2 = x cos(x) y3 = (x + 1)minus1px for x = 0 025 10 and a single point(x y) = (4 5) in one figure with different colors and styles Make a legend containing the three functionsMake labels for both axes and a title Add a text to the single point saying single point Change the minimumand maximum values of the axes such that function y3 can be looked at in more detail _When the displayed figure is to your liking you can print it to paper The easiest way to do this is to click onFile in the menu-bar and to choose Print If in the print window you click OK your figure will be printed onthe printer indicated in the print window18Command Resultgrid onoff adds a grid to the plot at the tick marks or removes itaxis([xmin xmax ymin ymax]) sets the minimum and maximum values of the axesbox offon removes the axes box or shows itxlabel(rsquotextrsquo) plots the label text on the x axisylabel(rsquotextrsquo) plots the label text on the y axistitle(rsquotextrsquo) plots a title above the graphtext(xyrsquotextrsquo) adds text at the point (xy)gtext(rsquotextrsquo) adds text at a manually (with a mouse) indicated pointlegend(rsquofun1rsquorsquofun2rsquo) plots a legend box (move it with your mouse) to name your functionslegend off deletes the legend boxTable 5 Plot-manipulationsThere is also a print command which can be used to send a figure to a printer or output it to a file Youcan optionally specify a print device (ie an output format such as tiff or postscript) and options that controlvarious characteristics of the printed file (ie which Figure to print etc) You can also print to a file if youspecify the file name If you do not provide an extension print adds one Since they are many parametersthey will not be explained here (check help print to learn more) Instead try to understand the examplesgtgt print -dwinc print the current Figure to the current printer in colorgtgt print -f1 -deps myfileeps print Figure no1 to the file myfileeps in blackgtgt print -f1 -depsc myfileceps print Figure no1 to the file myfilecoleps in colorgtgt print -dtiff myfile1tiff print the current Figure to the file myfile1tiffgtgt print -dpsc myfile1cps print the current Figure to the file myfile1ps in colorgtgt print -f2 -djpeg myfile2 print Figure no2 to the file myfile2jpgExercise 18Exercise with printing (especially to a file) the figure from Exercise 16 _

4 Curve fitting and interpolationThere are two ways to describe data with an analytical function- curve fitting or regression finding a smooth curve that best fits (approximates) the data accordingto a criterion (eg best least square fit) The curve does not have to go through any of the data points- interpolation the data are assumed to be correct desired in a way to describe what happens betweenthe data points In other words given a finite set of points the goal of interpolation is to find a functionfrom a given class of functions (eg polynomials) which passes through the specified pointsThe figure below illustrates the difference between regression (curve fitting) and interpolationminus5 0 5minus6minus4minus20246810fiting a 3rd order polynomialinterpolation

41 Curve fittingMatlab interprets the best fit of a curve by the lsquoleast squares curve fittingrsquo The curve used is restricted153-15619to polynomials With the command polyfit any polynomial can be fitted to the data polyfit (x y n)finds the coefficients of a polynomial of degree n that fits the data (finds the linear relation between x and y)Letrsquos start with finding a linear regression of some datagtgt x = 010gtgt y = [-10 24 102 158 284 276 299 405 483 522 751]gtgt p = polyfit (x y 1) find the fitting polynomial of order 1p = 06772 -03914

The output of polyfit is a row vector of the polynomial coefficients the solution of this example is thereforey = 06772x minus 03914Exercise 19Execute the above example Plot the data and the fitted curve in a figure Determine the 2nd and 9th orderpolynomial of these data as well and display the solution in a figureHint x1 = linspace (xmin xmax n) results in a vector with n element evenly distributed from xmintill xmax z = polyval (p x1) calculates the values of the polynomial for every element of x1 _Exercise 20Define x and y as followsgtgt x = -55gtgt y = 02x^3 - x + 2 a 3rd order polynomialgtgt y = y + randn(111) add some noise to yDetermine the 3rd order polynomial fitting y (note that because of added noise the coefficients are differentthat originally chosen) Try some other polynomials as well Plot the results in a figure _42 InterpolationThe simplest way to examine an interpolation is by displaying the function plots with the command plot157-161 The neighboring data points are connected with straight lines This is called a linear interpolation Whenmore data-points are taken into account the effect of interpolation becomes less visible Analyzegtgt x1 = linspace(0 2pi2)gtgt x2 = linspace(0 2pi4)gtgt x3 = linspace(0 2pi16)gtgt x4 = linspace(0 2pi256)gtgt plot(x1sin(x1)x2sin(x2)x3sin(x3)x4sin(x4))gtgt legend(rsquo2 pointsrsquorsquo4 pointsrsquorsquo16 pointsrsquorsquo256 pointsrsquo)

5 Numerical analysisNumerical analysis can be used whenever it is impossible or very difficult to determine the analytical solutionMatlab can be used to find for example the minimum maximum or integral of a certain function51 Evaluation of a functionAs said before the command plot plots a function by connecting defined data points Sometimes however a168-173 function is constant and not very interesting over some range and then acts unexpectedly wildly over anotherWith plot this function might be misinterpreted The command fplot is then useful An examplegtgt x = 0pi82pigtgt y = sin (8x)gtgt plot (x y rsquobrsquo)gtgt hold ongtgt fplot (rsquosin (8z)rsquo [0 2pi] rsquorrsquo)gtgt title (rsquosin (8z)rsquo)gtgt hold off20Command Resultfplot (rsquofunrsquo [min x max x]) plots the function fun for min x till max xfmin (rsquofunrsquo min x max x) gives the x-value of the miminum of thefunction fun between min x and max xfzero (rsquofunrsquo x0) gives the x-value for which the functionfun is zero in the neighborhood of x0Table 6 Evaluation of a functionExecution of these commands results in a figure with an almost straight blue line and a red sine fplot canalso be used to plot a defined functiongtgt f = rsquosin (8z)rsquogtgt fplot (f [0 2pi] rsquorrsquo)gtgt title (f)Other useful commands for a detailed study of a range of a function are listed in Table 6Exercise 21The command fmax does not exist Use one or more of the commands from Table 6 to determine the maximumof the function x cos(x) for 10 lt x lt 15 _52 Integration and differentiationThe integral- or the surface underneath a 2D function- can be determined with the command trapz trapz173-182 does this by measuring the surface between the x-axis and the -by a straight line connected- data points Theaccuracy of this method depends on the distance between the data pointsgtgt x = 00510 y = 05 sqrt (x) + x sin (x) area1 = trapz (x y)

area1 =181655gtgt x = 000510 y = 05 sqrt (x) + x sin (x) area2 = trapz (x y)area2 =183846Differentiation is done by determining the slope in each data point Numerically this is done by first fitting apolynomial followed by differentiating this functiongtgt x = 010gtgt y = [-10 24 102 -158 284 276 775 35 483 522 751]gtgt p = polyfit (x y 5)p = 00026 -00554 03634 -06888 02747 00877gtgt dp = polyder (p)dp = 00132 -02216 10903 -13776 02747gtgt x1 = linspace (0 10 200)gtgt z = polyval (p x1)gtgt dz = polyval (dp x1)gtgt plot (x y rsquog-rsquo x1 z rsquobrsquo x1 dz rsquorrsquo)gtgt legend (rsquodata pointsrsquo rsquocurve fitrsquo rsquoderivativersquo)Exercise 22Determine the integral and derivative of the 4th polynomial fitted through (xy) with x = [4 5 6 7 8 9 1011 12 13] y = [1284 1200 724 -096 -1116 -2096 -2700 -2496 -956 2544] _

6 Control flowAs you know it is possible to execute more than one command at the same time (see section 11) Theseparate commands should then be divided by commarsquos (to display the output) or by semicolons (to suppress21output display) Control flow loops increase the number of possibilities A control flow structure is a block ofcommands that allows conditional code execution and making loops61 Logical and relational operatorsTo use control flow commands it is necessary to perform operations that result in logical values TRUE or88-91 FALSE In Matlab the result of a logical operation is 1 if it is true and 0 if it is false Table 7 shows therelational and logical operations2 Another way to get to know more about them is to type help relop Therelational operators lt lt= gt gt= == and ~= can be used to compare two arrays of the same size or anarray to a scalar The logical operators amp | and ~ allow for the logical combination or negation of relationaloperators In addition three functions are also available xor any and all (use help to find out more)Important The logical amp and | have the equal precedence in Matlab which means that those operatorsassociate from left to right A common situation isgtgt b = 10gtgt 1 | b gt 0 amp 0ans =0gtgt (1 | b gt 0) amp 0 this indicates the same as aboveans =0gtgt 1 | (b gt 0 amp 0)ans =1This shows that you should always use brackets to indicate in which way the operators should be evaluatedCommand Resulta = (b gt c) a is 1 if b is larger than c Similar are lt gt= and lt=a = (b == c) a is 1 if b is equal to ca = (b ~= c) a is 1 if b is not equal ca = ~b logical complement a is 1 if b is 0a = (b amp c) logical AND a is 1 if b = TRUE AND c = TRUEa = (b | c) logical OR a is 1 if b = TRUE OR c = TRUETable 7 Relational and logical operationsExercise 23Predict and check the result of each of the operations of Table 7 for b = 0 and c = -1 _Exercise 24Define two vectors with seven elements (randn(17)) and perform all logical operations including xor anyand all _Exercise 25While doing logical operations between a vector and a scalar each element of the vector is compared to thescalar Predict and check the result of each logical operator for the vector b = [2 31 -40 0] and the scalarc = 0 _Before moving on check whether you now understand the following relations

gtgt a = randperm(10) a random permutation of the numbers from 1 to 10gtgt b = 110gtgt b - (a lt= 7) subtracts from b a 0-1 vector taking 1 for a lt= 7 and 0 otherwisegtgt (a gt= 2) amp (a lt 4) returns ones at positions where 2 lt= a lt 4gtgt ~(b gt 4) returns ones at positions where b lt= 4gtgt (a == b) | b == 3 returns ones at positions where a is equal to b or b is equal to 3gtgt any (a gt 5) returns 1 when ANY of the a elements are larger than 5gtgt any (b lt 5 amp a gt 8) returns 1 when there in the evaluated expressiongtgt (b lt 5 amp a gt 8) appears at least one 1gtgt all (b gt 2) returns 1 when ALL b elements are larger than 22rdquoequal tordquo in the table on page 88 of rdquoThe Student Edition of Matlabrdquo must be rdquo==rdquo instead of rdquo=rdquo2262 Conditional code executionSelection control structures if-blocks are used to decide which instruction to execute next depending whether117-119 expression is TRUE or not The general description is given below In the examples below the command dispis frequently used This command displays on the screen the text between the quotesbull if endSyntaxif logical_expressionstatement1statement2endExampleif (a gt 0)b = adisp (rsquoa is positiversquo)endbull if else endSyntaxif logical_expressionblock of statementsevaluated if TRUEelseblock of statementsevaluated if FALSEendExampleif (temperature gt 100)disp (rsquoAbove boilingrsquo)toohigh = 1elsedisp (rsquoTemperature is OKrsquo)toohigh = 0endbull if elseif else endSyntaxif logical_expression1block of statements evaluatedif logical_expression1 is TRUEelseif logical_expression2block of statements evaluatedif logical_expression2 is TRUEelseblock of statements evaluatedif no other expression is TRUEendExampleif (height gt 190)disp (rsquovery tallrsquo)elseif (height gt 170)disp (rsquotallrsquo)elseif (height lt 150)disp (rsquosmallrsquo)

elsedisp (rsquoaveragersquo)endRemark To do the exercises below a script m-file will be useful It is an external file that contains asequence of Matlab commands What you need to do is to open an editor enter all commands needed forthe solution of a task save it with the extension rsquomrsquo (eg mytaskm) and then run it from the CommandWindow by typing mytask To open the Matlab editor go to the File menu-bar choose the Open optionand then m-file A new window will appear where you can write your scripts and save them on the disk Allcommands in the script will be executed in Matlab You will learn more on script m-files in section 91Important m-script file must be saved in one of the directories in Matlabrsquos pathAn example A script shortm can be created from the two lines given below and run by calling shortx = 0054plot (x sin(x) rsquo-rsquo)Exercise 26Create a script that asks for a number N and computes the drag coefficient C depending on the Reynoldrsquos23number N (make use of the if elseif construction) The command input might be useful here(read pages 32-33 from rdquoThe Student Edition of Matlabrdquoor use help)C =8gtgtgtltgtgtgt0 N _ 024N N 2 (0 01]24N (1 + 014N07) N 2 (01 1e3]043 N 2 (1e3 5e5]019 minus 8e4N N gt 5e5Check whether your script works correctly Compute the drag coefficient for eg N = -3e3 001 56 1e3 3e6(remember that eg 3e3 is a Matlab notation of 3 _ 103) _Exercise 27Write a script that asks for an integer and checks whether it can be divided by 2 or 3 Consider all possibilitiessuch as divisible by both 2 and 3 divisible by 2 and not by 3 etc (use the command rem) _Another selection structure is switch which switches between several cases depending on an expression which119-120 is either a scalar or a stringSyntaxswitch expressioncase choice1block of commands1case choice2a choice2bblock of commands2otherwiseblock of commandsendExamplemethod = 2switch methodcase 12disp(rsquoMethod is linearrsquo)case 3disp(rsquoMethod is cubicrsquo)case 4disp(rsquoMethod is nearestrsquo)otherwisedisp(rsquoUnknown methodrsquo)endThe statements following the first case where the expression matches the choice are executed Thisconstruction can be very handy to avoid long if elseif else end constructions Theexpression can be a scalar or a string A scalar expression matches a choice if expression == choice Astring expression matches a choice if strcmp(expression choice) returns 1 (is true) (strcmp is a commandcomparing two strings)Important Note that the switch-construction only allows the execution of one group of commandsExercise 28Assume that the months are represented by numbers from 1 to 12 Write a script that asks you to provide a

month and returns the number of days in that particular month Alternatively write a script that asks youto provide a month name (eg rsquoJunersquo) instead of a number Use the switch-construction _63 LoopsIteration control structures loops are used to repeat a block of statements until some condition is met Two114-117 types of loops existbull the for loop that repeats a group of statements a fixed number of timesSyntaxfor index = firststeplastblock of statementsendExamplesumx = 0for i=1length(x)sumx = sumx + x(i)end24You can specify any step including a negative value The index of the for-loop can be also a vectorSee some examples of possible variationsExample 1for i=12nendExample 2for i=n-13endExample 3for x=0054disp(x^2)endExample 4for x=[25 9 81]disp(sqrt(x))endbull while loop which evaluates a group of commands as long as expression is TRUESyntaxwhile expressionstatement1statement2statement3endExampleN = 100iter = 1msum = 0while iter lt= Nmsum = msum + iteriter = iter + 1endExercise 29Given the vectors x and y write a script computing the a matrix whose elements should be created accordingto a formula given below (make use of the length command to check the number of elements in both vectors)- aij = yixj (make sure that a division by zero will not occur)- bij = xi _ yj

- cij = 1 max (xi yj)_Exercise 30Determine the sum of the first 50 squared numbers with a control loop _Exercise 31Write a script to find the largest value n such that the sum p13 + p23 + + pn3 is less than 1000 _optionalExercise 32Write a script that transposes a matrix A Check its correctness with the Matlab operation Arsquo _Exercise 33

Write a script that asks for a temperature in degrees Celsius tc and computes the equivalent temperature indegrees Fahrenheit tf (use the formula tf = 95 _ tc + 32) The script should keep running until no numberis provided to convert The functions input and isempty (use help to learn more) should be useful here _end optional

64 Evaluation of logical and relational expressions in the control flow structuresThe relational and logical expressions may become more complicated It is not difficult to operate on them ifyou understand how they are evaluated To explain more details let us consider the following exampleif (~isempty(data)) amp (max(data) lt 5)endThis construction of the if-block is necessary to avoid comparison if data happens to be an empty matrix Insuch a case you cannot evaluate any expression and Matlab gives an error The amp operator returns 1 only ifboth expressions ~isempty (data) and max(data) lt 5 are true and 0 otherwise When data is an emptymatrix the next expression is not evaluated since the whole amp-expression is already known to be false Thesecond expression is checked only if data is a non-empty matrix Remember to put logical expression unitsbetween brackets to avoid wrong evaluations25Important The fact that computers make use of floating-point arithmetic means that often you should becareful when comparing two floating-point numbers just byif (x == y)end(Of course such a construction is allowed eg when you know that x and y represent integers) Instead of theabove construction you may try using thisif (abs (x - y) lt tolerance) eg tolerance = 1e-10endExercise 34Consider the following examplemax_iter = 50tolerance = 1e-4iter = 0xold = 01x = 1while (abs (x - xold) gt tolerance) amp (iter lt max_iter)xold = xx = cos(xold)iter = iter + 1endThis short program tries to solve the equation cos(x) = x (x is the solution found) Make the script solve cosfrom the presented code Note that the while-loop is repeated as long as both conditions are true If eitherthe condition (|x - xold| lt= tolerance) or (iter gt= max iter) is fulfilled then the loop is quitted Runthe script solve cos for different tolerance parameters eg 1e-3 1e-6 1e-8 1e-10 etc Use format long tocheck more precisely how much the found x is really different from cos(x) For each tolerance value checkthe number of performed iterations (iter value) _Exercise 35Create the script solve cos2 which is equal to the one given replacing the while-loop condition bywhile (abs (x - xold) gt tolerance) | (iter lt max_iter)Try to understand the difference and confirm your expectations by running solve cos2 What happens toiter _optional

65 Numerical analysis and the control flow structuresTake a look at the problem of a Taylor expansion The series will be determined numerically until the additionalterms are smaller than a defined precision Look at the Taylor expansion of 11minusx = 1 + x + x2 + withx = 042s = 0 x = 1 s = 0 x = 1x0 = 042 x0 = 042while (x gt 1e-6) or while (x gt (1e-6)s)s = s + x s = s + xx = x x0 x = x x0end endThe approximation of 11minusx is returned in s (first letter of sum) In the first case (on the left) the iteration

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 8: Introduction to Programming Using Matlab

2425verified with the commands who which gives a list of variables present in the workspace and whos whichincludes information on name number of allocated bytes and class of the variables For example assuming thatyou performed all commands given in the beginning after typing who you should get the following informationgtgt whoYour variables area ans b xThe command clear ltnamegt deletes the variable ltnamegt from the Matlab workspace clear or clear allremoves all variables This is useful when starting a new exercise For examplegtgt clear a xgtgt whoYour variables areans b16 Saving and loading dataThe easiest way to save or load Matlab variables is by using (clicking) the File menu-bar and then the Save26 Workspace as and Load Workspace items Also Matlab commands exist which allow you to saveand load data from filesThe command save allows for saving your workspace variables either into a binary file or an ASCII file (checkPreliminaries on binary and ASCII files) Binary files automatically get the rsquomatrsquo extension which is nottrue for ASCII files However it is recommended to add a rsquotxtrsquo or dat extensionExercise 1Learn how to use the save command by exercisinggtgt s1 = sin(pi4) s2 = sin(pi2)gtgt c1 = cos(pi4) c2 = cos(pi2)gtgt str = rsquohello worldrsquo this is a string example you will learn about strings latergtgt save saves all variables in binary format to the file matlabmatgtgt save data saves all variables in binary format to the file datamat6gtgt save numdata s1 c1 saves numeric variables s1 and c1 to the file numdatamatgtgt save strdata str saves a string variable str to the file strdatamatgtgtgtgt save allsin s saves all variables that match the pattern to allsinmatgtgt save allcosdat c -ascii saves c1c2 in 8-digit ascii format to allcosdat_The load command allows for loading variables into the workspace It uses the same syntax as saveExercise 2Assuming that you have done the previous exercise try to load variables from the created filesImportant before each load command clear the workspace and after loading check which variables arepresent in the workspace (using who)gtgt load loads all variables from the file matlabmatgtgt load data s1 c1 loads only specified variables from the file datamatgtgt load strdata loads all variables from the file strdatamatIt is also possible to read ASCII files that contain rows of space separated values Such a file may containcomments that begin with a percent character The resulting data is placed into a variable with the samename as the ASCII file (without the extension) Check for examplegtgt load allcosdat loads data from the file allcosdat into variable allcosgtgt who lists variables present in the workspace now_

2 Mathematics with numbers vectors and matricesThe basic element of Matlab is a matrix (or an array) Special cases arebull a 1 times 1-matrix a scalar or a single numberbull a matrix existing only of one row or one column a vector21 Single numbersYou have already got some experience with Matlab and you know that it can be used as a calculator To do4-614-1727that you can for example simply typegtgt 31256The result will beans =55714By default Matlab displays only 5 digits The command format long increases this number to 15 format

short reduces it to 5 again For examplegtgt format longgtgt 31256ans =557142857142857Exercise 3Define the format Matlab such that empty lines are suppressed and the output is given with 5 digitsCalculategtgt pigtgt sin(pi)Note that the answer is not exactly 0 _Use the command format to put Matlab in its standard-format ie short and loose7intermezzo

22 An introduction to floating-point numbersIn a computer numbers can be represented only in a discrete form It means that numbers are stored286 within a limited range and with a finite precision Integers can be represented exactly with the base of 2(read Preliminaries on bits and the binary system) The typical size of an integer is 16 bits so the largestpositive integer which can be stored is 216 = 65536 If negative integers are permitted then 16 bits allow forrepresenting integers between minus32768 and 32767 Within this range operations defined on the set of integerscan be performed exactlyHowever this is not valid for other real numbers In practice computers are integer machines and are capableof representing real numbers only by using complicated codes The most popular code is the floating pointstandard The term floating point is derived from the fact that there is no fixed number of digits before andafter the decimal point meaning that the decimal point can float Note that most floating-point numbers thata computer can represent are just approximations Therefore care should be taken that these approximationslead to reasonable results If a programmer is not careful small discrepancies in the approximations can causemeaningless results Note the difference between eg the integer arithmetic and floating-point arithmeticInteger arithmetic Floating-point arithmetic2 + 4 = 6 187 = 257143 4 = 12 25714 7 = 1799982511 = 2 100003 = 33333e+03When describing floating-point numbers precision refers to the number of bits used for the fractional partThe larger the precision the more exact fractional quantities can be represented Floating-point numbers areoften classified as single precision or double precision A double-precision number uses twice as many bits asa single-precision value so it can represent fractional values much better However the precision itself is notdouble The extra bits are also used to increase the range of magnitudes that can be representedMatlab relies on a computerrsquos floating point arithmetic You could have already noticed that in the last408-410 exercise since the value of sin(_) was almost zero and not completely zero It came from the fact that boththe value of _ is represented with a finite precision and the sin function is also approximatedThe fundamental type in Matlab is double which stands for a representation with a double precision It uses64 bits The single precision obtained by using the single type offers 32 bits Since most numeric operationsrequire high accuracy the double type is used by defaultThe exact machine precision might be defined as the smallest positive number _ that added to 1 does notchange the result so 1 + _ = 1 in floating-point arithmetic this value is larger than zero (in exact arithmeticof course _ = 0 holds) Matlab machine precision is stored in the built-in variable eps _ 22204e-16 Thismeans that the relative accuracy of individual arithmetic operations is about 16 digitsend intermezzo

23 Assignments and variablesWorking with complex numbers is easily done with MatlabExercise 4Choose two complex numbers for example -3 + 2i and 5 - 7i Try to add subtract multiply and dividethese two numbers _During this exercise the complex numbers had to be typed four times To reduce this assign each number to4-610-12a variable For the previous exercise this results ingtgt z = -3 + 2igtgt w = 5 - 7igtgt y1 = z + w y2 = z - w y3 = z w y4 = z w y5 = w zFormally there is no need to declare (ie define the name size and the type of) a new variable in Matlab Avariable is simply created by an assignment (the way it has been done above) Each newly created numerical

variable is always of the double type You can change this type by converting it into eg the single type 11a variable a is converted into a different type by performing eg a = single(a) a = int16(a) etc8In some cases when huge matrices should be handled and precision is not very important this might be a wayto proceed Also when only integers are taken into consideration it might be useful to convert the doublerepresentations into eg int16 or int321 integer types Since most computations should be performed with ahigh accuracy Matlab automatically chooses the double type It means that real numbers are approximatedwith the highest possible precision However it is important to emphasize that integer numbers are alwaysrepresented exactly no matter which numeric type is usedBear in mind that undefined values cannot be assigned to a variable So the following is not possiblegtgt clear x to make sure that x does not existgtgt fun = x^2 + 4 sin (x)It becomes possible bygtgt x = pi 3 fun = x^2 + 4 sin (x)Exercise 5Predict the result ofx = pi 3 x = x - 1 x = x + 5 x = abs(x) xCheck your prediction by performing these commands in Matlab _Exercise 6Here are some examples of different types of Matlab variables You do not need to understand them all nowsince you will learn more about them during the course Create them manually in Matlabgtgt this_is_my_very_simple_variable_today = 5 a number check what happens since thegtgt name is very long (gt 31 characters)gtgt 2t = 8 what is the problem with this commandgtgt this_is_a_matrix = [1 2 3 4 5 6] a matrixgtgt c = rsquoErsquo a charactergtgt str = rsquoHello worldrsquo a stringgtgt m = [rsquoJrsquorsquoorsquorsquohrsquorsquonrsquo] try to guess what it isCheck the types by using the command whos Use clear ltnamegt to remove a variable from the workspace _Exercise 7In addition to creating variables by assigning values to them a few other ways exist For instance there is anumber of built-in variables eg ans pi eps i inf or nan Find out what value is assigned to each of these74584 built-in variables _24 VectorsRow vectors are lists of numbers separated either by commas or by spaces They are examples of simple arrays41-49 The number of entries is known as the length of the vector (the command length exists as well) Their entitiesare referred to as elements or components The entries must be enclosed in [ ]gtgt v = [-1 sin(3) 7]v =-10000 01411 70000gtgt length(v)ans =3A number of operations can be done on vectors A vector can be multiplied by a scalar or addedsubtractedtofrom another vector with the same length or a number can be addedsubtracted tofrom a vector Allthese operations are carried out element-by-element Vectors can be also built from the already existing onesgtgt v = [-1 2 7] w = [2 3 4]gtgt z = v + w an element-by-element sumz =1 5 119gtgt v3 = v + 2 add 2 to all elements of vector v3v3 =1 4 9gtgt t = [2v -w]ans =-2 4 14 -2 -3 -4Also a particular value can be changed or displayedgtgt v(2) = -1 w(2) change the 2nd value of v display the 2nd value of wv =-1 -1 7ans =

3A colon notation is an important shortcut used when producing row vectors (see Table 3 and help colon)gtgt 25ans =2 3 4 5gtgt -23ans =-2 -1 0 1 2 3In general firststeplast produces a vector of entities with the value first incrementing by the stepuntil it reaches lastgtgt 020524ans =02000 07000 12000 17000 22000gtgt -3310ans =-3 0 3 6 9gtgt 15-05-05 negative step is also possibleans =15000 10000 05000 0 -05000Parts of vectors can be extracted by using a colon notationgtgt r = [-126 2 3 -2] -126 =gt -1 1 3 5r =-1 1 3 5 2 3 -2gtgt r(36) get elements of r which are on the positions from 3 to 6ans =3 5 2 3gtgt r(125) get elements of r which are on the positions from 1 to 5 taken with the step of 2ans =-1 3 2gtgt r(5-12) what will you get hereTo create column vectors you should separate entries by a semicolon () or by new linesgtgt f = [-1 3 5]f =-135The same operations as on row vectors can be done on column vectors However you cannot for exampleadd a column vector to a row vector To do that you need an operation called transposing which converts acolumn vector into a row vector and vice versa10gtgt f = [-1 3 5] a column vectorgtgt frsquo frsquo is a row vectorans =-1 3 5gtgt v = [-1 2 7] a row vectorgtgt f + v you cannot add a column vector f to a row vector v Error using ==gt +Matrix dimensions must agreegtgt frsquo + vans =-2 5 12gtgt f + vrsquoans =-2512If x is a complex vector than xrsquo gives the conjugate transpose of x eggtgt x = [1+2i -1+i]x =10000 + 20000i -10000 + 10000igtgt xrsquo this is the conjugate transposeans =10000 - 20000i-10000 - 10000i

gtgt xrsquo this is the rsquonormalrsquo transposeans =10000 + 20000i-10000 + 10000iExercise 8Exercise to become acquainted with operating on row and column vectors Enter all examples given in thissection and make new variations yourself Exercise with the colon notation approach as well _25 MatricesAn ntimesk matrix is a rectangular array of numbers having n rows and k columns Defining a matrix in Matlabis similar to defining a vector The generalization is straightforward if you know that a matrix consists of row49-6175-86vectors (or column vectors) Commas or spaces are used to separate elements in a row and semicolons areused to separate individual rows For example the matrix A =01 2 34 5 67 8 91Ais defined asgtgt A = [1 2 3 4 5 6 7 8 9] row by row inputA =1 2 34 5 67 8 9Another examples are for instancegtgt A2 = [14 -125]A2 =1 2 3 4-1 1 3 5gtgt A3 = [1 3-4 7]A3 =1 3-4 711Command ResultA(ij) Aij

A(j) j-th column of AA(i) i-th row of AA(klmn) (l minus k + 1) times (n minus m + 1) matrix with elements Aij with k _ i _ l m _ j _ nv(ij)rsquo rsquovector-partrsquo (vi vi+1 vj) of vector vTable 2 Manipulation of (groups of) matrix-elementsCommand Resultn = rank (A) n becomes the rank of matrix Ax = det (A) x becomes the determinant of matrix AC = size (A) C becomes a row-vector with 2 elements the number of rows and columns of Ax = trace (A) x becomes the trace (sum of diagonal elements) of matrix Ax = norm (v) x becomes the length of vector vC = A + B sum of two matricesC = A - B subtraction of two matricesC = A B multiplication of two matricesC = A B rdquoelement-by-elementrdquo multiplication (A and B are of equal size)C = A ^ k power of a matrix (k 2 Z can also be used for Aminus1)C = A ^ k rdquoelement-by-elementrdquo power of a matrixC = Arsquo the transposed of a matrix AT

C = A B rdquoelement-by-elementrdquo division (A and B are of equal size)U = A B finds the solution that minimizes the squared error in Ax minus BU = B A solution of XA = B analogous to the previous commandC = inv (A) C becomes the inverse of AC = null (A) C is an orthonormal basis for the null space of Aobtained from the singular value decompositionC = orth (A) C is an orthonormal basis for the range of AC = rref (A) C is the reduced row echelon form of AL = eig (A) L is a vector containing the -possibly complex- eigenvalues of a square matrix A[X D] = eig (A) produces a diagonal matrix D of eigenvalues and a full matrix X

whose columns are the corresponding eigenvectors of AS = svd (A) S is a vector containing the singular values of A[U S V] = svd (A) S is a diagonal matrix of the same dimension as Awith nonnegative diagonal elements in decreasing orderThe columns U and V are the accompanying singular vectorsx = linspace(a b n) generates a vector x of n equally spaced points between a and bx = logspace(a b n) generates a vector x starting at 10a and ended at 10b containing n valuesA = diag (v) gives a diagonal matrix with the elements v1 v2 vn on the diagonalA = eye (n) A is a n times n identity matrixA = zeros (n m) A is a n times m matrix with zeros (default m = n)A = rand (n m) A is a n times m matrix with elements uniformly distributed between 0 and 1A = randn (n m) ditto - with elements standard normal distributedv = max (A) v becomes a vector with the maximum value of the elements in each column of Aor v is the maximum of all elements if A is a vectorv = min (A) ditto - with minimumv = sum (A) ditto - with sumTable 3 Frequently used matrix operations and functions12Transposing a vector changes it from a row to a column or the other way around This idea can be extendedto a matrix where transposing interchanges rows with the corresponding columns as in the examplegtgt A2 A2rsquoA2 =1 2 3 4-1 1 3 5ans =1 -12 13 34 5gtgt size(A2) returns the size (dimensions) of a matrixans =2 4gtgt size(A2rsquo)ans =4 2There exists also some built-in matrices of size specified by the user (see Table 2) A few examples are givenbelowgtgt E = [] an empty matrix of 0-by-0 elementsE =[]gtgt I = eye(3) the identity matrixI =1 0 00 1 00 0 1gtgt B = rand(23) a matrix of random numbers you will get a different one00227 09101 0922200299 00640 03309gtgt O = ones(32)O =1 11 11 1gtgt r = [1 3 -2] R = diag(r) create a diagonal matrix with r on the diagonalR =1 0 00 3 00 0 -2gtgt v = linspace(124) a vector is also an example of a matrixv =10000 13333 16667 20000It is often needed to build a larger matrix from the smaller onesgtgt x = [4 -1] y = [-1 4]x =4

-1y =-1 4gtgt X = [x yrsquo] X consists of the columns x and yrsquoX =4 -1-1 4gtgt T = [ -1 3 4 4 5 6] t = 1313gtgt T2 = [T t] add to T a new row namely the row vector t getting T2T2 =-1 3 44 5 61 2 3gtgt G = [1 5 4 5 0 2] G is a matrix of the 3-by-2 size check size(G)gtgt T3 = [T2 G] T3 consists of T2 and new columns being the colums of GT3 = added at the end of T2-1 3 4 1 54 5 6 4 51 2 3 0 2gtgt [diag(56) ones(32)]ans =5 00 61 11 11 1A part can be extract from a matrix in a similar way as from a vector Each element in the matrix is indexedby a row and a column to which it belongs Mathematically the element from the i-th row and the j-thcolumn of the matrix A is denoted by Aij Matlab provides the A(ij) notationgtgt A = [13 46 79]A =1 2 34 5 67 8 9gtgt A(12) A(23) A(31)ans =2ans =6ans =7gtgt A(43) A is a 3-by-3 matrix Index exceeds matrix dimensionsgtgt A(23) = A(23) + 2A(11)A =1 2 34 5 87 8 9Having defined a matrix it is easy to extended it automatically For the matrix A it can be done eg asfollowsgtgt A(52) = 5 assign 5 to the position (52) the uninitializedA = elements become zeros1 2 34 5 87 8 90 0 00 5 0Different parts of the matrix A can be now extractedgtgt A(2) extract the 2nd column of Aans =25814

05gtgtgt A(34) extract the rows 3rd and 4th of Aans =7 8 90 0 0gtgt A(2312) extract a part of Aans =4 57 8If needed the other zero elements of the matrix A can be also defined by eggtgt A(4) = [1 2 3] assign vector [1 2 3] to the 4th row of Agtgt A(5[13]) = [4 5] a rsquoshortcutrsquo when assigning A(51) = 4 and A(53) = 5gtgt A how does the matrix A look like nowAs you have seen in the examples above it is possible to manipulate (groups of) matrix-elements Thecommands are shortly explained in Table 2Exercise 9Define the matrix A = [14 58 1 1 1 1] Predict and check the result ofgtgt B = A(3)gtgt C = A(1322)gtgt A(11) = 9gtgt A(2313) = [0 0 0 0 0 0]gtgt A(l212) = [l l 3 3]gtgt A = A(3314)_Exercise 10Define the matrices T=[ 3 4 1 8 -4 3] A = [diag(-123) T -4 4 1 2 1] Perform the followingoperations on the matrix Abull extract a vector consisting of the 2nd and 4th elements of the 3rd rowbull find the minimum of the 3rd columnbull find the maximum of the 2nd rowbull compute the sum of the 2nd columbull compute the mean of the 1st and 4th rowsbull extract the submatrix consisting of the 1st and 3rd rows and all columnsbull extract the submatrix consisting of the 1st and 2nd rows and the 3rd 4th and 5th columnsbull compute the total sum of the 1st and 2nd rowsbull add 3 to all elements of the 2nd and 3rd colums_Table 3 shows some frequently used matrix operations and functions A few examples are provided belowgtgt B = rand(23) a matrix of random numbers you will get a different oneB =09501 06068 0891302311 04860 07621gtgt B2 = [1 2 5 1 5 6]gtgt B + B2rsquo add two matrices why B2rsquo is needed instead of B2ans =19501 56068 5891322311 14860 67621gtgt S = ans4 divide all elements of the matrix ans by 4S =04875 14017 1472805578 03715 1690515gtgt C = [1 -1 4 7 0 -1]gtgt B C matrix multiplication is not defined for B and C Error using ==gt Inner matrix dimensions must agreegtgt B C but you can multiply element-by-elementans =09501 -06068 3565216180 0 -07621gtgt D = B Crsquo or you can make the multiplication legal Crsquo is now 3-by-2D =39085 5759627935 08559

gtgt D^3 this is equivalent to D D Dans =1992503 2041413990133 910548gtgt D^3 - 2 do for all elements raise to the power 3 and subtract 2ans =577069 1890638198005 -13731gtgtgtgt r = [1 3 -2]r B2 this is a legal operation r is a 1-by-3 matrix and B2 isans = 3-by-2 matrix B2 r is an illegal operation6 -7Remind that an n-by-k matrix A (having n rows and k columns) can be multiply by another matrix B onlyif B has k rows ie S is of the k-by-m size (m is arbitrary) As a result you get an n-by-m matrixA ˙B = C A 2 Rntimesk B 2 Rktimesm C 2 Rntimesm

RemarkYou can now compute the inner product between two vectors x and y xT y = Pi xi yi in a simple waygtgt f = [-1 3 5] a column vectorgtgt v = [-1 2 7] a column vectorgtgt frsquo v this is the inner productans =42gtgt f vrsquo be careful now a 3-by-1 matrix is multiplied by a 1-by-3gtgt matrix which results in a 3-by-3 matrix (the outer product)ans =1 -2 -7-3 6 21-5 10 35gtgt f v this is an element-by-element multiplication1635gtgt sum (f v) this is an another way to compute the inner productans =42Exercise 11Perform all operations from Table 3 using chosen matrices A and B vector v and scalars k a b n and m _Exercise 12Let A be a random 3 times 3 matrix and b a random 3 times 1 vector Given that Ax = b then x = Aminus1b Find x(there exist at least two possible commands to do this look at Table 3) _optionalThe concept of an empty matrix [] is also very useful in Matlab For instance a few columns or rows canbe removed from a matrix by assigning an empty matrix to it Try for example16Symbol Color Symbol Styley yellow dotted liner red o circlesg green - solid lineb blue - dashdotted lineTable 4 Plot colors and stylesgtgt C = [1 2 3 4 5 6 7 8 1 1 1 1]gtgt D = C D(2) = [] now a copy of C is in D remove the 2nd column of Dgtgt C ([13]) = [] remove the rows 1 and 3 from Cend optional

3 VisualizationMatlab can be used to visualize the results of an experiment Therefore you should define variables each ofthem containing all values of one parameter to plot31 Simple plotsWith the command plot a graphical display can be made plot(y) draws the points (1 y(1)) (2 y(2)) 184 (n y(n)) and connects the points with a straight line plot(xy) does the same for (x(1) y(1)) (x(2) y(2)) (x(n) y(n)) x and y have to be row- or column vectors of equal lengthThe commands loglog semilogx and semilogy are similar to plot except that they use logarithmic axesExercise 13Type the following commands after predicting the resultgtgt x = 0330

gtgt y = 2^[010] this is the same as y = [1 2 4 8 16 32 64 128 256 512 1024]gtgt plot(xy) to get a graphic representationgtgt semilogy(xy) to get logarithmic axesAs you can see the same figure is used for both plot commands The previous function is removed as soonas the next is displayed The command figure gives you an extra figure Repeat the previous commandsbut generate a new figure before plotting the second function so that you can see both functions in separatewindows You can also switch back to a figure using figure(n) where n is its number _Exercise 14Make a plot such that the coordinates (2 6) (25 18) (5 175) (42 125) and (212) are connected by aline _Exercise 15Plot the function y = sin(x) + x minus x cos(x) in two separate figures for the intervals 0 lt x lt 30 andminus100 lt x lt 100 _32 Several functions in one figureWhen more than one function is plotted in one figure it might be useful to use different markers and colors184-188197-201Table 4 shows a few possibilities help plot shows allThere are different ways to get more than one function into a figure The first one is with the command holdon After this command all functions will be plotted in the same figure until the command hold off is usedAn examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt plot (x1 y1 rsquordrsquo)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)17gtgt hold ongtgt plot (x2 y2 rsquoy-rsquo)gtgt plot (x1y1rsquok-rsquo)gtgt hold offA second method to display more than one function in one figure is to plot several functions at the same timeThe next commands will have the same results as the commands in the previous examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt plot (x1 y1rsquordrsquo x2 y2 rsquoy-rsquo x1 y1 rsquok-rsquo)It is also possible to get more than one figure in one figure window With the command subplot the windowcan be horizontally and vertically divided into any number of subfiguresgtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt subplot(131) plot (x1 y1rsquordrsquo)gtgt subplot(132) plot (x2 y2 rsquoy-rsquo)gtgt subplot(133) plot (x1 y1 rsquok-rsquo)optional

33 Other 2D plotting featuresIn the introduction of this chapter some commands similar to plot loglog semilogx and semilogy were201-211 mentioned There are however more ways to display dataExercise 16To get an impression of other visualizations type the following commands and describe the result (note thatthe command figure creates a new figure window)gtgt figure bar plot of a bell shaped curvegtgt x = -290229gtgt bar (x exp (-xx))gtgt figure stairstep plot of a sine wavegtgt x = 002510gtgt stairs (x sin (x))gtgt figure errorbar plotgtgt x = -2012gtgt y = erf (x) error function check help if you are interestedgtgt e = rand (size (x)) 10gtgt errorbar (x y e)

_end optional

34 PrintingBefore printing a figure you made you might want to add some information such as a title or change the189-196 lay-out a little Table 5 shows some of the commands that can be usedExercise 17Plot the functions y1 = sin(4x) y2 = x cos(x) y3 = (x + 1)minus1px for x = 0 025 10 and a single point(x y) = (4 5) in one figure with different colors and styles Make a legend containing the three functionsMake labels for both axes and a title Add a text to the single point saying single point Change the minimumand maximum values of the axes such that function y3 can be looked at in more detail _When the displayed figure is to your liking you can print it to paper The easiest way to do this is to click onFile in the menu-bar and to choose Print If in the print window you click OK your figure will be printed onthe printer indicated in the print window18Command Resultgrid onoff adds a grid to the plot at the tick marks or removes itaxis([xmin xmax ymin ymax]) sets the minimum and maximum values of the axesbox offon removes the axes box or shows itxlabel(rsquotextrsquo) plots the label text on the x axisylabel(rsquotextrsquo) plots the label text on the y axistitle(rsquotextrsquo) plots a title above the graphtext(xyrsquotextrsquo) adds text at the point (xy)gtext(rsquotextrsquo) adds text at a manually (with a mouse) indicated pointlegend(rsquofun1rsquorsquofun2rsquo) plots a legend box (move it with your mouse) to name your functionslegend off deletes the legend boxTable 5 Plot-manipulationsThere is also a print command which can be used to send a figure to a printer or output it to a file Youcan optionally specify a print device (ie an output format such as tiff or postscript) and options that controlvarious characteristics of the printed file (ie which Figure to print etc) You can also print to a file if youspecify the file name If you do not provide an extension print adds one Since they are many parametersthey will not be explained here (check help print to learn more) Instead try to understand the examplesgtgt print -dwinc print the current Figure to the current printer in colorgtgt print -f1 -deps myfileeps print Figure no1 to the file myfileeps in blackgtgt print -f1 -depsc myfileceps print Figure no1 to the file myfilecoleps in colorgtgt print -dtiff myfile1tiff print the current Figure to the file myfile1tiffgtgt print -dpsc myfile1cps print the current Figure to the file myfile1ps in colorgtgt print -f2 -djpeg myfile2 print Figure no2 to the file myfile2jpgExercise 18Exercise with printing (especially to a file) the figure from Exercise 16 _

4 Curve fitting and interpolationThere are two ways to describe data with an analytical function- curve fitting or regression finding a smooth curve that best fits (approximates) the data accordingto a criterion (eg best least square fit) The curve does not have to go through any of the data points- interpolation the data are assumed to be correct desired in a way to describe what happens betweenthe data points In other words given a finite set of points the goal of interpolation is to find a functionfrom a given class of functions (eg polynomials) which passes through the specified pointsThe figure below illustrates the difference between regression (curve fitting) and interpolationminus5 0 5minus6minus4minus20246810fiting a 3rd order polynomialinterpolation

41 Curve fittingMatlab interprets the best fit of a curve by the lsquoleast squares curve fittingrsquo The curve used is restricted153-15619to polynomials With the command polyfit any polynomial can be fitted to the data polyfit (x y n)finds the coefficients of a polynomial of degree n that fits the data (finds the linear relation between x and y)Letrsquos start with finding a linear regression of some datagtgt x = 010gtgt y = [-10 24 102 158 284 276 299 405 483 522 751]gtgt p = polyfit (x y 1) find the fitting polynomial of order 1p = 06772 -03914

The output of polyfit is a row vector of the polynomial coefficients the solution of this example is thereforey = 06772x minus 03914Exercise 19Execute the above example Plot the data and the fitted curve in a figure Determine the 2nd and 9th orderpolynomial of these data as well and display the solution in a figureHint x1 = linspace (xmin xmax n) results in a vector with n element evenly distributed from xmintill xmax z = polyval (p x1) calculates the values of the polynomial for every element of x1 _Exercise 20Define x and y as followsgtgt x = -55gtgt y = 02x^3 - x + 2 a 3rd order polynomialgtgt y = y + randn(111) add some noise to yDetermine the 3rd order polynomial fitting y (note that because of added noise the coefficients are differentthat originally chosen) Try some other polynomials as well Plot the results in a figure _42 InterpolationThe simplest way to examine an interpolation is by displaying the function plots with the command plot157-161 The neighboring data points are connected with straight lines This is called a linear interpolation Whenmore data-points are taken into account the effect of interpolation becomes less visible Analyzegtgt x1 = linspace(0 2pi2)gtgt x2 = linspace(0 2pi4)gtgt x3 = linspace(0 2pi16)gtgt x4 = linspace(0 2pi256)gtgt plot(x1sin(x1)x2sin(x2)x3sin(x3)x4sin(x4))gtgt legend(rsquo2 pointsrsquorsquo4 pointsrsquorsquo16 pointsrsquorsquo256 pointsrsquo)

5 Numerical analysisNumerical analysis can be used whenever it is impossible or very difficult to determine the analytical solutionMatlab can be used to find for example the minimum maximum or integral of a certain function51 Evaluation of a functionAs said before the command plot plots a function by connecting defined data points Sometimes however a168-173 function is constant and not very interesting over some range and then acts unexpectedly wildly over anotherWith plot this function might be misinterpreted The command fplot is then useful An examplegtgt x = 0pi82pigtgt y = sin (8x)gtgt plot (x y rsquobrsquo)gtgt hold ongtgt fplot (rsquosin (8z)rsquo [0 2pi] rsquorrsquo)gtgt title (rsquosin (8z)rsquo)gtgt hold off20Command Resultfplot (rsquofunrsquo [min x max x]) plots the function fun for min x till max xfmin (rsquofunrsquo min x max x) gives the x-value of the miminum of thefunction fun between min x and max xfzero (rsquofunrsquo x0) gives the x-value for which the functionfun is zero in the neighborhood of x0Table 6 Evaluation of a functionExecution of these commands results in a figure with an almost straight blue line and a red sine fplot canalso be used to plot a defined functiongtgt f = rsquosin (8z)rsquogtgt fplot (f [0 2pi] rsquorrsquo)gtgt title (f)Other useful commands for a detailed study of a range of a function are listed in Table 6Exercise 21The command fmax does not exist Use one or more of the commands from Table 6 to determine the maximumof the function x cos(x) for 10 lt x lt 15 _52 Integration and differentiationThe integral- or the surface underneath a 2D function- can be determined with the command trapz trapz173-182 does this by measuring the surface between the x-axis and the -by a straight line connected- data points Theaccuracy of this method depends on the distance between the data pointsgtgt x = 00510 y = 05 sqrt (x) + x sin (x) area1 = trapz (x y)

area1 =181655gtgt x = 000510 y = 05 sqrt (x) + x sin (x) area2 = trapz (x y)area2 =183846Differentiation is done by determining the slope in each data point Numerically this is done by first fitting apolynomial followed by differentiating this functiongtgt x = 010gtgt y = [-10 24 102 -158 284 276 775 35 483 522 751]gtgt p = polyfit (x y 5)p = 00026 -00554 03634 -06888 02747 00877gtgt dp = polyder (p)dp = 00132 -02216 10903 -13776 02747gtgt x1 = linspace (0 10 200)gtgt z = polyval (p x1)gtgt dz = polyval (dp x1)gtgt plot (x y rsquog-rsquo x1 z rsquobrsquo x1 dz rsquorrsquo)gtgt legend (rsquodata pointsrsquo rsquocurve fitrsquo rsquoderivativersquo)Exercise 22Determine the integral and derivative of the 4th polynomial fitted through (xy) with x = [4 5 6 7 8 9 1011 12 13] y = [1284 1200 724 -096 -1116 -2096 -2700 -2496 -956 2544] _

6 Control flowAs you know it is possible to execute more than one command at the same time (see section 11) Theseparate commands should then be divided by commarsquos (to display the output) or by semicolons (to suppress21output display) Control flow loops increase the number of possibilities A control flow structure is a block ofcommands that allows conditional code execution and making loops61 Logical and relational operatorsTo use control flow commands it is necessary to perform operations that result in logical values TRUE or88-91 FALSE In Matlab the result of a logical operation is 1 if it is true and 0 if it is false Table 7 shows therelational and logical operations2 Another way to get to know more about them is to type help relop Therelational operators lt lt= gt gt= == and ~= can be used to compare two arrays of the same size or anarray to a scalar The logical operators amp | and ~ allow for the logical combination or negation of relationaloperators In addition three functions are also available xor any and all (use help to find out more)Important The logical amp and | have the equal precedence in Matlab which means that those operatorsassociate from left to right A common situation isgtgt b = 10gtgt 1 | b gt 0 amp 0ans =0gtgt (1 | b gt 0) amp 0 this indicates the same as aboveans =0gtgt 1 | (b gt 0 amp 0)ans =1This shows that you should always use brackets to indicate in which way the operators should be evaluatedCommand Resulta = (b gt c) a is 1 if b is larger than c Similar are lt gt= and lt=a = (b == c) a is 1 if b is equal to ca = (b ~= c) a is 1 if b is not equal ca = ~b logical complement a is 1 if b is 0a = (b amp c) logical AND a is 1 if b = TRUE AND c = TRUEa = (b | c) logical OR a is 1 if b = TRUE OR c = TRUETable 7 Relational and logical operationsExercise 23Predict and check the result of each of the operations of Table 7 for b = 0 and c = -1 _Exercise 24Define two vectors with seven elements (randn(17)) and perform all logical operations including xor anyand all _Exercise 25While doing logical operations between a vector and a scalar each element of the vector is compared to thescalar Predict and check the result of each logical operator for the vector b = [2 31 -40 0] and the scalarc = 0 _Before moving on check whether you now understand the following relations

gtgt a = randperm(10) a random permutation of the numbers from 1 to 10gtgt b = 110gtgt b - (a lt= 7) subtracts from b a 0-1 vector taking 1 for a lt= 7 and 0 otherwisegtgt (a gt= 2) amp (a lt 4) returns ones at positions where 2 lt= a lt 4gtgt ~(b gt 4) returns ones at positions where b lt= 4gtgt (a == b) | b == 3 returns ones at positions where a is equal to b or b is equal to 3gtgt any (a gt 5) returns 1 when ANY of the a elements are larger than 5gtgt any (b lt 5 amp a gt 8) returns 1 when there in the evaluated expressiongtgt (b lt 5 amp a gt 8) appears at least one 1gtgt all (b gt 2) returns 1 when ALL b elements are larger than 22rdquoequal tordquo in the table on page 88 of rdquoThe Student Edition of Matlabrdquo must be rdquo==rdquo instead of rdquo=rdquo2262 Conditional code executionSelection control structures if-blocks are used to decide which instruction to execute next depending whether117-119 expression is TRUE or not The general description is given below In the examples below the command dispis frequently used This command displays on the screen the text between the quotesbull if endSyntaxif logical_expressionstatement1statement2endExampleif (a gt 0)b = adisp (rsquoa is positiversquo)endbull if else endSyntaxif logical_expressionblock of statementsevaluated if TRUEelseblock of statementsevaluated if FALSEendExampleif (temperature gt 100)disp (rsquoAbove boilingrsquo)toohigh = 1elsedisp (rsquoTemperature is OKrsquo)toohigh = 0endbull if elseif else endSyntaxif logical_expression1block of statements evaluatedif logical_expression1 is TRUEelseif logical_expression2block of statements evaluatedif logical_expression2 is TRUEelseblock of statements evaluatedif no other expression is TRUEendExampleif (height gt 190)disp (rsquovery tallrsquo)elseif (height gt 170)disp (rsquotallrsquo)elseif (height lt 150)disp (rsquosmallrsquo)

elsedisp (rsquoaveragersquo)endRemark To do the exercises below a script m-file will be useful It is an external file that contains asequence of Matlab commands What you need to do is to open an editor enter all commands needed forthe solution of a task save it with the extension rsquomrsquo (eg mytaskm) and then run it from the CommandWindow by typing mytask To open the Matlab editor go to the File menu-bar choose the Open optionand then m-file A new window will appear where you can write your scripts and save them on the disk Allcommands in the script will be executed in Matlab You will learn more on script m-files in section 91Important m-script file must be saved in one of the directories in Matlabrsquos pathAn example A script shortm can be created from the two lines given below and run by calling shortx = 0054plot (x sin(x) rsquo-rsquo)Exercise 26Create a script that asks for a number N and computes the drag coefficient C depending on the Reynoldrsquos23number N (make use of the if elseif construction) The command input might be useful here(read pages 32-33 from rdquoThe Student Edition of Matlabrdquoor use help)C =8gtgtgtltgtgtgt0 N _ 024N N 2 (0 01]24N (1 + 014N07) N 2 (01 1e3]043 N 2 (1e3 5e5]019 minus 8e4N N gt 5e5Check whether your script works correctly Compute the drag coefficient for eg N = -3e3 001 56 1e3 3e6(remember that eg 3e3 is a Matlab notation of 3 _ 103) _Exercise 27Write a script that asks for an integer and checks whether it can be divided by 2 or 3 Consider all possibilitiessuch as divisible by both 2 and 3 divisible by 2 and not by 3 etc (use the command rem) _Another selection structure is switch which switches between several cases depending on an expression which119-120 is either a scalar or a stringSyntaxswitch expressioncase choice1block of commands1case choice2a choice2bblock of commands2otherwiseblock of commandsendExamplemethod = 2switch methodcase 12disp(rsquoMethod is linearrsquo)case 3disp(rsquoMethod is cubicrsquo)case 4disp(rsquoMethod is nearestrsquo)otherwisedisp(rsquoUnknown methodrsquo)endThe statements following the first case where the expression matches the choice are executed Thisconstruction can be very handy to avoid long if elseif else end constructions Theexpression can be a scalar or a string A scalar expression matches a choice if expression == choice Astring expression matches a choice if strcmp(expression choice) returns 1 (is true) (strcmp is a commandcomparing two strings)Important Note that the switch-construction only allows the execution of one group of commandsExercise 28Assume that the months are represented by numbers from 1 to 12 Write a script that asks you to provide a

month and returns the number of days in that particular month Alternatively write a script that asks youto provide a month name (eg rsquoJunersquo) instead of a number Use the switch-construction _63 LoopsIteration control structures loops are used to repeat a block of statements until some condition is met Two114-117 types of loops existbull the for loop that repeats a group of statements a fixed number of timesSyntaxfor index = firststeplastblock of statementsendExamplesumx = 0for i=1length(x)sumx = sumx + x(i)end24You can specify any step including a negative value The index of the for-loop can be also a vectorSee some examples of possible variationsExample 1for i=12nendExample 2for i=n-13endExample 3for x=0054disp(x^2)endExample 4for x=[25 9 81]disp(sqrt(x))endbull while loop which evaluates a group of commands as long as expression is TRUESyntaxwhile expressionstatement1statement2statement3endExampleN = 100iter = 1msum = 0while iter lt= Nmsum = msum + iteriter = iter + 1endExercise 29Given the vectors x and y write a script computing the a matrix whose elements should be created accordingto a formula given below (make use of the length command to check the number of elements in both vectors)- aij = yixj (make sure that a division by zero will not occur)- bij = xi _ yj

- cij = 1 max (xi yj)_Exercise 30Determine the sum of the first 50 squared numbers with a control loop _Exercise 31Write a script to find the largest value n such that the sum p13 + p23 + + pn3 is less than 1000 _optionalExercise 32Write a script that transposes a matrix A Check its correctness with the Matlab operation Arsquo _Exercise 33

Write a script that asks for a temperature in degrees Celsius tc and computes the equivalent temperature indegrees Fahrenheit tf (use the formula tf = 95 _ tc + 32) The script should keep running until no numberis provided to convert The functions input and isempty (use help to learn more) should be useful here _end optional

64 Evaluation of logical and relational expressions in the control flow structuresThe relational and logical expressions may become more complicated It is not difficult to operate on them ifyou understand how they are evaluated To explain more details let us consider the following exampleif (~isempty(data)) amp (max(data) lt 5)endThis construction of the if-block is necessary to avoid comparison if data happens to be an empty matrix Insuch a case you cannot evaluate any expression and Matlab gives an error The amp operator returns 1 only ifboth expressions ~isempty (data) and max(data) lt 5 are true and 0 otherwise When data is an emptymatrix the next expression is not evaluated since the whole amp-expression is already known to be false Thesecond expression is checked only if data is a non-empty matrix Remember to put logical expression unitsbetween brackets to avoid wrong evaluations25Important The fact that computers make use of floating-point arithmetic means that often you should becareful when comparing two floating-point numbers just byif (x == y)end(Of course such a construction is allowed eg when you know that x and y represent integers) Instead of theabove construction you may try using thisif (abs (x - y) lt tolerance) eg tolerance = 1e-10endExercise 34Consider the following examplemax_iter = 50tolerance = 1e-4iter = 0xold = 01x = 1while (abs (x - xold) gt tolerance) amp (iter lt max_iter)xold = xx = cos(xold)iter = iter + 1endThis short program tries to solve the equation cos(x) = x (x is the solution found) Make the script solve cosfrom the presented code Note that the while-loop is repeated as long as both conditions are true If eitherthe condition (|x - xold| lt= tolerance) or (iter gt= max iter) is fulfilled then the loop is quitted Runthe script solve cos for different tolerance parameters eg 1e-3 1e-6 1e-8 1e-10 etc Use format long tocheck more precisely how much the found x is really different from cos(x) For each tolerance value checkthe number of performed iterations (iter value) _Exercise 35Create the script solve cos2 which is equal to the one given replacing the while-loop condition bywhile (abs (x - xold) gt tolerance) | (iter lt max_iter)Try to understand the difference and confirm your expectations by running solve cos2 What happens toiter _optional

65 Numerical analysis and the control flow structuresTake a look at the problem of a Taylor expansion The series will be determined numerically until the additionalterms are smaller than a defined precision Look at the Taylor expansion of 11minusx = 1 + x + x2 + withx = 042s = 0 x = 1 s = 0 x = 1x0 = 042 x0 = 042while (x gt 1e-6) or while (x gt (1e-6)s)s = s + x s = s + xx = x x0 x = x x0end endThe approximation of 11minusx is returned in s (first letter of sum) In the first case (on the left) the iteration

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 9: Introduction to Programming Using Matlab

short reduces it to 5 again For examplegtgt format longgtgt 31256ans =557142857142857Exercise 3Define the format Matlab such that empty lines are suppressed and the output is given with 5 digitsCalculategtgt pigtgt sin(pi)Note that the answer is not exactly 0 _Use the command format to put Matlab in its standard-format ie short and loose7intermezzo

22 An introduction to floating-point numbersIn a computer numbers can be represented only in a discrete form It means that numbers are stored286 within a limited range and with a finite precision Integers can be represented exactly with the base of 2(read Preliminaries on bits and the binary system) The typical size of an integer is 16 bits so the largestpositive integer which can be stored is 216 = 65536 If negative integers are permitted then 16 bits allow forrepresenting integers between minus32768 and 32767 Within this range operations defined on the set of integerscan be performed exactlyHowever this is not valid for other real numbers In practice computers are integer machines and are capableof representing real numbers only by using complicated codes The most popular code is the floating pointstandard The term floating point is derived from the fact that there is no fixed number of digits before andafter the decimal point meaning that the decimal point can float Note that most floating-point numbers thata computer can represent are just approximations Therefore care should be taken that these approximationslead to reasonable results If a programmer is not careful small discrepancies in the approximations can causemeaningless results Note the difference between eg the integer arithmetic and floating-point arithmeticInteger arithmetic Floating-point arithmetic2 + 4 = 6 187 = 257143 4 = 12 25714 7 = 1799982511 = 2 100003 = 33333e+03When describing floating-point numbers precision refers to the number of bits used for the fractional partThe larger the precision the more exact fractional quantities can be represented Floating-point numbers areoften classified as single precision or double precision A double-precision number uses twice as many bits asa single-precision value so it can represent fractional values much better However the precision itself is notdouble The extra bits are also used to increase the range of magnitudes that can be representedMatlab relies on a computerrsquos floating point arithmetic You could have already noticed that in the last408-410 exercise since the value of sin(_) was almost zero and not completely zero It came from the fact that boththe value of _ is represented with a finite precision and the sin function is also approximatedThe fundamental type in Matlab is double which stands for a representation with a double precision It uses64 bits The single precision obtained by using the single type offers 32 bits Since most numeric operationsrequire high accuracy the double type is used by defaultThe exact machine precision might be defined as the smallest positive number _ that added to 1 does notchange the result so 1 + _ = 1 in floating-point arithmetic this value is larger than zero (in exact arithmeticof course _ = 0 holds) Matlab machine precision is stored in the built-in variable eps _ 22204e-16 Thismeans that the relative accuracy of individual arithmetic operations is about 16 digitsend intermezzo

23 Assignments and variablesWorking with complex numbers is easily done with MatlabExercise 4Choose two complex numbers for example -3 + 2i and 5 - 7i Try to add subtract multiply and dividethese two numbers _During this exercise the complex numbers had to be typed four times To reduce this assign each number to4-610-12a variable For the previous exercise this results ingtgt z = -3 + 2igtgt w = 5 - 7igtgt y1 = z + w y2 = z - w y3 = z w y4 = z w y5 = w zFormally there is no need to declare (ie define the name size and the type of) a new variable in Matlab Avariable is simply created by an assignment (the way it has been done above) Each newly created numerical

variable is always of the double type You can change this type by converting it into eg the single type 11a variable a is converted into a different type by performing eg a = single(a) a = int16(a) etc8In some cases when huge matrices should be handled and precision is not very important this might be a wayto proceed Also when only integers are taken into consideration it might be useful to convert the doublerepresentations into eg int16 or int321 integer types Since most computations should be performed with ahigh accuracy Matlab automatically chooses the double type It means that real numbers are approximatedwith the highest possible precision However it is important to emphasize that integer numbers are alwaysrepresented exactly no matter which numeric type is usedBear in mind that undefined values cannot be assigned to a variable So the following is not possiblegtgt clear x to make sure that x does not existgtgt fun = x^2 + 4 sin (x)It becomes possible bygtgt x = pi 3 fun = x^2 + 4 sin (x)Exercise 5Predict the result ofx = pi 3 x = x - 1 x = x + 5 x = abs(x) xCheck your prediction by performing these commands in Matlab _Exercise 6Here are some examples of different types of Matlab variables You do not need to understand them all nowsince you will learn more about them during the course Create them manually in Matlabgtgt this_is_my_very_simple_variable_today = 5 a number check what happens since thegtgt name is very long (gt 31 characters)gtgt 2t = 8 what is the problem with this commandgtgt this_is_a_matrix = [1 2 3 4 5 6] a matrixgtgt c = rsquoErsquo a charactergtgt str = rsquoHello worldrsquo a stringgtgt m = [rsquoJrsquorsquoorsquorsquohrsquorsquonrsquo] try to guess what it isCheck the types by using the command whos Use clear ltnamegt to remove a variable from the workspace _Exercise 7In addition to creating variables by assigning values to them a few other ways exist For instance there is anumber of built-in variables eg ans pi eps i inf or nan Find out what value is assigned to each of these74584 built-in variables _24 VectorsRow vectors are lists of numbers separated either by commas or by spaces They are examples of simple arrays41-49 The number of entries is known as the length of the vector (the command length exists as well) Their entitiesare referred to as elements or components The entries must be enclosed in [ ]gtgt v = [-1 sin(3) 7]v =-10000 01411 70000gtgt length(v)ans =3A number of operations can be done on vectors A vector can be multiplied by a scalar or addedsubtractedtofrom another vector with the same length or a number can be addedsubtracted tofrom a vector Allthese operations are carried out element-by-element Vectors can be also built from the already existing onesgtgt v = [-1 2 7] w = [2 3 4]gtgt z = v + w an element-by-element sumz =1 5 119gtgt v3 = v + 2 add 2 to all elements of vector v3v3 =1 4 9gtgt t = [2v -w]ans =-2 4 14 -2 -3 -4Also a particular value can be changed or displayedgtgt v(2) = -1 w(2) change the 2nd value of v display the 2nd value of wv =-1 -1 7ans =

3A colon notation is an important shortcut used when producing row vectors (see Table 3 and help colon)gtgt 25ans =2 3 4 5gtgt -23ans =-2 -1 0 1 2 3In general firststeplast produces a vector of entities with the value first incrementing by the stepuntil it reaches lastgtgt 020524ans =02000 07000 12000 17000 22000gtgt -3310ans =-3 0 3 6 9gtgt 15-05-05 negative step is also possibleans =15000 10000 05000 0 -05000Parts of vectors can be extracted by using a colon notationgtgt r = [-126 2 3 -2] -126 =gt -1 1 3 5r =-1 1 3 5 2 3 -2gtgt r(36) get elements of r which are on the positions from 3 to 6ans =3 5 2 3gtgt r(125) get elements of r which are on the positions from 1 to 5 taken with the step of 2ans =-1 3 2gtgt r(5-12) what will you get hereTo create column vectors you should separate entries by a semicolon () or by new linesgtgt f = [-1 3 5]f =-135The same operations as on row vectors can be done on column vectors However you cannot for exampleadd a column vector to a row vector To do that you need an operation called transposing which converts acolumn vector into a row vector and vice versa10gtgt f = [-1 3 5] a column vectorgtgt frsquo frsquo is a row vectorans =-1 3 5gtgt v = [-1 2 7] a row vectorgtgt f + v you cannot add a column vector f to a row vector v Error using ==gt +Matrix dimensions must agreegtgt frsquo + vans =-2 5 12gtgt f + vrsquoans =-2512If x is a complex vector than xrsquo gives the conjugate transpose of x eggtgt x = [1+2i -1+i]x =10000 + 20000i -10000 + 10000igtgt xrsquo this is the conjugate transposeans =10000 - 20000i-10000 - 10000i

gtgt xrsquo this is the rsquonormalrsquo transposeans =10000 + 20000i-10000 + 10000iExercise 8Exercise to become acquainted with operating on row and column vectors Enter all examples given in thissection and make new variations yourself Exercise with the colon notation approach as well _25 MatricesAn ntimesk matrix is a rectangular array of numbers having n rows and k columns Defining a matrix in Matlabis similar to defining a vector The generalization is straightforward if you know that a matrix consists of row49-6175-86vectors (or column vectors) Commas or spaces are used to separate elements in a row and semicolons areused to separate individual rows For example the matrix A =01 2 34 5 67 8 91Ais defined asgtgt A = [1 2 3 4 5 6 7 8 9] row by row inputA =1 2 34 5 67 8 9Another examples are for instancegtgt A2 = [14 -125]A2 =1 2 3 4-1 1 3 5gtgt A3 = [1 3-4 7]A3 =1 3-4 711Command ResultA(ij) Aij

A(j) j-th column of AA(i) i-th row of AA(klmn) (l minus k + 1) times (n minus m + 1) matrix with elements Aij with k _ i _ l m _ j _ nv(ij)rsquo rsquovector-partrsquo (vi vi+1 vj) of vector vTable 2 Manipulation of (groups of) matrix-elementsCommand Resultn = rank (A) n becomes the rank of matrix Ax = det (A) x becomes the determinant of matrix AC = size (A) C becomes a row-vector with 2 elements the number of rows and columns of Ax = trace (A) x becomes the trace (sum of diagonal elements) of matrix Ax = norm (v) x becomes the length of vector vC = A + B sum of two matricesC = A - B subtraction of two matricesC = A B multiplication of two matricesC = A B rdquoelement-by-elementrdquo multiplication (A and B are of equal size)C = A ^ k power of a matrix (k 2 Z can also be used for Aminus1)C = A ^ k rdquoelement-by-elementrdquo power of a matrixC = Arsquo the transposed of a matrix AT

C = A B rdquoelement-by-elementrdquo division (A and B are of equal size)U = A B finds the solution that minimizes the squared error in Ax minus BU = B A solution of XA = B analogous to the previous commandC = inv (A) C becomes the inverse of AC = null (A) C is an orthonormal basis for the null space of Aobtained from the singular value decompositionC = orth (A) C is an orthonormal basis for the range of AC = rref (A) C is the reduced row echelon form of AL = eig (A) L is a vector containing the -possibly complex- eigenvalues of a square matrix A[X D] = eig (A) produces a diagonal matrix D of eigenvalues and a full matrix X

whose columns are the corresponding eigenvectors of AS = svd (A) S is a vector containing the singular values of A[U S V] = svd (A) S is a diagonal matrix of the same dimension as Awith nonnegative diagonal elements in decreasing orderThe columns U and V are the accompanying singular vectorsx = linspace(a b n) generates a vector x of n equally spaced points between a and bx = logspace(a b n) generates a vector x starting at 10a and ended at 10b containing n valuesA = diag (v) gives a diagonal matrix with the elements v1 v2 vn on the diagonalA = eye (n) A is a n times n identity matrixA = zeros (n m) A is a n times m matrix with zeros (default m = n)A = rand (n m) A is a n times m matrix with elements uniformly distributed between 0 and 1A = randn (n m) ditto - with elements standard normal distributedv = max (A) v becomes a vector with the maximum value of the elements in each column of Aor v is the maximum of all elements if A is a vectorv = min (A) ditto - with minimumv = sum (A) ditto - with sumTable 3 Frequently used matrix operations and functions12Transposing a vector changes it from a row to a column or the other way around This idea can be extendedto a matrix where transposing interchanges rows with the corresponding columns as in the examplegtgt A2 A2rsquoA2 =1 2 3 4-1 1 3 5ans =1 -12 13 34 5gtgt size(A2) returns the size (dimensions) of a matrixans =2 4gtgt size(A2rsquo)ans =4 2There exists also some built-in matrices of size specified by the user (see Table 2) A few examples are givenbelowgtgt E = [] an empty matrix of 0-by-0 elementsE =[]gtgt I = eye(3) the identity matrixI =1 0 00 1 00 0 1gtgt B = rand(23) a matrix of random numbers you will get a different one00227 09101 0922200299 00640 03309gtgt O = ones(32)O =1 11 11 1gtgt r = [1 3 -2] R = diag(r) create a diagonal matrix with r on the diagonalR =1 0 00 3 00 0 -2gtgt v = linspace(124) a vector is also an example of a matrixv =10000 13333 16667 20000It is often needed to build a larger matrix from the smaller onesgtgt x = [4 -1] y = [-1 4]x =4

-1y =-1 4gtgt X = [x yrsquo] X consists of the columns x and yrsquoX =4 -1-1 4gtgt T = [ -1 3 4 4 5 6] t = 1313gtgt T2 = [T t] add to T a new row namely the row vector t getting T2T2 =-1 3 44 5 61 2 3gtgt G = [1 5 4 5 0 2] G is a matrix of the 3-by-2 size check size(G)gtgt T3 = [T2 G] T3 consists of T2 and new columns being the colums of GT3 = added at the end of T2-1 3 4 1 54 5 6 4 51 2 3 0 2gtgt [diag(56) ones(32)]ans =5 00 61 11 11 1A part can be extract from a matrix in a similar way as from a vector Each element in the matrix is indexedby a row and a column to which it belongs Mathematically the element from the i-th row and the j-thcolumn of the matrix A is denoted by Aij Matlab provides the A(ij) notationgtgt A = [13 46 79]A =1 2 34 5 67 8 9gtgt A(12) A(23) A(31)ans =2ans =6ans =7gtgt A(43) A is a 3-by-3 matrix Index exceeds matrix dimensionsgtgt A(23) = A(23) + 2A(11)A =1 2 34 5 87 8 9Having defined a matrix it is easy to extended it automatically For the matrix A it can be done eg asfollowsgtgt A(52) = 5 assign 5 to the position (52) the uninitializedA = elements become zeros1 2 34 5 87 8 90 0 00 5 0Different parts of the matrix A can be now extractedgtgt A(2) extract the 2nd column of Aans =25814

05gtgtgt A(34) extract the rows 3rd and 4th of Aans =7 8 90 0 0gtgt A(2312) extract a part of Aans =4 57 8If needed the other zero elements of the matrix A can be also defined by eggtgt A(4) = [1 2 3] assign vector [1 2 3] to the 4th row of Agtgt A(5[13]) = [4 5] a rsquoshortcutrsquo when assigning A(51) = 4 and A(53) = 5gtgt A how does the matrix A look like nowAs you have seen in the examples above it is possible to manipulate (groups of) matrix-elements Thecommands are shortly explained in Table 2Exercise 9Define the matrix A = [14 58 1 1 1 1] Predict and check the result ofgtgt B = A(3)gtgt C = A(1322)gtgt A(11) = 9gtgt A(2313) = [0 0 0 0 0 0]gtgt A(l212) = [l l 3 3]gtgt A = A(3314)_Exercise 10Define the matrices T=[ 3 4 1 8 -4 3] A = [diag(-123) T -4 4 1 2 1] Perform the followingoperations on the matrix Abull extract a vector consisting of the 2nd and 4th elements of the 3rd rowbull find the minimum of the 3rd columnbull find the maximum of the 2nd rowbull compute the sum of the 2nd columbull compute the mean of the 1st and 4th rowsbull extract the submatrix consisting of the 1st and 3rd rows and all columnsbull extract the submatrix consisting of the 1st and 2nd rows and the 3rd 4th and 5th columnsbull compute the total sum of the 1st and 2nd rowsbull add 3 to all elements of the 2nd and 3rd colums_Table 3 shows some frequently used matrix operations and functions A few examples are provided belowgtgt B = rand(23) a matrix of random numbers you will get a different oneB =09501 06068 0891302311 04860 07621gtgt B2 = [1 2 5 1 5 6]gtgt B + B2rsquo add two matrices why B2rsquo is needed instead of B2ans =19501 56068 5891322311 14860 67621gtgt S = ans4 divide all elements of the matrix ans by 4S =04875 14017 1472805578 03715 1690515gtgt C = [1 -1 4 7 0 -1]gtgt B C matrix multiplication is not defined for B and C Error using ==gt Inner matrix dimensions must agreegtgt B C but you can multiply element-by-elementans =09501 -06068 3565216180 0 -07621gtgt D = B Crsquo or you can make the multiplication legal Crsquo is now 3-by-2D =39085 5759627935 08559

gtgt D^3 this is equivalent to D D Dans =1992503 2041413990133 910548gtgt D^3 - 2 do for all elements raise to the power 3 and subtract 2ans =577069 1890638198005 -13731gtgtgtgt r = [1 3 -2]r B2 this is a legal operation r is a 1-by-3 matrix and B2 isans = 3-by-2 matrix B2 r is an illegal operation6 -7Remind that an n-by-k matrix A (having n rows and k columns) can be multiply by another matrix B onlyif B has k rows ie S is of the k-by-m size (m is arbitrary) As a result you get an n-by-m matrixA ˙B = C A 2 Rntimesk B 2 Rktimesm C 2 Rntimesm

RemarkYou can now compute the inner product between two vectors x and y xT y = Pi xi yi in a simple waygtgt f = [-1 3 5] a column vectorgtgt v = [-1 2 7] a column vectorgtgt frsquo v this is the inner productans =42gtgt f vrsquo be careful now a 3-by-1 matrix is multiplied by a 1-by-3gtgt matrix which results in a 3-by-3 matrix (the outer product)ans =1 -2 -7-3 6 21-5 10 35gtgt f v this is an element-by-element multiplication1635gtgt sum (f v) this is an another way to compute the inner productans =42Exercise 11Perform all operations from Table 3 using chosen matrices A and B vector v and scalars k a b n and m _Exercise 12Let A be a random 3 times 3 matrix and b a random 3 times 1 vector Given that Ax = b then x = Aminus1b Find x(there exist at least two possible commands to do this look at Table 3) _optionalThe concept of an empty matrix [] is also very useful in Matlab For instance a few columns or rows canbe removed from a matrix by assigning an empty matrix to it Try for example16Symbol Color Symbol Styley yellow dotted liner red o circlesg green - solid lineb blue - dashdotted lineTable 4 Plot colors and stylesgtgt C = [1 2 3 4 5 6 7 8 1 1 1 1]gtgt D = C D(2) = [] now a copy of C is in D remove the 2nd column of Dgtgt C ([13]) = [] remove the rows 1 and 3 from Cend optional

3 VisualizationMatlab can be used to visualize the results of an experiment Therefore you should define variables each ofthem containing all values of one parameter to plot31 Simple plotsWith the command plot a graphical display can be made plot(y) draws the points (1 y(1)) (2 y(2)) 184 (n y(n)) and connects the points with a straight line plot(xy) does the same for (x(1) y(1)) (x(2) y(2)) (x(n) y(n)) x and y have to be row- or column vectors of equal lengthThe commands loglog semilogx and semilogy are similar to plot except that they use logarithmic axesExercise 13Type the following commands after predicting the resultgtgt x = 0330

gtgt y = 2^[010] this is the same as y = [1 2 4 8 16 32 64 128 256 512 1024]gtgt plot(xy) to get a graphic representationgtgt semilogy(xy) to get logarithmic axesAs you can see the same figure is used for both plot commands The previous function is removed as soonas the next is displayed The command figure gives you an extra figure Repeat the previous commandsbut generate a new figure before plotting the second function so that you can see both functions in separatewindows You can also switch back to a figure using figure(n) where n is its number _Exercise 14Make a plot such that the coordinates (2 6) (25 18) (5 175) (42 125) and (212) are connected by aline _Exercise 15Plot the function y = sin(x) + x minus x cos(x) in two separate figures for the intervals 0 lt x lt 30 andminus100 lt x lt 100 _32 Several functions in one figureWhen more than one function is plotted in one figure it might be useful to use different markers and colors184-188197-201Table 4 shows a few possibilities help plot shows allThere are different ways to get more than one function into a figure The first one is with the command holdon After this command all functions will be plotted in the same figure until the command hold off is usedAn examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt plot (x1 y1 rsquordrsquo)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)17gtgt hold ongtgt plot (x2 y2 rsquoy-rsquo)gtgt plot (x1y1rsquok-rsquo)gtgt hold offA second method to display more than one function in one figure is to plot several functions at the same timeThe next commands will have the same results as the commands in the previous examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt plot (x1 y1rsquordrsquo x2 y2 rsquoy-rsquo x1 y1 rsquok-rsquo)It is also possible to get more than one figure in one figure window With the command subplot the windowcan be horizontally and vertically divided into any number of subfiguresgtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt subplot(131) plot (x1 y1rsquordrsquo)gtgt subplot(132) plot (x2 y2 rsquoy-rsquo)gtgt subplot(133) plot (x1 y1 rsquok-rsquo)optional

33 Other 2D plotting featuresIn the introduction of this chapter some commands similar to plot loglog semilogx and semilogy were201-211 mentioned There are however more ways to display dataExercise 16To get an impression of other visualizations type the following commands and describe the result (note thatthe command figure creates a new figure window)gtgt figure bar plot of a bell shaped curvegtgt x = -290229gtgt bar (x exp (-xx))gtgt figure stairstep plot of a sine wavegtgt x = 002510gtgt stairs (x sin (x))gtgt figure errorbar plotgtgt x = -2012gtgt y = erf (x) error function check help if you are interestedgtgt e = rand (size (x)) 10gtgt errorbar (x y e)

_end optional

34 PrintingBefore printing a figure you made you might want to add some information such as a title or change the189-196 lay-out a little Table 5 shows some of the commands that can be usedExercise 17Plot the functions y1 = sin(4x) y2 = x cos(x) y3 = (x + 1)minus1px for x = 0 025 10 and a single point(x y) = (4 5) in one figure with different colors and styles Make a legend containing the three functionsMake labels for both axes and a title Add a text to the single point saying single point Change the minimumand maximum values of the axes such that function y3 can be looked at in more detail _When the displayed figure is to your liking you can print it to paper The easiest way to do this is to click onFile in the menu-bar and to choose Print If in the print window you click OK your figure will be printed onthe printer indicated in the print window18Command Resultgrid onoff adds a grid to the plot at the tick marks or removes itaxis([xmin xmax ymin ymax]) sets the minimum and maximum values of the axesbox offon removes the axes box or shows itxlabel(rsquotextrsquo) plots the label text on the x axisylabel(rsquotextrsquo) plots the label text on the y axistitle(rsquotextrsquo) plots a title above the graphtext(xyrsquotextrsquo) adds text at the point (xy)gtext(rsquotextrsquo) adds text at a manually (with a mouse) indicated pointlegend(rsquofun1rsquorsquofun2rsquo) plots a legend box (move it with your mouse) to name your functionslegend off deletes the legend boxTable 5 Plot-manipulationsThere is also a print command which can be used to send a figure to a printer or output it to a file Youcan optionally specify a print device (ie an output format such as tiff or postscript) and options that controlvarious characteristics of the printed file (ie which Figure to print etc) You can also print to a file if youspecify the file name If you do not provide an extension print adds one Since they are many parametersthey will not be explained here (check help print to learn more) Instead try to understand the examplesgtgt print -dwinc print the current Figure to the current printer in colorgtgt print -f1 -deps myfileeps print Figure no1 to the file myfileeps in blackgtgt print -f1 -depsc myfileceps print Figure no1 to the file myfilecoleps in colorgtgt print -dtiff myfile1tiff print the current Figure to the file myfile1tiffgtgt print -dpsc myfile1cps print the current Figure to the file myfile1ps in colorgtgt print -f2 -djpeg myfile2 print Figure no2 to the file myfile2jpgExercise 18Exercise with printing (especially to a file) the figure from Exercise 16 _

4 Curve fitting and interpolationThere are two ways to describe data with an analytical function- curve fitting or regression finding a smooth curve that best fits (approximates) the data accordingto a criterion (eg best least square fit) The curve does not have to go through any of the data points- interpolation the data are assumed to be correct desired in a way to describe what happens betweenthe data points In other words given a finite set of points the goal of interpolation is to find a functionfrom a given class of functions (eg polynomials) which passes through the specified pointsThe figure below illustrates the difference between regression (curve fitting) and interpolationminus5 0 5minus6minus4minus20246810fiting a 3rd order polynomialinterpolation

41 Curve fittingMatlab interprets the best fit of a curve by the lsquoleast squares curve fittingrsquo The curve used is restricted153-15619to polynomials With the command polyfit any polynomial can be fitted to the data polyfit (x y n)finds the coefficients of a polynomial of degree n that fits the data (finds the linear relation between x and y)Letrsquos start with finding a linear regression of some datagtgt x = 010gtgt y = [-10 24 102 158 284 276 299 405 483 522 751]gtgt p = polyfit (x y 1) find the fitting polynomial of order 1p = 06772 -03914

The output of polyfit is a row vector of the polynomial coefficients the solution of this example is thereforey = 06772x minus 03914Exercise 19Execute the above example Plot the data and the fitted curve in a figure Determine the 2nd and 9th orderpolynomial of these data as well and display the solution in a figureHint x1 = linspace (xmin xmax n) results in a vector with n element evenly distributed from xmintill xmax z = polyval (p x1) calculates the values of the polynomial for every element of x1 _Exercise 20Define x and y as followsgtgt x = -55gtgt y = 02x^3 - x + 2 a 3rd order polynomialgtgt y = y + randn(111) add some noise to yDetermine the 3rd order polynomial fitting y (note that because of added noise the coefficients are differentthat originally chosen) Try some other polynomials as well Plot the results in a figure _42 InterpolationThe simplest way to examine an interpolation is by displaying the function plots with the command plot157-161 The neighboring data points are connected with straight lines This is called a linear interpolation Whenmore data-points are taken into account the effect of interpolation becomes less visible Analyzegtgt x1 = linspace(0 2pi2)gtgt x2 = linspace(0 2pi4)gtgt x3 = linspace(0 2pi16)gtgt x4 = linspace(0 2pi256)gtgt plot(x1sin(x1)x2sin(x2)x3sin(x3)x4sin(x4))gtgt legend(rsquo2 pointsrsquorsquo4 pointsrsquorsquo16 pointsrsquorsquo256 pointsrsquo)

5 Numerical analysisNumerical analysis can be used whenever it is impossible or very difficult to determine the analytical solutionMatlab can be used to find for example the minimum maximum or integral of a certain function51 Evaluation of a functionAs said before the command plot plots a function by connecting defined data points Sometimes however a168-173 function is constant and not very interesting over some range and then acts unexpectedly wildly over anotherWith plot this function might be misinterpreted The command fplot is then useful An examplegtgt x = 0pi82pigtgt y = sin (8x)gtgt plot (x y rsquobrsquo)gtgt hold ongtgt fplot (rsquosin (8z)rsquo [0 2pi] rsquorrsquo)gtgt title (rsquosin (8z)rsquo)gtgt hold off20Command Resultfplot (rsquofunrsquo [min x max x]) plots the function fun for min x till max xfmin (rsquofunrsquo min x max x) gives the x-value of the miminum of thefunction fun between min x and max xfzero (rsquofunrsquo x0) gives the x-value for which the functionfun is zero in the neighborhood of x0Table 6 Evaluation of a functionExecution of these commands results in a figure with an almost straight blue line and a red sine fplot canalso be used to plot a defined functiongtgt f = rsquosin (8z)rsquogtgt fplot (f [0 2pi] rsquorrsquo)gtgt title (f)Other useful commands for a detailed study of a range of a function are listed in Table 6Exercise 21The command fmax does not exist Use one or more of the commands from Table 6 to determine the maximumof the function x cos(x) for 10 lt x lt 15 _52 Integration and differentiationThe integral- or the surface underneath a 2D function- can be determined with the command trapz trapz173-182 does this by measuring the surface between the x-axis and the -by a straight line connected- data points Theaccuracy of this method depends on the distance between the data pointsgtgt x = 00510 y = 05 sqrt (x) + x sin (x) area1 = trapz (x y)

area1 =181655gtgt x = 000510 y = 05 sqrt (x) + x sin (x) area2 = trapz (x y)area2 =183846Differentiation is done by determining the slope in each data point Numerically this is done by first fitting apolynomial followed by differentiating this functiongtgt x = 010gtgt y = [-10 24 102 -158 284 276 775 35 483 522 751]gtgt p = polyfit (x y 5)p = 00026 -00554 03634 -06888 02747 00877gtgt dp = polyder (p)dp = 00132 -02216 10903 -13776 02747gtgt x1 = linspace (0 10 200)gtgt z = polyval (p x1)gtgt dz = polyval (dp x1)gtgt plot (x y rsquog-rsquo x1 z rsquobrsquo x1 dz rsquorrsquo)gtgt legend (rsquodata pointsrsquo rsquocurve fitrsquo rsquoderivativersquo)Exercise 22Determine the integral and derivative of the 4th polynomial fitted through (xy) with x = [4 5 6 7 8 9 1011 12 13] y = [1284 1200 724 -096 -1116 -2096 -2700 -2496 -956 2544] _

6 Control flowAs you know it is possible to execute more than one command at the same time (see section 11) Theseparate commands should then be divided by commarsquos (to display the output) or by semicolons (to suppress21output display) Control flow loops increase the number of possibilities A control flow structure is a block ofcommands that allows conditional code execution and making loops61 Logical and relational operatorsTo use control flow commands it is necessary to perform operations that result in logical values TRUE or88-91 FALSE In Matlab the result of a logical operation is 1 if it is true and 0 if it is false Table 7 shows therelational and logical operations2 Another way to get to know more about them is to type help relop Therelational operators lt lt= gt gt= == and ~= can be used to compare two arrays of the same size or anarray to a scalar The logical operators amp | and ~ allow for the logical combination or negation of relationaloperators In addition three functions are also available xor any and all (use help to find out more)Important The logical amp and | have the equal precedence in Matlab which means that those operatorsassociate from left to right A common situation isgtgt b = 10gtgt 1 | b gt 0 amp 0ans =0gtgt (1 | b gt 0) amp 0 this indicates the same as aboveans =0gtgt 1 | (b gt 0 amp 0)ans =1This shows that you should always use brackets to indicate in which way the operators should be evaluatedCommand Resulta = (b gt c) a is 1 if b is larger than c Similar are lt gt= and lt=a = (b == c) a is 1 if b is equal to ca = (b ~= c) a is 1 if b is not equal ca = ~b logical complement a is 1 if b is 0a = (b amp c) logical AND a is 1 if b = TRUE AND c = TRUEa = (b | c) logical OR a is 1 if b = TRUE OR c = TRUETable 7 Relational and logical operationsExercise 23Predict and check the result of each of the operations of Table 7 for b = 0 and c = -1 _Exercise 24Define two vectors with seven elements (randn(17)) and perform all logical operations including xor anyand all _Exercise 25While doing logical operations between a vector and a scalar each element of the vector is compared to thescalar Predict and check the result of each logical operator for the vector b = [2 31 -40 0] and the scalarc = 0 _Before moving on check whether you now understand the following relations

gtgt a = randperm(10) a random permutation of the numbers from 1 to 10gtgt b = 110gtgt b - (a lt= 7) subtracts from b a 0-1 vector taking 1 for a lt= 7 and 0 otherwisegtgt (a gt= 2) amp (a lt 4) returns ones at positions where 2 lt= a lt 4gtgt ~(b gt 4) returns ones at positions where b lt= 4gtgt (a == b) | b == 3 returns ones at positions where a is equal to b or b is equal to 3gtgt any (a gt 5) returns 1 when ANY of the a elements are larger than 5gtgt any (b lt 5 amp a gt 8) returns 1 when there in the evaluated expressiongtgt (b lt 5 amp a gt 8) appears at least one 1gtgt all (b gt 2) returns 1 when ALL b elements are larger than 22rdquoequal tordquo in the table on page 88 of rdquoThe Student Edition of Matlabrdquo must be rdquo==rdquo instead of rdquo=rdquo2262 Conditional code executionSelection control structures if-blocks are used to decide which instruction to execute next depending whether117-119 expression is TRUE or not The general description is given below In the examples below the command dispis frequently used This command displays on the screen the text between the quotesbull if endSyntaxif logical_expressionstatement1statement2endExampleif (a gt 0)b = adisp (rsquoa is positiversquo)endbull if else endSyntaxif logical_expressionblock of statementsevaluated if TRUEelseblock of statementsevaluated if FALSEendExampleif (temperature gt 100)disp (rsquoAbove boilingrsquo)toohigh = 1elsedisp (rsquoTemperature is OKrsquo)toohigh = 0endbull if elseif else endSyntaxif logical_expression1block of statements evaluatedif logical_expression1 is TRUEelseif logical_expression2block of statements evaluatedif logical_expression2 is TRUEelseblock of statements evaluatedif no other expression is TRUEendExampleif (height gt 190)disp (rsquovery tallrsquo)elseif (height gt 170)disp (rsquotallrsquo)elseif (height lt 150)disp (rsquosmallrsquo)

elsedisp (rsquoaveragersquo)endRemark To do the exercises below a script m-file will be useful It is an external file that contains asequence of Matlab commands What you need to do is to open an editor enter all commands needed forthe solution of a task save it with the extension rsquomrsquo (eg mytaskm) and then run it from the CommandWindow by typing mytask To open the Matlab editor go to the File menu-bar choose the Open optionand then m-file A new window will appear where you can write your scripts and save them on the disk Allcommands in the script will be executed in Matlab You will learn more on script m-files in section 91Important m-script file must be saved in one of the directories in Matlabrsquos pathAn example A script shortm can be created from the two lines given below and run by calling shortx = 0054plot (x sin(x) rsquo-rsquo)Exercise 26Create a script that asks for a number N and computes the drag coefficient C depending on the Reynoldrsquos23number N (make use of the if elseif construction) The command input might be useful here(read pages 32-33 from rdquoThe Student Edition of Matlabrdquoor use help)C =8gtgtgtltgtgtgt0 N _ 024N N 2 (0 01]24N (1 + 014N07) N 2 (01 1e3]043 N 2 (1e3 5e5]019 minus 8e4N N gt 5e5Check whether your script works correctly Compute the drag coefficient for eg N = -3e3 001 56 1e3 3e6(remember that eg 3e3 is a Matlab notation of 3 _ 103) _Exercise 27Write a script that asks for an integer and checks whether it can be divided by 2 or 3 Consider all possibilitiessuch as divisible by both 2 and 3 divisible by 2 and not by 3 etc (use the command rem) _Another selection structure is switch which switches between several cases depending on an expression which119-120 is either a scalar or a stringSyntaxswitch expressioncase choice1block of commands1case choice2a choice2bblock of commands2otherwiseblock of commandsendExamplemethod = 2switch methodcase 12disp(rsquoMethod is linearrsquo)case 3disp(rsquoMethod is cubicrsquo)case 4disp(rsquoMethod is nearestrsquo)otherwisedisp(rsquoUnknown methodrsquo)endThe statements following the first case where the expression matches the choice are executed Thisconstruction can be very handy to avoid long if elseif else end constructions Theexpression can be a scalar or a string A scalar expression matches a choice if expression == choice Astring expression matches a choice if strcmp(expression choice) returns 1 (is true) (strcmp is a commandcomparing two strings)Important Note that the switch-construction only allows the execution of one group of commandsExercise 28Assume that the months are represented by numbers from 1 to 12 Write a script that asks you to provide a

month and returns the number of days in that particular month Alternatively write a script that asks youto provide a month name (eg rsquoJunersquo) instead of a number Use the switch-construction _63 LoopsIteration control structures loops are used to repeat a block of statements until some condition is met Two114-117 types of loops existbull the for loop that repeats a group of statements a fixed number of timesSyntaxfor index = firststeplastblock of statementsendExamplesumx = 0for i=1length(x)sumx = sumx + x(i)end24You can specify any step including a negative value The index of the for-loop can be also a vectorSee some examples of possible variationsExample 1for i=12nendExample 2for i=n-13endExample 3for x=0054disp(x^2)endExample 4for x=[25 9 81]disp(sqrt(x))endbull while loop which evaluates a group of commands as long as expression is TRUESyntaxwhile expressionstatement1statement2statement3endExampleN = 100iter = 1msum = 0while iter lt= Nmsum = msum + iteriter = iter + 1endExercise 29Given the vectors x and y write a script computing the a matrix whose elements should be created accordingto a formula given below (make use of the length command to check the number of elements in both vectors)- aij = yixj (make sure that a division by zero will not occur)- bij = xi _ yj

- cij = 1 max (xi yj)_Exercise 30Determine the sum of the first 50 squared numbers with a control loop _Exercise 31Write a script to find the largest value n such that the sum p13 + p23 + + pn3 is less than 1000 _optionalExercise 32Write a script that transposes a matrix A Check its correctness with the Matlab operation Arsquo _Exercise 33

Write a script that asks for a temperature in degrees Celsius tc and computes the equivalent temperature indegrees Fahrenheit tf (use the formula tf = 95 _ tc + 32) The script should keep running until no numberis provided to convert The functions input and isempty (use help to learn more) should be useful here _end optional

64 Evaluation of logical and relational expressions in the control flow structuresThe relational and logical expressions may become more complicated It is not difficult to operate on them ifyou understand how they are evaluated To explain more details let us consider the following exampleif (~isempty(data)) amp (max(data) lt 5)endThis construction of the if-block is necessary to avoid comparison if data happens to be an empty matrix Insuch a case you cannot evaluate any expression and Matlab gives an error The amp operator returns 1 only ifboth expressions ~isempty (data) and max(data) lt 5 are true and 0 otherwise When data is an emptymatrix the next expression is not evaluated since the whole amp-expression is already known to be false Thesecond expression is checked only if data is a non-empty matrix Remember to put logical expression unitsbetween brackets to avoid wrong evaluations25Important The fact that computers make use of floating-point arithmetic means that often you should becareful when comparing two floating-point numbers just byif (x == y)end(Of course such a construction is allowed eg when you know that x and y represent integers) Instead of theabove construction you may try using thisif (abs (x - y) lt tolerance) eg tolerance = 1e-10endExercise 34Consider the following examplemax_iter = 50tolerance = 1e-4iter = 0xold = 01x = 1while (abs (x - xold) gt tolerance) amp (iter lt max_iter)xold = xx = cos(xold)iter = iter + 1endThis short program tries to solve the equation cos(x) = x (x is the solution found) Make the script solve cosfrom the presented code Note that the while-loop is repeated as long as both conditions are true If eitherthe condition (|x - xold| lt= tolerance) or (iter gt= max iter) is fulfilled then the loop is quitted Runthe script solve cos for different tolerance parameters eg 1e-3 1e-6 1e-8 1e-10 etc Use format long tocheck more precisely how much the found x is really different from cos(x) For each tolerance value checkthe number of performed iterations (iter value) _Exercise 35Create the script solve cos2 which is equal to the one given replacing the while-loop condition bywhile (abs (x - xold) gt tolerance) | (iter lt max_iter)Try to understand the difference and confirm your expectations by running solve cos2 What happens toiter _optional

65 Numerical analysis and the control flow structuresTake a look at the problem of a Taylor expansion The series will be determined numerically until the additionalterms are smaller than a defined precision Look at the Taylor expansion of 11minusx = 1 + x + x2 + withx = 042s = 0 x = 1 s = 0 x = 1x0 = 042 x0 = 042while (x gt 1e-6) or while (x gt (1e-6)s)s = s + x s = s + xx = x x0 x = x x0end endThe approximation of 11minusx is returned in s (first letter of sum) In the first case (on the left) the iteration

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 10: Introduction to Programming Using Matlab

variable is always of the double type You can change this type by converting it into eg the single type 11a variable a is converted into a different type by performing eg a = single(a) a = int16(a) etc8In some cases when huge matrices should be handled and precision is not very important this might be a wayto proceed Also when only integers are taken into consideration it might be useful to convert the doublerepresentations into eg int16 or int321 integer types Since most computations should be performed with ahigh accuracy Matlab automatically chooses the double type It means that real numbers are approximatedwith the highest possible precision However it is important to emphasize that integer numbers are alwaysrepresented exactly no matter which numeric type is usedBear in mind that undefined values cannot be assigned to a variable So the following is not possiblegtgt clear x to make sure that x does not existgtgt fun = x^2 + 4 sin (x)It becomes possible bygtgt x = pi 3 fun = x^2 + 4 sin (x)Exercise 5Predict the result ofx = pi 3 x = x - 1 x = x + 5 x = abs(x) xCheck your prediction by performing these commands in Matlab _Exercise 6Here are some examples of different types of Matlab variables You do not need to understand them all nowsince you will learn more about them during the course Create them manually in Matlabgtgt this_is_my_very_simple_variable_today = 5 a number check what happens since thegtgt name is very long (gt 31 characters)gtgt 2t = 8 what is the problem with this commandgtgt this_is_a_matrix = [1 2 3 4 5 6] a matrixgtgt c = rsquoErsquo a charactergtgt str = rsquoHello worldrsquo a stringgtgt m = [rsquoJrsquorsquoorsquorsquohrsquorsquonrsquo] try to guess what it isCheck the types by using the command whos Use clear ltnamegt to remove a variable from the workspace _Exercise 7In addition to creating variables by assigning values to them a few other ways exist For instance there is anumber of built-in variables eg ans pi eps i inf or nan Find out what value is assigned to each of these74584 built-in variables _24 VectorsRow vectors are lists of numbers separated either by commas or by spaces They are examples of simple arrays41-49 The number of entries is known as the length of the vector (the command length exists as well) Their entitiesare referred to as elements or components The entries must be enclosed in [ ]gtgt v = [-1 sin(3) 7]v =-10000 01411 70000gtgt length(v)ans =3A number of operations can be done on vectors A vector can be multiplied by a scalar or addedsubtractedtofrom another vector with the same length or a number can be addedsubtracted tofrom a vector Allthese operations are carried out element-by-element Vectors can be also built from the already existing onesgtgt v = [-1 2 7] w = [2 3 4]gtgt z = v + w an element-by-element sumz =1 5 119gtgt v3 = v + 2 add 2 to all elements of vector v3v3 =1 4 9gtgt t = [2v -w]ans =-2 4 14 -2 -3 -4Also a particular value can be changed or displayedgtgt v(2) = -1 w(2) change the 2nd value of v display the 2nd value of wv =-1 -1 7ans =

3A colon notation is an important shortcut used when producing row vectors (see Table 3 and help colon)gtgt 25ans =2 3 4 5gtgt -23ans =-2 -1 0 1 2 3In general firststeplast produces a vector of entities with the value first incrementing by the stepuntil it reaches lastgtgt 020524ans =02000 07000 12000 17000 22000gtgt -3310ans =-3 0 3 6 9gtgt 15-05-05 negative step is also possibleans =15000 10000 05000 0 -05000Parts of vectors can be extracted by using a colon notationgtgt r = [-126 2 3 -2] -126 =gt -1 1 3 5r =-1 1 3 5 2 3 -2gtgt r(36) get elements of r which are on the positions from 3 to 6ans =3 5 2 3gtgt r(125) get elements of r which are on the positions from 1 to 5 taken with the step of 2ans =-1 3 2gtgt r(5-12) what will you get hereTo create column vectors you should separate entries by a semicolon () or by new linesgtgt f = [-1 3 5]f =-135The same operations as on row vectors can be done on column vectors However you cannot for exampleadd a column vector to a row vector To do that you need an operation called transposing which converts acolumn vector into a row vector and vice versa10gtgt f = [-1 3 5] a column vectorgtgt frsquo frsquo is a row vectorans =-1 3 5gtgt v = [-1 2 7] a row vectorgtgt f + v you cannot add a column vector f to a row vector v Error using ==gt +Matrix dimensions must agreegtgt frsquo + vans =-2 5 12gtgt f + vrsquoans =-2512If x is a complex vector than xrsquo gives the conjugate transpose of x eggtgt x = [1+2i -1+i]x =10000 + 20000i -10000 + 10000igtgt xrsquo this is the conjugate transposeans =10000 - 20000i-10000 - 10000i

gtgt xrsquo this is the rsquonormalrsquo transposeans =10000 + 20000i-10000 + 10000iExercise 8Exercise to become acquainted with operating on row and column vectors Enter all examples given in thissection and make new variations yourself Exercise with the colon notation approach as well _25 MatricesAn ntimesk matrix is a rectangular array of numbers having n rows and k columns Defining a matrix in Matlabis similar to defining a vector The generalization is straightforward if you know that a matrix consists of row49-6175-86vectors (or column vectors) Commas or spaces are used to separate elements in a row and semicolons areused to separate individual rows For example the matrix A =01 2 34 5 67 8 91Ais defined asgtgt A = [1 2 3 4 5 6 7 8 9] row by row inputA =1 2 34 5 67 8 9Another examples are for instancegtgt A2 = [14 -125]A2 =1 2 3 4-1 1 3 5gtgt A3 = [1 3-4 7]A3 =1 3-4 711Command ResultA(ij) Aij

A(j) j-th column of AA(i) i-th row of AA(klmn) (l minus k + 1) times (n minus m + 1) matrix with elements Aij with k _ i _ l m _ j _ nv(ij)rsquo rsquovector-partrsquo (vi vi+1 vj) of vector vTable 2 Manipulation of (groups of) matrix-elementsCommand Resultn = rank (A) n becomes the rank of matrix Ax = det (A) x becomes the determinant of matrix AC = size (A) C becomes a row-vector with 2 elements the number of rows and columns of Ax = trace (A) x becomes the trace (sum of diagonal elements) of matrix Ax = norm (v) x becomes the length of vector vC = A + B sum of two matricesC = A - B subtraction of two matricesC = A B multiplication of two matricesC = A B rdquoelement-by-elementrdquo multiplication (A and B are of equal size)C = A ^ k power of a matrix (k 2 Z can also be used for Aminus1)C = A ^ k rdquoelement-by-elementrdquo power of a matrixC = Arsquo the transposed of a matrix AT

C = A B rdquoelement-by-elementrdquo division (A and B are of equal size)U = A B finds the solution that minimizes the squared error in Ax minus BU = B A solution of XA = B analogous to the previous commandC = inv (A) C becomes the inverse of AC = null (A) C is an orthonormal basis for the null space of Aobtained from the singular value decompositionC = orth (A) C is an orthonormal basis for the range of AC = rref (A) C is the reduced row echelon form of AL = eig (A) L is a vector containing the -possibly complex- eigenvalues of a square matrix A[X D] = eig (A) produces a diagonal matrix D of eigenvalues and a full matrix X

whose columns are the corresponding eigenvectors of AS = svd (A) S is a vector containing the singular values of A[U S V] = svd (A) S is a diagonal matrix of the same dimension as Awith nonnegative diagonal elements in decreasing orderThe columns U and V are the accompanying singular vectorsx = linspace(a b n) generates a vector x of n equally spaced points between a and bx = logspace(a b n) generates a vector x starting at 10a and ended at 10b containing n valuesA = diag (v) gives a diagonal matrix with the elements v1 v2 vn on the diagonalA = eye (n) A is a n times n identity matrixA = zeros (n m) A is a n times m matrix with zeros (default m = n)A = rand (n m) A is a n times m matrix with elements uniformly distributed between 0 and 1A = randn (n m) ditto - with elements standard normal distributedv = max (A) v becomes a vector with the maximum value of the elements in each column of Aor v is the maximum of all elements if A is a vectorv = min (A) ditto - with minimumv = sum (A) ditto - with sumTable 3 Frequently used matrix operations and functions12Transposing a vector changes it from a row to a column or the other way around This idea can be extendedto a matrix where transposing interchanges rows with the corresponding columns as in the examplegtgt A2 A2rsquoA2 =1 2 3 4-1 1 3 5ans =1 -12 13 34 5gtgt size(A2) returns the size (dimensions) of a matrixans =2 4gtgt size(A2rsquo)ans =4 2There exists also some built-in matrices of size specified by the user (see Table 2) A few examples are givenbelowgtgt E = [] an empty matrix of 0-by-0 elementsE =[]gtgt I = eye(3) the identity matrixI =1 0 00 1 00 0 1gtgt B = rand(23) a matrix of random numbers you will get a different one00227 09101 0922200299 00640 03309gtgt O = ones(32)O =1 11 11 1gtgt r = [1 3 -2] R = diag(r) create a diagonal matrix with r on the diagonalR =1 0 00 3 00 0 -2gtgt v = linspace(124) a vector is also an example of a matrixv =10000 13333 16667 20000It is often needed to build a larger matrix from the smaller onesgtgt x = [4 -1] y = [-1 4]x =4

-1y =-1 4gtgt X = [x yrsquo] X consists of the columns x and yrsquoX =4 -1-1 4gtgt T = [ -1 3 4 4 5 6] t = 1313gtgt T2 = [T t] add to T a new row namely the row vector t getting T2T2 =-1 3 44 5 61 2 3gtgt G = [1 5 4 5 0 2] G is a matrix of the 3-by-2 size check size(G)gtgt T3 = [T2 G] T3 consists of T2 and new columns being the colums of GT3 = added at the end of T2-1 3 4 1 54 5 6 4 51 2 3 0 2gtgt [diag(56) ones(32)]ans =5 00 61 11 11 1A part can be extract from a matrix in a similar way as from a vector Each element in the matrix is indexedby a row and a column to which it belongs Mathematically the element from the i-th row and the j-thcolumn of the matrix A is denoted by Aij Matlab provides the A(ij) notationgtgt A = [13 46 79]A =1 2 34 5 67 8 9gtgt A(12) A(23) A(31)ans =2ans =6ans =7gtgt A(43) A is a 3-by-3 matrix Index exceeds matrix dimensionsgtgt A(23) = A(23) + 2A(11)A =1 2 34 5 87 8 9Having defined a matrix it is easy to extended it automatically For the matrix A it can be done eg asfollowsgtgt A(52) = 5 assign 5 to the position (52) the uninitializedA = elements become zeros1 2 34 5 87 8 90 0 00 5 0Different parts of the matrix A can be now extractedgtgt A(2) extract the 2nd column of Aans =25814

05gtgtgt A(34) extract the rows 3rd and 4th of Aans =7 8 90 0 0gtgt A(2312) extract a part of Aans =4 57 8If needed the other zero elements of the matrix A can be also defined by eggtgt A(4) = [1 2 3] assign vector [1 2 3] to the 4th row of Agtgt A(5[13]) = [4 5] a rsquoshortcutrsquo when assigning A(51) = 4 and A(53) = 5gtgt A how does the matrix A look like nowAs you have seen in the examples above it is possible to manipulate (groups of) matrix-elements Thecommands are shortly explained in Table 2Exercise 9Define the matrix A = [14 58 1 1 1 1] Predict and check the result ofgtgt B = A(3)gtgt C = A(1322)gtgt A(11) = 9gtgt A(2313) = [0 0 0 0 0 0]gtgt A(l212) = [l l 3 3]gtgt A = A(3314)_Exercise 10Define the matrices T=[ 3 4 1 8 -4 3] A = [diag(-123) T -4 4 1 2 1] Perform the followingoperations on the matrix Abull extract a vector consisting of the 2nd and 4th elements of the 3rd rowbull find the minimum of the 3rd columnbull find the maximum of the 2nd rowbull compute the sum of the 2nd columbull compute the mean of the 1st and 4th rowsbull extract the submatrix consisting of the 1st and 3rd rows and all columnsbull extract the submatrix consisting of the 1st and 2nd rows and the 3rd 4th and 5th columnsbull compute the total sum of the 1st and 2nd rowsbull add 3 to all elements of the 2nd and 3rd colums_Table 3 shows some frequently used matrix operations and functions A few examples are provided belowgtgt B = rand(23) a matrix of random numbers you will get a different oneB =09501 06068 0891302311 04860 07621gtgt B2 = [1 2 5 1 5 6]gtgt B + B2rsquo add two matrices why B2rsquo is needed instead of B2ans =19501 56068 5891322311 14860 67621gtgt S = ans4 divide all elements of the matrix ans by 4S =04875 14017 1472805578 03715 1690515gtgt C = [1 -1 4 7 0 -1]gtgt B C matrix multiplication is not defined for B and C Error using ==gt Inner matrix dimensions must agreegtgt B C but you can multiply element-by-elementans =09501 -06068 3565216180 0 -07621gtgt D = B Crsquo or you can make the multiplication legal Crsquo is now 3-by-2D =39085 5759627935 08559

gtgt D^3 this is equivalent to D D Dans =1992503 2041413990133 910548gtgt D^3 - 2 do for all elements raise to the power 3 and subtract 2ans =577069 1890638198005 -13731gtgtgtgt r = [1 3 -2]r B2 this is a legal operation r is a 1-by-3 matrix and B2 isans = 3-by-2 matrix B2 r is an illegal operation6 -7Remind that an n-by-k matrix A (having n rows and k columns) can be multiply by another matrix B onlyif B has k rows ie S is of the k-by-m size (m is arbitrary) As a result you get an n-by-m matrixA ˙B = C A 2 Rntimesk B 2 Rktimesm C 2 Rntimesm

RemarkYou can now compute the inner product between two vectors x and y xT y = Pi xi yi in a simple waygtgt f = [-1 3 5] a column vectorgtgt v = [-1 2 7] a column vectorgtgt frsquo v this is the inner productans =42gtgt f vrsquo be careful now a 3-by-1 matrix is multiplied by a 1-by-3gtgt matrix which results in a 3-by-3 matrix (the outer product)ans =1 -2 -7-3 6 21-5 10 35gtgt f v this is an element-by-element multiplication1635gtgt sum (f v) this is an another way to compute the inner productans =42Exercise 11Perform all operations from Table 3 using chosen matrices A and B vector v and scalars k a b n and m _Exercise 12Let A be a random 3 times 3 matrix and b a random 3 times 1 vector Given that Ax = b then x = Aminus1b Find x(there exist at least two possible commands to do this look at Table 3) _optionalThe concept of an empty matrix [] is also very useful in Matlab For instance a few columns or rows canbe removed from a matrix by assigning an empty matrix to it Try for example16Symbol Color Symbol Styley yellow dotted liner red o circlesg green - solid lineb blue - dashdotted lineTable 4 Plot colors and stylesgtgt C = [1 2 3 4 5 6 7 8 1 1 1 1]gtgt D = C D(2) = [] now a copy of C is in D remove the 2nd column of Dgtgt C ([13]) = [] remove the rows 1 and 3 from Cend optional

3 VisualizationMatlab can be used to visualize the results of an experiment Therefore you should define variables each ofthem containing all values of one parameter to plot31 Simple plotsWith the command plot a graphical display can be made plot(y) draws the points (1 y(1)) (2 y(2)) 184 (n y(n)) and connects the points with a straight line plot(xy) does the same for (x(1) y(1)) (x(2) y(2)) (x(n) y(n)) x and y have to be row- or column vectors of equal lengthThe commands loglog semilogx and semilogy are similar to plot except that they use logarithmic axesExercise 13Type the following commands after predicting the resultgtgt x = 0330

gtgt y = 2^[010] this is the same as y = [1 2 4 8 16 32 64 128 256 512 1024]gtgt plot(xy) to get a graphic representationgtgt semilogy(xy) to get logarithmic axesAs you can see the same figure is used for both plot commands The previous function is removed as soonas the next is displayed The command figure gives you an extra figure Repeat the previous commandsbut generate a new figure before plotting the second function so that you can see both functions in separatewindows You can also switch back to a figure using figure(n) where n is its number _Exercise 14Make a plot such that the coordinates (2 6) (25 18) (5 175) (42 125) and (212) are connected by aline _Exercise 15Plot the function y = sin(x) + x minus x cos(x) in two separate figures for the intervals 0 lt x lt 30 andminus100 lt x lt 100 _32 Several functions in one figureWhen more than one function is plotted in one figure it might be useful to use different markers and colors184-188197-201Table 4 shows a few possibilities help plot shows allThere are different ways to get more than one function into a figure The first one is with the command holdon After this command all functions will be plotted in the same figure until the command hold off is usedAn examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt plot (x1 y1 rsquordrsquo)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)17gtgt hold ongtgt plot (x2 y2 rsquoy-rsquo)gtgt plot (x1y1rsquok-rsquo)gtgt hold offA second method to display more than one function in one figure is to plot several functions at the same timeThe next commands will have the same results as the commands in the previous examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt plot (x1 y1rsquordrsquo x2 y2 rsquoy-rsquo x1 y1 rsquok-rsquo)It is also possible to get more than one figure in one figure window With the command subplot the windowcan be horizontally and vertically divided into any number of subfiguresgtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt subplot(131) plot (x1 y1rsquordrsquo)gtgt subplot(132) plot (x2 y2 rsquoy-rsquo)gtgt subplot(133) plot (x1 y1 rsquok-rsquo)optional

33 Other 2D plotting featuresIn the introduction of this chapter some commands similar to plot loglog semilogx and semilogy were201-211 mentioned There are however more ways to display dataExercise 16To get an impression of other visualizations type the following commands and describe the result (note thatthe command figure creates a new figure window)gtgt figure bar plot of a bell shaped curvegtgt x = -290229gtgt bar (x exp (-xx))gtgt figure stairstep plot of a sine wavegtgt x = 002510gtgt stairs (x sin (x))gtgt figure errorbar plotgtgt x = -2012gtgt y = erf (x) error function check help if you are interestedgtgt e = rand (size (x)) 10gtgt errorbar (x y e)

_end optional

34 PrintingBefore printing a figure you made you might want to add some information such as a title or change the189-196 lay-out a little Table 5 shows some of the commands that can be usedExercise 17Plot the functions y1 = sin(4x) y2 = x cos(x) y3 = (x + 1)minus1px for x = 0 025 10 and a single point(x y) = (4 5) in one figure with different colors and styles Make a legend containing the three functionsMake labels for both axes and a title Add a text to the single point saying single point Change the minimumand maximum values of the axes such that function y3 can be looked at in more detail _When the displayed figure is to your liking you can print it to paper The easiest way to do this is to click onFile in the menu-bar and to choose Print If in the print window you click OK your figure will be printed onthe printer indicated in the print window18Command Resultgrid onoff adds a grid to the plot at the tick marks or removes itaxis([xmin xmax ymin ymax]) sets the minimum and maximum values of the axesbox offon removes the axes box or shows itxlabel(rsquotextrsquo) plots the label text on the x axisylabel(rsquotextrsquo) plots the label text on the y axistitle(rsquotextrsquo) plots a title above the graphtext(xyrsquotextrsquo) adds text at the point (xy)gtext(rsquotextrsquo) adds text at a manually (with a mouse) indicated pointlegend(rsquofun1rsquorsquofun2rsquo) plots a legend box (move it with your mouse) to name your functionslegend off deletes the legend boxTable 5 Plot-manipulationsThere is also a print command which can be used to send a figure to a printer or output it to a file Youcan optionally specify a print device (ie an output format such as tiff or postscript) and options that controlvarious characteristics of the printed file (ie which Figure to print etc) You can also print to a file if youspecify the file name If you do not provide an extension print adds one Since they are many parametersthey will not be explained here (check help print to learn more) Instead try to understand the examplesgtgt print -dwinc print the current Figure to the current printer in colorgtgt print -f1 -deps myfileeps print Figure no1 to the file myfileeps in blackgtgt print -f1 -depsc myfileceps print Figure no1 to the file myfilecoleps in colorgtgt print -dtiff myfile1tiff print the current Figure to the file myfile1tiffgtgt print -dpsc myfile1cps print the current Figure to the file myfile1ps in colorgtgt print -f2 -djpeg myfile2 print Figure no2 to the file myfile2jpgExercise 18Exercise with printing (especially to a file) the figure from Exercise 16 _

4 Curve fitting and interpolationThere are two ways to describe data with an analytical function- curve fitting or regression finding a smooth curve that best fits (approximates) the data accordingto a criterion (eg best least square fit) The curve does not have to go through any of the data points- interpolation the data are assumed to be correct desired in a way to describe what happens betweenthe data points In other words given a finite set of points the goal of interpolation is to find a functionfrom a given class of functions (eg polynomials) which passes through the specified pointsThe figure below illustrates the difference between regression (curve fitting) and interpolationminus5 0 5minus6minus4minus20246810fiting a 3rd order polynomialinterpolation

41 Curve fittingMatlab interprets the best fit of a curve by the lsquoleast squares curve fittingrsquo The curve used is restricted153-15619to polynomials With the command polyfit any polynomial can be fitted to the data polyfit (x y n)finds the coefficients of a polynomial of degree n that fits the data (finds the linear relation between x and y)Letrsquos start with finding a linear regression of some datagtgt x = 010gtgt y = [-10 24 102 158 284 276 299 405 483 522 751]gtgt p = polyfit (x y 1) find the fitting polynomial of order 1p = 06772 -03914

The output of polyfit is a row vector of the polynomial coefficients the solution of this example is thereforey = 06772x minus 03914Exercise 19Execute the above example Plot the data and the fitted curve in a figure Determine the 2nd and 9th orderpolynomial of these data as well and display the solution in a figureHint x1 = linspace (xmin xmax n) results in a vector with n element evenly distributed from xmintill xmax z = polyval (p x1) calculates the values of the polynomial for every element of x1 _Exercise 20Define x and y as followsgtgt x = -55gtgt y = 02x^3 - x + 2 a 3rd order polynomialgtgt y = y + randn(111) add some noise to yDetermine the 3rd order polynomial fitting y (note that because of added noise the coefficients are differentthat originally chosen) Try some other polynomials as well Plot the results in a figure _42 InterpolationThe simplest way to examine an interpolation is by displaying the function plots with the command plot157-161 The neighboring data points are connected with straight lines This is called a linear interpolation Whenmore data-points are taken into account the effect of interpolation becomes less visible Analyzegtgt x1 = linspace(0 2pi2)gtgt x2 = linspace(0 2pi4)gtgt x3 = linspace(0 2pi16)gtgt x4 = linspace(0 2pi256)gtgt plot(x1sin(x1)x2sin(x2)x3sin(x3)x4sin(x4))gtgt legend(rsquo2 pointsrsquorsquo4 pointsrsquorsquo16 pointsrsquorsquo256 pointsrsquo)

5 Numerical analysisNumerical analysis can be used whenever it is impossible or very difficult to determine the analytical solutionMatlab can be used to find for example the minimum maximum or integral of a certain function51 Evaluation of a functionAs said before the command plot plots a function by connecting defined data points Sometimes however a168-173 function is constant and not very interesting over some range and then acts unexpectedly wildly over anotherWith plot this function might be misinterpreted The command fplot is then useful An examplegtgt x = 0pi82pigtgt y = sin (8x)gtgt plot (x y rsquobrsquo)gtgt hold ongtgt fplot (rsquosin (8z)rsquo [0 2pi] rsquorrsquo)gtgt title (rsquosin (8z)rsquo)gtgt hold off20Command Resultfplot (rsquofunrsquo [min x max x]) plots the function fun for min x till max xfmin (rsquofunrsquo min x max x) gives the x-value of the miminum of thefunction fun between min x and max xfzero (rsquofunrsquo x0) gives the x-value for which the functionfun is zero in the neighborhood of x0Table 6 Evaluation of a functionExecution of these commands results in a figure with an almost straight blue line and a red sine fplot canalso be used to plot a defined functiongtgt f = rsquosin (8z)rsquogtgt fplot (f [0 2pi] rsquorrsquo)gtgt title (f)Other useful commands for a detailed study of a range of a function are listed in Table 6Exercise 21The command fmax does not exist Use one or more of the commands from Table 6 to determine the maximumof the function x cos(x) for 10 lt x lt 15 _52 Integration and differentiationThe integral- or the surface underneath a 2D function- can be determined with the command trapz trapz173-182 does this by measuring the surface between the x-axis and the -by a straight line connected- data points Theaccuracy of this method depends on the distance between the data pointsgtgt x = 00510 y = 05 sqrt (x) + x sin (x) area1 = trapz (x y)

area1 =181655gtgt x = 000510 y = 05 sqrt (x) + x sin (x) area2 = trapz (x y)area2 =183846Differentiation is done by determining the slope in each data point Numerically this is done by first fitting apolynomial followed by differentiating this functiongtgt x = 010gtgt y = [-10 24 102 -158 284 276 775 35 483 522 751]gtgt p = polyfit (x y 5)p = 00026 -00554 03634 -06888 02747 00877gtgt dp = polyder (p)dp = 00132 -02216 10903 -13776 02747gtgt x1 = linspace (0 10 200)gtgt z = polyval (p x1)gtgt dz = polyval (dp x1)gtgt plot (x y rsquog-rsquo x1 z rsquobrsquo x1 dz rsquorrsquo)gtgt legend (rsquodata pointsrsquo rsquocurve fitrsquo rsquoderivativersquo)Exercise 22Determine the integral and derivative of the 4th polynomial fitted through (xy) with x = [4 5 6 7 8 9 1011 12 13] y = [1284 1200 724 -096 -1116 -2096 -2700 -2496 -956 2544] _

6 Control flowAs you know it is possible to execute more than one command at the same time (see section 11) Theseparate commands should then be divided by commarsquos (to display the output) or by semicolons (to suppress21output display) Control flow loops increase the number of possibilities A control flow structure is a block ofcommands that allows conditional code execution and making loops61 Logical and relational operatorsTo use control flow commands it is necessary to perform operations that result in logical values TRUE or88-91 FALSE In Matlab the result of a logical operation is 1 if it is true and 0 if it is false Table 7 shows therelational and logical operations2 Another way to get to know more about them is to type help relop Therelational operators lt lt= gt gt= == and ~= can be used to compare two arrays of the same size or anarray to a scalar The logical operators amp | and ~ allow for the logical combination or negation of relationaloperators In addition three functions are also available xor any and all (use help to find out more)Important The logical amp and | have the equal precedence in Matlab which means that those operatorsassociate from left to right A common situation isgtgt b = 10gtgt 1 | b gt 0 amp 0ans =0gtgt (1 | b gt 0) amp 0 this indicates the same as aboveans =0gtgt 1 | (b gt 0 amp 0)ans =1This shows that you should always use brackets to indicate in which way the operators should be evaluatedCommand Resulta = (b gt c) a is 1 if b is larger than c Similar are lt gt= and lt=a = (b == c) a is 1 if b is equal to ca = (b ~= c) a is 1 if b is not equal ca = ~b logical complement a is 1 if b is 0a = (b amp c) logical AND a is 1 if b = TRUE AND c = TRUEa = (b | c) logical OR a is 1 if b = TRUE OR c = TRUETable 7 Relational and logical operationsExercise 23Predict and check the result of each of the operations of Table 7 for b = 0 and c = -1 _Exercise 24Define two vectors with seven elements (randn(17)) and perform all logical operations including xor anyand all _Exercise 25While doing logical operations between a vector and a scalar each element of the vector is compared to thescalar Predict and check the result of each logical operator for the vector b = [2 31 -40 0] and the scalarc = 0 _Before moving on check whether you now understand the following relations

gtgt a = randperm(10) a random permutation of the numbers from 1 to 10gtgt b = 110gtgt b - (a lt= 7) subtracts from b a 0-1 vector taking 1 for a lt= 7 and 0 otherwisegtgt (a gt= 2) amp (a lt 4) returns ones at positions where 2 lt= a lt 4gtgt ~(b gt 4) returns ones at positions where b lt= 4gtgt (a == b) | b == 3 returns ones at positions where a is equal to b or b is equal to 3gtgt any (a gt 5) returns 1 when ANY of the a elements are larger than 5gtgt any (b lt 5 amp a gt 8) returns 1 when there in the evaluated expressiongtgt (b lt 5 amp a gt 8) appears at least one 1gtgt all (b gt 2) returns 1 when ALL b elements are larger than 22rdquoequal tordquo in the table on page 88 of rdquoThe Student Edition of Matlabrdquo must be rdquo==rdquo instead of rdquo=rdquo2262 Conditional code executionSelection control structures if-blocks are used to decide which instruction to execute next depending whether117-119 expression is TRUE or not The general description is given below In the examples below the command dispis frequently used This command displays on the screen the text between the quotesbull if endSyntaxif logical_expressionstatement1statement2endExampleif (a gt 0)b = adisp (rsquoa is positiversquo)endbull if else endSyntaxif logical_expressionblock of statementsevaluated if TRUEelseblock of statementsevaluated if FALSEendExampleif (temperature gt 100)disp (rsquoAbove boilingrsquo)toohigh = 1elsedisp (rsquoTemperature is OKrsquo)toohigh = 0endbull if elseif else endSyntaxif logical_expression1block of statements evaluatedif logical_expression1 is TRUEelseif logical_expression2block of statements evaluatedif logical_expression2 is TRUEelseblock of statements evaluatedif no other expression is TRUEendExampleif (height gt 190)disp (rsquovery tallrsquo)elseif (height gt 170)disp (rsquotallrsquo)elseif (height lt 150)disp (rsquosmallrsquo)

elsedisp (rsquoaveragersquo)endRemark To do the exercises below a script m-file will be useful It is an external file that contains asequence of Matlab commands What you need to do is to open an editor enter all commands needed forthe solution of a task save it with the extension rsquomrsquo (eg mytaskm) and then run it from the CommandWindow by typing mytask To open the Matlab editor go to the File menu-bar choose the Open optionand then m-file A new window will appear where you can write your scripts and save them on the disk Allcommands in the script will be executed in Matlab You will learn more on script m-files in section 91Important m-script file must be saved in one of the directories in Matlabrsquos pathAn example A script shortm can be created from the two lines given below and run by calling shortx = 0054plot (x sin(x) rsquo-rsquo)Exercise 26Create a script that asks for a number N and computes the drag coefficient C depending on the Reynoldrsquos23number N (make use of the if elseif construction) The command input might be useful here(read pages 32-33 from rdquoThe Student Edition of Matlabrdquoor use help)C =8gtgtgtltgtgtgt0 N _ 024N N 2 (0 01]24N (1 + 014N07) N 2 (01 1e3]043 N 2 (1e3 5e5]019 minus 8e4N N gt 5e5Check whether your script works correctly Compute the drag coefficient for eg N = -3e3 001 56 1e3 3e6(remember that eg 3e3 is a Matlab notation of 3 _ 103) _Exercise 27Write a script that asks for an integer and checks whether it can be divided by 2 or 3 Consider all possibilitiessuch as divisible by both 2 and 3 divisible by 2 and not by 3 etc (use the command rem) _Another selection structure is switch which switches between several cases depending on an expression which119-120 is either a scalar or a stringSyntaxswitch expressioncase choice1block of commands1case choice2a choice2bblock of commands2otherwiseblock of commandsendExamplemethod = 2switch methodcase 12disp(rsquoMethod is linearrsquo)case 3disp(rsquoMethod is cubicrsquo)case 4disp(rsquoMethod is nearestrsquo)otherwisedisp(rsquoUnknown methodrsquo)endThe statements following the first case where the expression matches the choice are executed Thisconstruction can be very handy to avoid long if elseif else end constructions Theexpression can be a scalar or a string A scalar expression matches a choice if expression == choice Astring expression matches a choice if strcmp(expression choice) returns 1 (is true) (strcmp is a commandcomparing two strings)Important Note that the switch-construction only allows the execution of one group of commandsExercise 28Assume that the months are represented by numbers from 1 to 12 Write a script that asks you to provide a

month and returns the number of days in that particular month Alternatively write a script that asks youto provide a month name (eg rsquoJunersquo) instead of a number Use the switch-construction _63 LoopsIteration control structures loops are used to repeat a block of statements until some condition is met Two114-117 types of loops existbull the for loop that repeats a group of statements a fixed number of timesSyntaxfor index = firststeplastblock of statementsendExamplesumx = 0for i=1length(x)sumx = sumx + x(i)end24You can specify any step including a negative value The index of the for-loop can be also a vectorSee some examples of possible variationsExample 1for i=12nendExample 2for i=n-13endExample 3for x=0054disp(x^2)endExample 4for x=[25 9 81]disp(sqrt(x))endbull while loop which evaluates a group of commands as long as expression is TRUESyntaxwhile expressionstatement1statement2statement3endExampleN = 100iter = 1msum = 0while iter lt= Nmsum = msum + iteriter = iter + 1endExercise 29Given the vectors x and y write a script computing the a matrix whose elements should be created accordingto a formula given below (make use of the length command to check the number of elements in both vectors)- aij = yixj (make sure that a division by zero will not occur)- bij = xi _ yj

- cij = 1 max (xi yj)_Exercise 30Determine the sum of the first 50 squared numbers with a control loop _Exercise 31Write a script to find the largest value n such that the sum p13 + p23 + + pn3 is less than 1000 _optionalExercise 32Write a script that transposes a matrix A Check its correctness with the Matlab operation Arsquo _Exercise 33

Write a script that asks for a temperature in degrees Celsius tc and computes the equivalent temperature indegrees Fahrenheit tf (use the formula tf = 95 _ tc + 32) The script should keep running until no numberis provided to convert The functions input and isempty (use help to learn more) should be useful here _end optional

64 Evaluation of logical and relational expressions in the control flow structuresThe relational and logical expressions may become more complicated It is not difficult to operate on them ifyou understand how they are evaluated To explain more details let us consider the following exampleif (~isempty(data)) amp (max(data) lt 5)endThis construction of the if-block is necessary to avoid comparison if data happens to be an empty matrix Insuch a case you cannot evaluate any expression and Matlab gives an error The amp operator returns 1 only ifboth expressions ~isempty (data) and max(data) lt 5 are true and 0 otherwise When data is an emptymatrix the next expression is not evaluated since the whole amp-expression is already known to be false Thesecond expression is checked only if data is a non-empty matrix Remember to put logical expression unitsbetween brackets to avoid wrong evaluations25Important The fact that computers make use of floating-point arithmetic means that often you should becareful when comparing two floating-point numbers just byif (x == y)end(Of course such a construction is allowed eg when you know that x and y represent integers) Instead of theabove construction you may try using thisif (abs (x - y) lt tolerance) eg tolerance = 1e-10endExercise 34Consider the following examplemax_iter = 50tolerance = 1e-4iter = 0xold = 01x = 1while (abs (x - xold) gt tolerance) amp (iter lt max_iter)xold = xx = cos(xold)iter = iter + 1endThis short program tries to solve the equation cos(x) = x (x is the solution found) Make the script solve cosfrom the presented code Note that the while-loop is repeated as long as both conditions are true If eitherthe condition (|x - xold| lt= tolerance) or (iter gt= max iter) is fulfilled then the loop is quitted Runthe script solve cos for different tolerance parameters eg 1e-3 1e-6 1e-8 1e-10 etc Use format long tocheck more precisely how much the found x is really different from cos(x) For each tolerance value checkthe number of performed iterations (iter value) _Exercise 35Create the script solve cos2 which is equal to the one given replacing the while-loop condition bywhile (abs (x - xold) gt tolerance) | (iter lt max_iter)Try to understand the difference and confirm your expectations by running solve cos2 What happens toiter _optional

65 Numerical analysis and the control flow structuresTake a look at the problem of a Taylor expansion The series will be determined numerically until the additionalterms are smaller than a defined precision Look at the Taylor expansion of 11minusx = 1 + x + x2 + withx = 042s = 0 x = 1 s = 0 x = 1x0 = 042 x0 = 042while (x gt 1e-6) or while (x gt (1e-6)s)s = s + x s = s + xx = x x0 x = x x0end endThe approximation of 11minusx is returned in s (first letter of sum) In the first case (on the left) the iteration

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 11: Introduction to Programming Using Matlab

3A colon notation is an important shortcut used when producing row vectors (see Table 3 and help colon)gtgt 25ans =2 3 4 5gtgt -23ans =-2 -1 0 1 2 3In general firststeplast produces a vector of entities with the value first incrementing by the stepuntil it reaches lastgtgt 020524ans =02000 07000 12000 17000 22000gtgt -3310ans =-3 0 3 6 9gtgt 15-05-05 negative step is also possibleans =15000 10000 05000 0 -05000Parts of vectors can be extracted by using a colon notationgtgt r = [-126 2 3 -2] -126 =gt -1 1 3 5r =-1 1 3 5 2 3 -2gtgt r(36) get elements of r which are on the positions from 3 to 6ans =3 5 2 3gtgt r(125) get elements of r which are on the positions from 1 to 5 taken with the step of 2ans =-1 3 2gtgt r(5-12) what will you get hereTo create column vectors you should separate entries by a semicolon () or by new linesgtgt f = [-1 3 5]f =-135The same operations as on row vectors can be done on column vectors However you cannot for exampleadd a column vector to a row vector To do that you need an operation called transposing which converts acolumn vector into a row vector and vice versa10gtgt f = [-1 3 5] a column vectorgtgt frsquo frsquo is a row vectorans =-1 3 5gtgt v = [-1 2 7] a row vectorgtgt f + v you cannot add a column vector f to a row vector v Error using ==gt +Matrix dimensions must agreegtgt frsquo + vans =-2 5 12gtgt f + vrsquoans =-2512If x is a complex vector than xrsquo gives the conjugate transpose of x eggtgt x = [1+2i -1+i]x =10000 + 20000i -10000 + 10000igtgt xrsquo this is the conjugate transposeans =10000 - 20000i-10000 - 10000i

gtgt xrsquo this is the rsquonormalrsquo transposeans =10000 + 20000i-10000 + 10000iExercise 8Exercise to become acquainted with operating on row and column vectors Enter all examples given in thissection and make new variations yourself Exercise with the colon notation approach as well _25 MatricesAn ntimesk matrix is a rectangular array of numbers having n rows and k columns Defining a matrix in Matlabis similar to defining a vector The generalization is straightforward if you know that a matrix consists of row49-6175-86vectors (or column vectors) Commas or spaces are used to separate elements in a row and semicolons areused to separate individual rows For example the matrix A =01 2 34 5 67 8 91Ais defined asgtgt A = [1 2 3 4 5 6 7 8 9] row by row inputA =1 2 34 5 67 8 9Another examples are for instancegtgt A2 = [14 -125]A2 =1 2 3 4-1 1 3 5gtgt A3 = [1 3-4 7]A3 =1 3-4 711Command ResultA(ij) Aij

A(j) j-th column of AA(i) i-th row of AA(klmn) (l minus k + 1) times (n minus m + 1) matrix with elements Aij with k _ i _ l m _ j _ nv(ij)rsquo rsquovector-partrsquo (vi vi+1 vj) of vector vTable 2 Manipulation of (groups of) matrix-elementsCommand Resultn = rank (A) n becomes the rank of matrix Ax = det (A) x becomes the determinant of matrix AC = size (A) C becomes a row-vector with 2 elements the number of rows and columns of Ax = trace (A) x becomes the trace (sum of diagonal elements) of matrix Ax = norm (v) x becomes the length of vector vC = A + B sum of two matricesC = A - B subtraction of two matricesC = A B multiplication of two matricesC = A B rdquoelement-by-elementrdquo multiplication (A and B are of equal size)C = A ^ k power of a matrix (k 2 Z can also be used for Aminus1)C = A ^ k rdquoelement-by-elementrdquo power of a matrixC = Arsquo the transposed of a matrix AT

C = A B rdquoelement-by-elementrdquo division (A and B are of equal size)U = A B finds the solution that minimizes the squared error in Ax minus BU = B A solution of XA = B analogous to the previous commandC = inv (A) C becomes the inverse of AC = null (A) C is an orthonormal basis for the null space of Aobtained from the singular value decompositionC = orth (A) C is an orthonormal basis for the range of AC = rref (A) C is the reduced row echelon form of AL = eig (A) L is a vector containing the -possibly complex- eigenvalues of a square matrix A[X D] = eig (A) produces a diagonal matrix D of eigenvalues and a full matrix X

whose columns are the corresponding eigenvectors of AS = svd (A) S is a vector containing the singular values of A[U S V] = svd (A) S is a diagonal matrix of the same dimension as Awith nonnegative diagonal elements in decreasing orderThe columns U and V are the accompanying singular vectorsx = linspace(a b n) generates a vector x of n equally spaced points between a and bx = logspace(a b n) generates a vector x starting at 10a and ended at 10b containing n valuesA = diag (v) gives a diagonal matrix with the elements v1 v2 vn on the diagonalA = eye (n) A is a n times n identity matrixA = zeros (n m) A is a n times m matrix with zeros (default m = n)A = rand (n m) A is a n times m matrix with elements uniformly distributed between 0 and 1A = randn (n m) ditto - with elements standard normal distributedv = max (A) v becomes a vector with the maximum value of the elements in each column of Aor v is the maximum of all elements if A is a vectorv = min (A) ditto - with minimumv = sum (A) ditto - with sumTable 3 Frequently used matrix operations and functions12Transposing a vector changes it from a row to a column or the other way around This idea can be extendedto a matrix where transposing interchanges rows with the corresponding columns as in the examplegtgt A2 A2rsquoA2 =1 2 3 4-1 1 3 5ans =1 -12 13 34 5gtgt size(A2) returns the size (dimensions) of a matrixans =2 4gtgt size(A2rsquo)ans =4 2There exists also some built-in matrices of size specified by the user (see Table 2) A few examples are givenbelowgtgt E = [] an empty matrix of 0-by-0 elementsE =[]gtgt I = eye(3) the identity matrixI =1 0 00 1 00 0 1gtgt B = rand(23) a matrix of random numbers you will get a different one00227 09101 0922200299 00640 03309gtgt O = ones(32)O =1 11 11 1gtgt r = [1 3 -2] R = diag(r) create a diagonal matrix with r on the diagonalR =1 0 00 3 00 0 -2gtgt v = linspace(124) a vector is also an example of a matrixv =10000 13333 16667 20000It is often needed to build a larger matrix from the smaller onesgtgt x = [4 -1] y = [-1 4]x =4

-1y =-1 4gtgt X = [x yrsquo] X consists of the columns x and yrsquoX =4 -1-1 4gtgt T = [ -1 3 4 4 5 6] t = 1313gtgt T2 = [T t] add to T a new row namely the row vector t getting T2T2 =-1 3 44 5 61 2 3gtgt G = [1 5 4 5 0 2] G is a matrix of the 3-by-2 size check size(G)gtgt T3 = [T2 G] T3 consists of T2 and new columns being the colums of GT3 = added at the end of T2-1 3 4 1 54 5 6 4 51 2 3 0 2gtgt [diag(56) ones(32)]ans =5 00 61 11 11 1A part can be extract from a matrix in a similar way as from a vector Each element in the matrix is indexedby a row and a column to which it belongs Mathematically the element from the i-th row and the j-thcolumn of the matrix A is denoted by Aij Matlab provides the A(ij) notationgtgt A = [13 46 79]A =1 2 34 5 67 8 9gtgt A(12) A(23) A(31)ans =2ans =6ans =7gtgt A(43) A is a 3-by-3 matrix Index exceeds matrix dimensionsgtgt A(23) = A(23) + 2A(11)A =1 2 34 5 87 8 9Having defined a matrix it is easy to extended it automatically For the matrix A it can be done eg asfollowsgtgt A(52) = 5 assign 5 to the position (52) the uninitializedA = elements become zeros1 2 34 5 87 8 90 0 00 5 0Different parts of the matrix A can be now extractedgtgt A(2) extract the 2nd column of Aans =25814

05gtgtgt A(34) extract the rows 3rd and 4th of Aans =7 8 90 0 0gtgt A(2312) extract a part of Aans =4 57 8If needed the other zero elements of the matrix A can be also defined by eggtgt A(4) = [1 2 3] assign vector [1 2 3] to the 4th row of Agtgt A(5[13]) = [4 5] a rsquoshortcutrsquo when assigning A(51) = 4 and A(53) = 5gtgt A how does the matrix A look like nowAs you have seen in the examples above it is possible to manipulate (groups of) matrix-elements Thecommands are shortly explained in Table 2Exercise 9Define the matrix A = [14 58 1 1 1 1] Predict and check the result ofgtgt B = A(3)gtgt C = A(1322)gtgt A(11) = 9gtgt A(2313) = [0 0 0 0 0 0]gtgt A(l212) = [l l 3 3]gtgt A = A(3314)_Exercise 10Define the matrices T=[ 3 4 1 8 -4 3] A = [diag(-123) T -4 4 1 2 1] Perform the followingoperations on the matrix Abull extract a vector consisting of the 2nd and 4th elements of the 3rd rowbull find the minimum of the 3rd columnbull find the maximum of the 2nd rowbull compute the sum of the 2nd columbull compute the mean of the 1st and 4th rowsbull extract the submatrix consisting of the 1st and 3rd rows and all columnsbull extract the submatrix consisting of the 1st and 2nd rows and the 3rd 4th and 5th columnsbull compute the total sum of the 1st and 2nd rowsbull add 3 to all elements of the 2nd and 3rd colums_Table 3 shows some frequently used matrix operations and functions A few examples are provided belowgtgt B = rand(23) a matrix of random numbers you will get a different oneB =09501 06068 0891302311 04860 07621gtgt B2 = [1 2 5 1 5 6]gtgt B + B2rsquo add two matrices why B2rsquo is needed instead of B2ans =19501 56068 5891322311 14860 67621gtgt S = ans4 divide all elements of the matrix ans by 4S =04875 14017 1472805578 03715 1690515gtgt C = [1 -1 4 7 0 -1]gtgt B C matrix multiplication is not defined for B and C Error using ==gt Inner matrix dimensions must agreegtgt B C but you can multiply element-by-elementans =09501 -06068 3565216180 0 -07621gtgt D = B Crsquo or you can make the multiplication legal Crsquo is now 3-by-2D =39085 5759627935 08559

gtgt D^3 this is equivalent to D D Dans =1992503 2041413990133 910548gtgt D^3 - 2 do for all elements raise to the power 3 and subtract 2ans =577069 1890638198005 -13731gtgtgtgt r = [1 3 -2]r B2 this is a legal operation r is a 1-by-3 matrix and B2 isans = 3-by-2 matrix B2 r is an illegal operation6 -7Remind that an n-by-k matrix A (having n rows and k columns) can be multiply by another matrix B onlyif B has k rows ie S is of the k-by-m size (m is arbitrary) As a result you get an n-by-m matrixA ˙B = C A 2 Rntimesk B 2 Rktimesm C 2 Rntimesm

RemarkYou can now compute the inner product between two vectors x and y xT y = Pi xi yi in a simple waygtgt f = [-1 3 5] a column vectorgtgt v = [-1 2 7] a column vectorgtgt frsquo v this is the inner productans =42gtgt f vrsquo be careful now a 3-by-1 matrix is multiplied by a 1-by-3gtgt matrix which results in a 3-by-3 matrix (the outer product)ans =1 -2 -7-3 6 21-5 10 35gtgt f v this is an element-by-element multiplication1635gtgt sum (f v) this is an another way to compute the inner productans =42Exercise 11Perform all operations from Table 3 using chosen matrices A and B vector v and scalars k a b n and m _Exercise 12Let A be a random 3 times 3 matrix and b a random 3 times 1 vector Given that Ax = b then x = Aminus1b Find x(there exist at least two possible commands to do this look at Table 3) _optionalThe concept of an empty matrix [] is also very useful in Matlab For instance a few columns or rows canbe removed from a matrix by assigning an empty matrix to it Try for example16Symbol Color Symbol Styley yellow dotted liner red o circlesg green - solid lineb blue - dashdotted lineTable 4 Plot colors and stylesgtgt C = [1 2 3 4 5 6 7 8 1 1 1 1]gtgt D = C D(2) = [] now a copy of C is in D remove the 2nd column of Dgtgt C ([13]) = [] remove the rows 1 and 3 from Cend optional

3 VisualizationMatlab can be used to visualize the results of an experiment Therefore you should define variables each ofthem containing all values of one parameter to plot31 Simple plotsWith the command plot a graphical display can be made plot(y) draws the points (1 y(1)) (2 y(2)) 184 (n y(n)) and connects the points with a straight line plot(xy) does the same for (x(1) y(1)) (x(2) y(2)) (x(n) y(n)) x and y have to be row- or column vectors of equal lengthThe commands loglog semilogx and semilogy are similar to plot except that they use logarithmic axesExercise 13Type the following commands after predicting the resultgtgt x = 0330

gtgt y = 2^[010] this is the same as y = [1 2 4 8 16 32 64 128 256 512 1024]gtgt plot(xy) to get a graphic representationgtgt semilogy(xy) to get logarithmic axesAs you can see the same figure is used for both plot commands The previous function is removed as soonas the next is displayed The command figure gives you an extra figure Repeat the previous commandsbut generate a new figure before plotting the second function so that you can see both functions in separatewindows You can also switch back to a figure using figure(n) where n is its number _Exercise 14Make a plot such that the coordinates (2 6) (25 18) (5 175) (42 125) and (212) are connected by aline _Exercise 15Plot the function y = sin(x) + x minus x cos(x) in two separate figures for the intervals 0 lt x lt 30 andminus100 lt x lt 100 _32 Several functions in one figureWhen more than one function is plotted in one figure it might be useful to use different markers and colors184-188197-201Table 4 shows a few possibilities help plot shows allThere are different ways to get more than one function into a figure The first one is with the command holdon After this command all functions will be plotted in the same figure until the command hold off is usedAn examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt plot (x1 y1 rsquordrsquo)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)17gtgt hold ongtgt plot (x2 y2 rsquoy-rsquo)gtgt plot (x1y1rsquok-rsquo)gtgt hold offA second method to display more than one function in one figure is to plot several functions at the same timeThe next commands will have the same results as the commands in the previous examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt plot (x1 y1rsquordrsquo x2 y2 rsquoy-rsquo x1 y1 rsquok-rsquo)It is also possible to get more than one figure in one figure window With the command subplot the windowcan be horizontally and vertically divided into any number of subfiguresgtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt subplot(131) plot (x1 y1rsquordrsquo)gtgt subplot(132) plot (x2 y2 rsquoy-rsquo)gtgt subplot(133) plot (x1 y1 rsquok-rsquo)optional

33 Other 2D plotting featuresIn the introduction of this chapter some commands similar to plot loglog semilogx and semilogy were201-211 mentioned There are however more ways to display dataExercise 16To get an impression of other visualizations type the following commands and describe the result (note thatthe command figure creates a new figure window)gtgt figure bar plot of a bell shaped curvegtgt x = -290229gtgt bar (x exp (-xx))gtgt figure stairstep plot of a sine wavegtgt x = 002510gtgt stairs (x sin (x))gtgt figure errorbar plotgtgt x = -2012gtgt y = erf (x) error function check help if you are interestedgtgt e = rand (size (x)) 10gtgt errorbar (x y e)

_end optional

34 PrintingBefore printing a figure you made you might want to add some information such as a title or change the189-196 lay-out a little Table 5 shows some of the commands that can be usedExercise 17Plot the functions y1 = sin(4x) y2 = x cos(x) y3 = (x + 1)minus1px for x = 0 025 10 and a single point(x y) = (4 5) in one figure with different colors and styles Make a legend containing the three functionsMake labels for both axes and a title Add a text to the single point saying single point Change the minimumand maximum values of the axes such that function y3 can be looked at in more detail _When the displayed figure is to your liking you can print it to paper The easiest way to do this is to click onFile in the menu-bar and to choose Print If in the print window you click OK your figure will be printed onthe printer indicated in the print window18Command Resultgrid onoff adds a grid to the plot at the tick marks or removes itaxis([xmin xmax ymin ymax]) sets the minimum and maximum values of the axesbox offon removes the axes box or shows itxlabel(rsquotextrsquo) plots the label text on the x axisylabel(rsquotextrsquo) plots the label text on the y axistitle(rsquotextrsquo) plots a title above the graphtext(xyrsquotextrsquo) adds text at the point (xy)gtext(rsquotextrsquo) adds text at a manually (with a mouse) indicated pointlegend(rsquofun1rsquorsquofun2rsquo) plots a legend box (move it with your mouse) to name your functionslegend off deletes the legend boxTable 5 Plot-manipulationsThere is also a print command which can be used to send a figure to a printer or output it to a file Youcan optionally specify a print device (ie an output format such as tiff or postscript) and options that controlvarious characteristics of the printed file (ie which Figure to print etc) You can also print to a file if youspecify the file name If you do not provide an extension print adds one Since they are many parametersthey will not be explained here (check help print to learn more) Instead try to understand the examplesgtgt print -dwinc print the current Figure to the current printer in colorgtgt print -f1 -deps myfileeps print Figure no1 to the file myfileeps in blackgtgt print -f1 -depsc myfileceps print Figure no1 to the file myfilecoleps in colorgtgt print -dtiff myfile1tiff print the current Figure to the file myfile1tiffgtgt print -dpsc myfile1cps print the current Figure to the file myfile1ps in colorgtgt print -f2 -djpeg myfile2 print Figure no2 to the file myfile2jpgExercise 18Exercise with printing (especially to a file) the figure from Exercise 16 _

4 Curve fitting and interpolationThere are two ways to describe data with an analytical function- curve fitting or regression finding a smooth curve that best fits (approximates) the data accordingto a criterion (eg best least square fit) The curve does not have to go through any of the data points- interpolation the data are assumed to be correct desired in a way to describe what happens betweenthe data points In other words given a finite set of points the goal of interpolation is to find a functionfrom a given class of functions (eg polynomials) which passes through the specified pointsThe figure below illustrates the difference between regression (curve fitting) and interpolationminus5 0 5minus6minus4minus20246810fiting a 3rd order polynomialinterpolation

41 Curve fittingMatlab interprets the best fit of a curve by the lsquoleast squares curve fittingrsquo The curve used is restricted153-15619to polynomials With the command polyfit any polynomial can be fitted to the data polyfit (x y n)finds the coefficients of a polynomial of degree n that fits the data (finds the linear relation between x and y)Letrsquos start with finding a linear regression of some datagtgt x = 010gtgt y = [-10 24 102 158 284 276 299 405 483 522 751]gtgt p = polyfit (x y 1) find the fitting polynomial of order 1p = 06772 -03914

The output of polyfit is a row vector of the polynomial coefficients the solution of this example is thereforey = 06772x minus 03914Exercise 19Execute the above example Plot the data and the fitted curve in a figure Determine the 2nd and 9th orderpolynomial of these data as well and display the solution in a figureHint x1 = linspace (xmin xmax n) results in a vector with n element evenly distributed from xmintill xmax z = polyval (p x1) calculates the values of the polynomial for every element of x1 _Exercise 20Define x and y as followsgtgt x = -55gtgt y = 02x^3 - x + 2 a 3rd order polynomialgtgt y = y + randn(111) add some noise to yDetermine the 3rd order polynomial fitting y (note that because of added noise the coefficients are differentthat originally chosen) Try some other polynomials as well Plot the results in a figure _42 InterpolationThe simplest way to examine an interpolation is by displaying the function plots with the command plot157-161 The neighboring data points are connected with straight lines This is called a linear interpolation Whenmore data-points are taken into account the effect of interpolation becomes less visible Analyzegtgt x1 = linspace(0 2pi2)gtgt x2 = linspace(0 2pi4)gtgt x3 = linspace(0 2pi16)gtgt x4 = linspace(0 2pi256)gtgt plot(x1sin(x1)x2sin(x2)x3sin(x3)x4sin(x4))gtgt legend(rsquo2 pointsrsquorsquo4 pointsrsquorsquo16 pointsrsquorsquo256 pointsrsquo)

5 Numerical analysisNumerical analysis can be used whenever it is impossible or very difficult to determine the analytical solutionMatlab can be used to find for example the minimum maximum or integral of a certain function51 Evaluation of a functionAs said before the command plot plots a function by connecting defined data points Sometimes however a168-173 function is constant and not very interesting over some range and then acts unexpectedly wildly over anotherWith plot this function might be misinterpreted The command fplot is then useful An examplegtgt x = 0pi82pigtgt y = sin (8x)gtgt plot (x y rsquobrsquo)gtgt hold ongtgt fplot (rsquosin (8z)rsquo [0 2pi] rsquorrsquo)gtgt title (rsquosin (8z)rsquo)gtgt hold off20Command Resultfplot (rsquofunrsquo [min x max x]) plots the function fun for min x till max xfmin (rsquofunrsquo min x max x) gives the x-value of the miminum of thefunction fun between min x and max xfzero (rsquofunrsquo x0) gives the x-value for which the functionfun is zero in the neighborhood of x0Table 6 Evaluation of a functionExecution of these commands results in a figure with an almost straight blue line and a red sine fplot canalso be used to plot a defined functiongtgt f = rsquosin (8z)rsquogtgt fplot (f [0 2pi] rsquorrsquo)gtgt title (f)Other useful commands for a detailed study of a range of a function are listed in Table 6Exercise 21The command fmax does not exist Use one or more of the commands from Table 6 to determine the maximumof the function x cos(x) for 10 lt x lt 15 _52 Integration and differentiationThe integral- or the surface underneath a 2D function- can be determined with the command trapz trapz173-182 does this by measuring the surface between the x-axis and the -by a straight line connected- data points Theaccuracy of this method depends on the distance between the data pointsgtgt x = 00510 y = 05 sqrt (x) + x sin (x) area1 = trapz (x y)

area1 =181655gtgt x = 000510 y = 05 sqrt (x) + x sin (x) area2 = trapz (x y)area2 =183846Differentiation is done by determining the slope in each data point Numerically this is done by first fitting apolynomial followed by differentiating this functiongtgt x = 010gtgt y = [-10 24 102 -158 284 276 775 35 483 522 751]gtgt p = polyfit (x y 5)p = 00026 -00554 03634 -06888 02747 00877gtgt dp = polyder (p)dp = 00132 -02216 10903 -13776 02747gtgt x1 = linspace (0 10 200)gtgt z = polyval (p x1)gtgt dz = polyval (dp x1)gtgt plot (x y rsquog-rsquo x1 z rsquobrsquo x1 dz rsquorrsquo)gtgt legend (rsquodata pointsrsquo rsquocurve fitrsquo rsquoderivativersquo)Exercise 22Determine the integral and derivative of the 4th polynomial fitted through (xy) with x = [4 5 6 7 8 9 1011 12 13] y = [1284 1200 724 -096 -1116 -2096 -2700 -2496 -956 2544] _

6 Control flowAs you know it is possible to execute more than one command at the same time (see section 11) Theseparate commands should then be divided by commarsquos (to display the output) or by semicolons (to suppress21output display) Control flow loops increase the number of possibilities A control flow structure is a block ofcommands that allows conditional code execution and making loops61 Logical and relational operatorsTo use control flow commands it is necessary to perform operations that result in logical values TRUE or88-91 FALSE In Matlab the result of a logical operation is 1 if it is true and 0 if it is false Table 7 shows therelational and logical operations2 Another way to get to know more about them is to type help relop Therelational operators lt lt= gt gt= == and ~= can be used to compare two arrays of the same size or anarray to a scalar The logical operators amp | and ~ allow for the logical combination or negation of relationaloperators In addition three functions are also available xor any and all (use help to find out more)Important The logical amp and | have the equal precedence in Matlab which means that those operatorsassociate from left to right A common situation isgtgt b = 10gtgt 1 | b gt 0 amp 0ans =0gtgt (1 | b gt 0) amp 0 this indicates the same as aboveans =0gtgt 1 | (b gt 0 amp 0)ans =1This shows that you should always use brackets to indicate in which way the operators should be evaluatedCommand Resulta = (b gt c) a is 1 if b is larger than c Similar are lt gt= and lt=a = (b == c) a is 1 if b is equal to ca = (b ~= c) a is 1 if b is not equal ca = ~b logical complement a is 1 if b is 0a = (b amp c) logical AND a is 1 if b = TRUE AND c = TRUEa = (b | c) logical OR a is 1 if b = TRUE OR c = TRUETable 7 Relational and logical operationsExercise 23Predict and check the result of each of the operations of Table 7 for b = 0 and c = -1 _Exercise 24Define two vectors with seven elements (randn(17)) and perform all logical operations including xor anyand all _Exercise 25While doing logical operations between a vector and a scalar each element of the vector is compared to thescalar Predict and check the result of each logical operator for the vector b = [2 31 -40 0] and the scalarc = 0 _Before moving on check whether you now understand the following relations

gtgt a = randperm(10) a random permutation of the numbers from 1 to 10gtgt b = 110gtgt b - (a lt= 7) subtracts from b a 0-1 vector taking 1 for a lt= 7 and 0 otherwisegtgt (a gt= 2) amp (a lt 4) returns ones at positions where 2 lt= a lt 4gtgt ~(b gt 4) returns ones at positions where b lt= 4gtgt (a == b) | b == 3 returns ones at positions where a is equal to b or b is equal to 3gtgt any (a gt 5) returns 1 when ANY of the a elements are larger than 5gtgt any (b lt 5 amp a gt 8) returns 1 when there in the evaluated expressiongtgt (b lt 5 amp a gt 8) appears at least one 1gtgt all (b gt 2) returns 1 when ALL b elements are larger than 22rdquoequal tordquo in the table on page 88 of rdquoThe Student Edition of Matlabrdquo must be rdquo==rdquo instead of rdquo=rdquo2262 Conditional code executionSelection control structures if-blocks are used to decide which instruction to execute next depending whether117-119 expression is TRUE or not The general description is given below In the examples below the command dispis frequently used This command displays on the screen the text between the quotesbull if endSyntaxif logical_expressionstatement1statement2endExampleif (a gt 0)b = adisp (rsquoa is positiversquo)endbull if else endSyntaxif logical_expressionblock of statementsevaluated if TRUEelseblock of statementsevaluated if FALSEendExampleif (temperature gt 100)disp (rsquoAbove boilingrsquo)toohigh = 1elsedisp (rsquoTemperature is OKrsquo)toohigh = 0endbull if elseif else endSyntaxif logical_expression1block of statements evaluatedif logical_expression1 is TRUEelseif logical_expression2block of statements evaluatedif logical_expression2 is TRUEelseblock of statements evaluatedif no other expression is TRUEendExampleif (height gt 190)disp (rsquovery tallrsquo)elseif (height gt 170)disp (rsquotallrsquo)elseif (height lt 150)disp (rsquosmallrsquo)

elsedisp (rsquoaveragersquo)endRemark To do the exercises below a script m-file will be useful It is an external file that contains asequence of Matlab commands What you need to do is to open an editor enter all commands needed forthe solution of a task save it with the extension rsquomrsquo (eg mytaskm) and then run it from the CommandWindow by typing mytask To open the Matlab editor go to the File menu-bar choose the Open optionand then m-file A new window will appear where you can write your scripts and save them on the disk Allcommands in the script will be executed in Matlab You will learn more on script m-files in section 91Important m-script file must be saved in one of the directories in Matlabrsquos pathAn example A script shortm can be created from the two lines given below and run by calling shortx = 0054plot (x sin(x) rsquo-rsquo)Exercise 26Create a script that asks for a number N and computes the drag coefficient C depending on the Reynoldrsquos23number N (make use of the if elseif construction) The command input might be useful here(read pages 32-33 from rdquoThe Student Edition of Matlabrdquoor use help)C =8gtgtgtltgtgtgt0 N _ 024N N 2 (0 01]24N (1 + 014N07) N 2 (01 1e3]043 N 2 (1e3 5e5]019 minus 8e4N N gt 5e5Check whether your script works correctly Compute the drag coefficient for eg N = -3e3 001 56 1e3 3e6(remember that eg 3e3 is a Matlab notation of 3 _ 103) _Exercise 27Write a script that asks for an integer and checks whether it can be divided by 2 or 3 Consider all possibilitiessuch as divisible by both 2 and 3 divisible by 2 and not by 3 etc (use the command rem) _Another selection structure is switch which switches between several cases depending on an expression which119-120 is either a scalar or a stringSyntaxswitch expressioncase choice1block of commands1case choice2a choice2bblock of commands2otherwiseblock of commandsendExamplemethod = 2switch methodcase 12disp(rsquoMethod is linearrsquo)case 3disp(rsquoMethod is cubicrsquo)case 4disp(rsquoMethod is nearestrsquo)otherwisedisp(rsquoUnknown methodrsquo)endThe statements following the first case where the expression matches the choice are executed Thisconstruction can be very handy to avoid long if elseif else end constructions Theexpression can be a scalar or a string A scalar expression matches a choice if expression == choice Astring expression matches a choice if strcmp(expression choice) returns 1 (is true) (strcmp is a commandcomparing two strings)Important Note that the switch-construction only allows the execution of one group of commandsExercise 28Assume that the months are represented by numbers from 1 to 12 Write a script that asks you to provide a

month and returns the number of days in that particular month Alternatively write a script that asks youto provide a month name (eg rsquoJunersquo) instead of a number Use the switch-construction _63 LoopsIteration control structures loops are used to repeat a block of statements until some condition is met Two114-117 types of loops existbull the for loop that repeats a group of statements a fixed number of timesSyntaxfor index = firststeplastblock of statementsendExamplesumx = 0for i=1length(x)sumx = sumx + x(i)end24You can specify any step including a negative value The index of the for-loop can be also a vectorSee some examples of possible variationsExample 1for i=12nendExample 2for i=n-13endExample 3for x=0054disp(x^2)endExample 4for x=[25 9 81]disp(sqrt(x))endbull while loop which evaluates a group of commands as long as expression is TRUESyntaxwhile expressionstatement1statement2statement3endExampleN = 100iter = 1msum = 0while iter lt= Nmsum = msum + iteriter = iter + 1endExercise 29Given the vectors x and y write a script computing the a matrix whose elements should be created accordingto a formula given below (make use of the length command to check the number of elements in both vectors)- aij = yixj (make sure that a division by zero will not occur)- bij = xi _ yj

- cij = 1 max (xi yj)_Exercise 30Determine the sum of the first 50 squared numbers with a control loop _Exercise 31Write a script to find the largest value n such that the sum p13 + p23 + + pn3 is less than 1000 _optionalExercise 32Write a script that transposes a matrix A Check its correctness with the Matlab operation Arsquo _Exercise 33

Write a script that asks for a temperature in degrees Celsius tc and computes the equivalent temperature indegrees Fahrenheit tf (use the formula tf = 95 _ tc + 32) The script should keep running until no numberis provided to convert The functions input and isempty (use help to learn more) should be useful here _end optional

64 Evaluation of logical and relational expressions in the control flow structuresThe relational and logical expressions may become more complicated It is not difficult to operate on them ifyou understand how they are evaluated To explain more details let us consider the following exampleif (~isempty(data)) amp (max(data) lt 5)endThis construction of the if-block is necessary to avoid comparison if data happens to be an empty matrix Insuch a case you cannot evaluate any expression and Matlab gives an error The amp operator returns 1 only ifboth expressions ~isempty (data) and max(data) lt 5 are true and 0 otherwise When data is an emptymatrix the next expression is not evaluated since the whole amp-expression is already known to be false Thesecond expression is checked only if data is a non-empty matrix Remember to put logical expression unitsbetween brackets to avoid wrong evaluations25Important The fact that computers make use of floating-point arithmetic means that often you should becareful when comparing two floating-point numbers just byif (x == y)end(Of course such a construction is allowed eg when you know that x and y represent integers) Instead of theabove construction you may try using thisif (abs (x - y) lt tolerance) eg tolerance = 1e-10endExercise 34Consider the following examplemax_iter = 50tolerance = 1e-4iter = 0xold = 01x = 1while (abs (x - xold) gt tolerance) amp (iter lt max_iter)xold = xx = cos(xold)iter = iter + 1endThis short program tries to solve the equation cos(x) = x (x is the solution found) Make the script solve cosfrom the presented code Note that the while-loop is repeated as long as both conditions are true If eitherthe condition (|x - xold| lt= tolerance) or (iter gt= max iter) is fulfilled then the loop is quitted Runthe script solve cos for different tolerance parameters eg 1e-3 1e-6 1e-8 1e-10 etc Use format long tocheck more precisely how much the found x is really different from cos(x) For each tolerance value checkthe number of performed iterations (iter value) _Exercise 35Create the script solve cos2 which is equal to the one given replacing the while-loop condition bywhile (abs (x - xold) gt tolerance) | (iter lt max_iter)Try to understand the difference and confirm your expectations by running solve cos2 What happens toiter _optional

65 Numerical analysis and the control flow structuresTake a look at the problem of a Taylor expansion The series will be determined numerically until the additionalterms are smaller than a defined precision Look at the Taylor expansion of 11minusx = 1 + x + x2 + withx = 042s = 0 x = 1 s = 0 x = 1x0 = 042 x0 = 042while (x gt 1e-6) or while (x gt (1e-6)s)s = s + x s = s + xx = x x0 x = x x0end endThe approximation of 11minusx is returned in s (first letter of sum) In the first case (on the left) the iteration

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 12: Introduction to Programming Using Matlab

gtgt xrsquo this is the rsquonormalrsquo transposeans =10000 + 20000i-10000 + 10000iExercise 8Exercise to become acquainted with operating on row and column vectors Enter all examples given in thissection and make new variations yourself Exercise with the colon notation approach as well _25 MatricesAn ntimesk matrix is a rectangular array of numbers having n rows and k columns Defining a matrix in Matlabis similar to defining a vector The generalization is straightforward if you know that a matrix consists of row49-6175-86vectors (or column vectors) Commas or spaces are used to separate elements in a row and semicolons areused to separate individual rows For example the matrix A =01 2 34 5 67 8 91Ais defined asgtgt A = [1 2 3 4 5 6 7 8 9] row by row inputA =1 2 34 5 67 8 9Another examples are for instancegtgt A2 = [14 -125]A2 =1 2 3 4-1 1 3 5gtgt A3 = [1 3-4 7]A3 =1 3-4 711Command ResultA(ij) Aij

A(j) j-th column of AA(i) i-th row of AA(klmn) (l minus k + 1) times (n minus m + 1) matrix with elements Aij with k _ i _ l m _ j _ nv(ij)rsquo rsquovector-partrsquo (vi vi+1 vj) of vector vTable 2 Manipulation of (groups of) matrix-elementsCommand Resultn = rank (A) n becomes the rank of matrix Ax = det (A) x becomes the determinant of matrix AC = size (A) C becomes a row-vector with 2 elements the number of rows and columns of Ax = trace (A) x becomes the trace (sum of diagonal elements) of matrix Ax = norm (v) x becomes the length of vector vC = A + B sum of two matricesC = A - B subtraction of two matricesC = A B multiplication of two matricesC = A B rdquoelement-by-elementrdquo multiplication (A and B are of equal size)C = A ^ k power of a matrix (k 2 Z can also be used for Aminus1)C = A ^ k rdquoelement-by-elementrdquo power of a matrixC = Arsquo the transposed of a matrix AT

C = A B rdquoelement-by-elementrdquo division (A and B are of equal size)U = A B finds the solution that minimizes the squared error in Ax minus BU = B A solution of XA = B analogous to the previous commandC = inv (A) C becomes the inverse of AC = null (A) C is an orthonormal basis for the null space of Aobtained from the singular value decompositionC = orth (A) C is an orthonormal basis for the range of AC = rref (A) C is the reduced row echelon form of AL = eig (A) L is a vector containing the -possibly complex- eigenvalues of a square matrix A[X D] = eig (A) produces a diagonal matrix D of eigenvalues and a full matrix X

whose columns are the corresponding eigenvectors of AS = svd (A) S is a vector containing the singular values of A[U S V] = svd (A) S is a diagonal matrix of the same dimension as Awith nonnegative diagonal elements in decreasing orderThe columns U and V are the accompanying singular vectorsx = linspace(a b n) generates a vector x of n equally spaced points between a and bx = logspace(a b n) generates a vector x starting at 10a and ended at 10b containing n valuesA = diag (v) gives a diagonal matrix with the elements v1 v2 vn on the diagonalA = eye (n) A is a n times n identity matrixA = zeros (n m) A is a n times m matrix with zeros (default m = n)A = rand (n m) A is a n times m matrix with elements uniformly distributed between 0 and 1A = randn (n m) ditto - with elements standard normal distributedv = max (A) v becomes a vector with the maximum value of the elements in each column of Aor v is the maximum of all elements if A is a vectorv = min (A) ditto - with minimumv = sum (A) ditto - with sumTable 3 Frequently used matrix operations and functions12Transposing a vector changes it from a row to a column or the other way around This idea can be extendedto a matrix where transposing interchanges rows with the corresponding columns as in the examplegtgt A2 A2rsquoA2 =1 2 3 4-1 1 3 5ans =1 -12 13 34 5gtgt size(A2) returns the size (dimensions) of a matrixans =2 4gtgt size(A2rsquo)ans =4 2There exists also some built-in matrices of size specified by the user (see Table 2) A few examples are givenbelowgtgt E = [] an empty matrix of 0-by-0 elementsE =[]gtgt I = eye(3) the identity matrixI =1 0 00 1 00 0 1gtgt B = rand(23) a matrix of random numbers you will get a different one00227 09101 0922200299 00640 03309gtgt O = ones(32)O =1 11 11 1gtgt r = [1 3 -2] R = diag(r) create a diagonal matrix with r on the diagonalR =1 0 00 3 00 0 -2gtgt v = linspace(124) a vector is also an example of a matrixv =10000 13333 16667 20000It is often needed to build a larger matrix from the smaller onesgtgt x = [4 -1] y = [-1 4]x =4

-1y =-1 4gtgt X = [x yrsquo] X consists of the columns x and yrsquoX =4 -1-1 4gtgt T = [ -1 3 4 4 5 6] t = 1313gtgt T2 = [T t] add to T a new row namely the row vector t getting T2T2 =-1 3 44 5 61 2 3gtgt G = [1 5 4 5 0 2] G is a matrix of the 3-by-2 size check size(G)gtgt T3 = [T2 G] T3 consists of T2 and new columns being the colums of GT3 = added at the end of T2-1 3 4 1 54 5 6 4 51 2 3 0 2gtgt [diag(56) ones(32)]ans =5 00 61 11 11 1A part can be extract from a matrix in a similar way as from a vector Each element in the matrix is indexedby a row and a column to which it belongs Mathematically the element from the i-th row and the j-thcolumn of the matrix A is denoted by Aij Matlab provides the A(ij) notationgtgt A = [13 46 79]A =1 2 34 5 67 8 9gtgt A(12) A(23) A(31)ans =2ans =6ans =7gtgt A(43) A is a 3-by-3 matrix Index exceeds matrix dimensionsgtgt A(23) = A(23) + 2A(11)A =1 2 34 5 87 8 9Having defined a matrix it is easy to extended it automatically For the matrix A it can be done eg asfollowsgtgt A(52) = 5 assign 5 to the position (52) the uninitializedA = elements become zeros1 2 34 5 87 8 90 0 00 5 0Different parts of the matrix A can be now extractedgtgt A(2) extract the 2nd column of Aans =25814

05gtgtgt A(34) extract the rows 3rd and 4th of Aans =7 8 90 0 0gtgt A(2312) extract a part of Aans =4 57 8If needed the other zero elements of the matrix A can be also defined by eggtgt A(4) = [1 2 3] assign vector [1 2 3] to the 4th row of Agtgt A(5[13]) = [4 5] a rsquoshortcutrsquo when assigning A(51) = 4 and A(53) = 5gtgt A how does the matrix A look like nowAs you have seen in the examples above it is possible to manipulate (groups of) matrix-elements Thecommands are shortly explained in Table 2Exercise 9Define the matrix A = [14 58 1 1 1 1] Predict and check the result ofgtgt B = A(3)gtgt C = A(1322)gtgt A(11) = 9gtgt A(2313) = [0 0 0 0 0 0]gtgt A(l212) = [l l 3 3]gtgt A = A(3314)_Exercise 10Define the matrices T=[ 3 4 1 8 -4 3] A = [diag(-123) T -4 4 1 2 1] Perform the followingoperations on the matrix Abull extract a vector consisting of the 2nd and 4th elements of the 3rd rowbull find the minimum of the 3rd columnbull find the maximum of the 2nd rowbull compute the sum of the 2nd columbull compute the mean of the 1st and 4th rowsbull extract the submatrix consisting of the 1st and 3rd rows and all columnsbull extract the submatrix consisting of the 1st and 2nd rows and the 3rd 4th and 5th columnsbull compute the total sum of the 1st and 2nd rowsbull add 3 to all elements of the 2nd and 3rd colums_Table 3 shows some frequently used matrix operations and functions A few examples are provided belowgtgt B = rand(23) a matrix of random numbers you will get a different oneB =09501 06068 0891302311 04860 07621gtgt B2 = [1 2 5 1 5 6]gtgt B + B2rsquo add two matrices why B2rsquo is needed instead of B2ans =19501 56068 5891322311 14860 67621gtgt S = ans4 divide all elements of the matrix ans by 4S =04875 14017 1472805578 03715 1690515gtgt C = [1 -1 4 7 0 -1]gtgt B C matrix multiplication is not defined for B and C Error using ==gt Inner matrix dimensions must agreegtgt B C but you can multiply element-by-elementans =09501 -06068 3565216180 0 -07621gtgt D = B Crsquo or you can make the multiplication legal Crsquo is now 3-by-2D =39085 5759627935 08559

gtgt D^3 this is equivalent to D D Dans =1992503 2041413990133 910548gtgt D^3 - 2 do for all elements raise to the power 3 and subtract 2ans =577069 1890638198005 -13731gtgtgtgt r = [1 3 -2]r B2 this is a legal operation r is a 1-by-3 matrix and B2 isans = 3-by-2 matrix B2 r is an illegal operation6 -7Remind that an n-by-k matrix A (having n rows and k columns) can be multiply by another matrix B onlyif B has k rows ie S is of the k-by-m size (m is arbitrary) As a result you get an n-by-m matrixA ˙B = C A 2 Rntimesk B 2 Rktimesm C 2 Rntimesm

RemarkYou can now compute the inner product between two vectors x and y xT y = Pi xi yi in a simple waygtgt f = [-1 3 5] a column vectorgtgt v = [-1 2 7] a column vectorgtgt frsquo v this is the inner productans =42gtgt f vrsquo be careful now a 3-by-1 matrix is multiplied by a 1-by-3gtgt matrix which results in a 3-by-3 matrix (the outer product)ans =1 -2 -7-3 6 21-5 10 35gtgt f v this is an element-by-element multiplication1635gtgt sum (f v) this is an another way to compute the inner productans =42Exercise 11Perform all operations from Table 3 using chosen matrices A and B vector v and scalars k a b n and m _Exercise 12Let A be a random 3 times 3 matrix and b a random 3 times 1 vector Given that Ax = b then x = Aminus1b Find x(there exist at least two possible commands to do this look at Table 3) _optionalThe concept of an empty matrix [] is also very useful in Matlab For instance a few columns or rows canbe removed from a matrix by assigning an empty matrix to it Try for example16Symbol Color Symbol Styley yellow dotted liner red o circlesg green - solid lineb blue - dashdotted lineTable 4 Plot colors and stylesgtgt C = [1 2 3 4 5 6 7 8 1 1 1 1]gtgt D = C D(2) = [] now a copy of C is in D remove the 2nd column of Dgtgt C ([13]) = [] remove the rows 1 and 3 from Cend optional

3 VisualizationMatlab can be used to visualize the results of an experiment Therefore you should define variables each ofthem containing all values of one parameter to plot31 Simple plotsWith the command plot a graphical display can be made plot(y) draws the points (1 y(1)) (2 y(2)) 184 (n y(n)) and connects the points with a straight line plot(xy) does the same for (x(1) y(1)) (x(2) y(2)) (x(n) y(n)) x and y have to be row- or column vectors of equal lengthThe commands loglog semilogx and semilogy are similar to plot except that they use logarithmic axesExercise 13Type the following commands after predicting the resultgtgt x = 0330

gtgt y = 2^[010] this is the same as y = [1 2 4 8 16 32 64 128 256 512 1024]gtgt plot(xy) to get a graphic representationgtgt semilogy(xy) to get logarithmic axesAs you can see the same figure is used for both plot commands The previous function is removed as soonas the next is displayed The command figure gives you an extra figure Repeat the previous commandsbut generate a new figure before plotting the second function so that you can see both functions in separatewindows You can also switch back to a figure using figure(n) where n is its number _Exercise 14Make a plot such that the coordinates (2 6) (25 18) (5 175) (42 125) and (212) are connected by aline _Exercise 15Plot the function y = sin(x) + x minus x cos(x) in two separate figures for the intervals 0 lt x lt 30 andminus100 lt x lt 100 _32 Several functions in one figureWhen more than one function is plotted in one figure it might be useful to use different markers and colors184-188197-201Table 4 shows a few possibilities help plot shows allThere are different ways to get more than one function into a figure The first one is with the command holdon After this command all functions will be plotted in the same figure until the command hold off is usedAn examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt plot (x1 y1 rsquordrsquo)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)17gtgt hold ongtgt plot (x2 y2 rsquoy-rsquo)gtgt plot (x1y1rsquok-rsquo)gtgt hold offA second method to display more than one function in one figure is to plot several functions at the same timeThe next commands will have the same results as the commands in the previous examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt plot (x1 y1rsquordrsquo x2 y2 rsquoy-rsquo x1 y1 rsquok-rsquo)It is also possible to get more than one figure in one figure window With the command subplot the windowcan be horizontally and vertically divided into any number of subfiguresgtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt subplot(131) plot (x1 y1rsquordrsquo)gtgt subplot(132) plot (x2 y2 rsquoy-rsquo)gtgt subplot(133) plot (x1 y1 rsquok-rsquo)optional

33 Other 2D plotting featuresIn the introduction of this chapter some commands similar to plot loglog semilogx and semilogy were201-211 mentioned There are however more ways to display dataExercise 16To get an impression of other visualizations type the following commands and describe the result (note thatthe command figure creates a new figure window)gtgt figure bar plot of a bell shaped curvegtgt x = -290229gtgt bar (x exp (-xx))gtgt figure stairstep plot of a sine wavegtgt x = 002510gtgt stairs (x sin (x))gtgt figure errorbar plotgtgt x = -2012gtgt y = erf (x) error function check help if you are interestedgtgt e = rand (size (x)) 10gtgt errorbar (x y e)

_end optional

34 PrintingBefore printing a figure you made you might want to add some information such as a title or change the189-196 lay-out a little Table 5 shows some of the commands that can be usedExercise 17Plot the functions y1 = sin(4x) y2 = x cos(x) y3 = (x + 1)minus1px for x = 0 025 10 and a single point(x y) = (4 5) in one figure with different colors and styles Make a legend containing the three functionsMake labels for both axes and a title Add a text to the single point saying single point Change the minimumand maximum values of the axes such that function y3 can be looked at in more detail _When the displayed figure is to your liking you can print it to paper The easiest way to do this is to click onFile in the menu-bar and to choose Print If in the print window you click OK your figure will be printed onthe printer indicated in the print window18Command Resultgrid onoff adds a grid to the plot at the tick marks or removes itaxis([xmin xmax ymin ymax]) sets the minimum and maximum values of the axesbox offon removes the axes box or shows itxlabel(rsquotextrsquo) plots the label text on the x axisylabel(rsquotextrsquo) plots the label text on the y axistitle(rsquotextrsquo) plots a title above the graphtext(xyrsquotextrsquo) adds text at the point (xy)gtext(rsquotextrsquo) adds text at a manually (with a mouse) indicated pointlegend(rsquofun1rsquorsquofun2rsquo) plots a legend box (move it with your mouse) to name your functionslegend off deletes the legend boxTable 5 Plot-manipulationsThere is also a print command which can be used to send a figure to a printer or output it to a file Youcan optionally specify a print device (ie an output format such as tiff or postscript) and options that controlvarious characteristics of the printed file (ie which Figure to print etc) You can also print to a file if youspecify the file name If you do not provide an extension print adds one Since they are many parametersthey will not be explained here (check help print to learn more) Instead try to understand the examplesgtgt print -dwinc print the current Figure to the current printer in colorgtgt print -f1 -deps myfileeps print Figure no1 to the file myfileeps in blackgtgt print -f1 -depsc myfileceps print Figure no1 to the file myfilecoleps in colorgtgt print -dtiff myfile1tiff print the current Figure to the file myfile1tiffgtgt print -dpsc myfile1cps print the current Figure to the file myfile1ps in colorgtgt print -f2 -djpeg myfile2 print Figure no2 to the file myfile2jpgExercise 18Exercise with printing (especially to a file) the figure from Exercise 16 _

4 Curve fitting and interpolationThere are two ways to describe data with an analytical function- curve fitting or regression finding a smooth curve that best fits (approximates) the data accordingto a criterion (eg best least square fit) The curve does not have to go through any of the data points- interpolation the data are assumed to be correct desired in a way to describe what happens betweenthe data points In other words given a finite set of points the goal of interpolation is to find a functionfrom a given class of functions (eg polynomials) which passes through the specified pointsThe figure below illustrates the difference between regression (curve fitting) and interpolationminus5 0 5minus6minus4minus20246810fiting a 3rd order polynomialinterpolation

41 Curve fittingMatlab interprets the best fit of a curve by the lsquoleast squares curve fittingrsquo The curve used is restricted153-15619to polynomials With the command polyfit any polynomial can be fitted to the data polyfit (x y n)finds the coefficients of a polynomial of degree n that fits the data (finds the linear relation between x and y)Letrsquos start with finding a linear regression of some datagtgt x = 010gtgt y = [-10 24 102 158 284 276 299 405 483 522 751]gtgt p = polyfit (x y 1) find the fitting polynomial of order 1p = 06772 -03914

The output of polyfit is a row vector of the polynomial coefficients the solution of this example is thereforey = 06772x minus 03914Exercise 19Execute the above example Plot the data and the fitted curve in a figure Determine the 2nd and 9th orderpolynomial of these data as well and display the solution in a figureHint x1 = linspace (xmin xmax n) results in a vector with n element evenly distributed from xmintill xmax z = polyval (p x1) calculates the values of the polynomial for every element of x1 _Exercise 20Define x and y as followsgtgt x = -55gtgt y = 02x^3 - x + 2 a 3rd order polynomialgtgt y = y + randn(111) add some noise to yDetermine the 3rd order polynomial fitting y (note that because of added noise the coefficients are differentthat originally chosen) Try some other polynomials as well Plot the results in a figure _42 InterpolationThe simplest way to examine an interpolation is by displaying the function plots with the command plot157-161 The neighboring data points are connected with straight lines This is called a linear interpolation Whenmore data-points are taken into account the effect of interpolation becomes less visible Analyzegtgt x1 = linspace(0 2pi2)gtgt x2 = linspace(0 2pi4)gtgt x3 = linspace(0 2pi16)gtgt x4 = linspace(0 2pi256)gtgt plot(x1sin(x1)x2sin(x2)x3sin(x3)x4sin(x4))gtgt legend(rsquo2 pointsrsquorsquo4 pointsrsquorsquo16 pointsrsquorsquo256 pointsrsquo)

5 Numerical analysisNumerical analysis can be used whenever it is impossible or very difficult to determine the analytical solutionMatlab can be used to find for example the minimum maximum or integral of a certain function51 Evaluation of a functionAs said before the command plot plots a function by connecting defined data points Sometimes however a168-173 function is constant and not very interesting over some range and then acts unexpectedly wildly over anotherWith plot this function might be misinterpreted The command fplot is then useful An examplegtgt x = 0pi82pigtgt y = sin (8x)gtgt plot (x y rsquobrsquo)gtgt hold ongtgt fplot (rsquosin (8z)rsquo [0 2pi] rsquorrsquo)gtgt title (rsquosin (8z)rsquo)gtgt hold off20Command Resultfplot (rsquofunrsquo [min x max x]) plots the function fun for min x till max xfmin (rsquofunrsquo min x max x) gives the x-value of the miminum of thefunction fun between min x and max xfzero (rsquofunrsquo x0) gives the x-value for which the functionfun is zero in the neighborhood of x0Table 6 Evaluation of a functionExecution of these commands results in a figure with an almost straight blue line and a red sine fplot canalso be used to plot a defined functiongtgt f = rsquosin (8z)rsquogtgt fplot (f [0 2pi] rsquorrsquo)gtgt title (f)Other useful commands for a detailed study of a range of a function are listed in Table 6Exercise 21The command fmax does not exist Use one or more of the commands from Table 6 to determine the maximumof the function x cos(x) for 10 lt x lt 15 _52 Integration and differentiationThe integral- or the surface underneath a 2D function- can be determined with the command trapz trapz173-182 does this by measuring the surface between the x-axis and the -by a straight line connected- data points Theaccuracy of this method depends on the distance between the data pointsgtgt x = 00510 y = 05 sqrt (x) + x sin (x) area1 = trapz (x y)

area1 =181655gtgt x = 000510 y = 05 sqrt (x) + x sin (x) area2 = trapz (x y)area2 =183846Differentiation is done by determining the slope in each data point Numerically this is done by first fitting apolynomial followed by differentiating this functiongtgt x = 010gtgt y = [-10 24 102 -158 284 276 775 35 483 522 751]gtgt p = polyfit (x y 5)p = 00026 -00554 03634 -06888 02747 00877gtgt dp = polyder (p)dp = 00132 -02216 10903 -13776 02747gtgt x1 = linspace (0 10 200)gtgt z = polyval (p x1)gtgt dz = polyval (dp x1)gtgt plot (x y rsquog-rsquo x1 z rsquobrsquo x1 dz rsquorrsquo)gtgt legend (rsquodata pointsrsquo rsquocurve fitrsquo rsquoderivativersquo)Exercise 22Determine the integral and derivative of the 4th polynomial fitted through (xy) with x = [4 5 6 7 8 9 1011 12 13] y = [1284 1200 724 -096 -1116 -2096 -2700 -2496 -956 2544] _

6 Control flowAs you know it is possible to execute more than one command at the same time (see section 11) Theseparate commands should then be divided by commarsquos (to display the output) or by semicolons (to suppress21output display) Control flow loops increase the number of possibilities A control flow structure is a block ofcommands that allows conditional code execution and making loops61 Logical and relational operatorsTo use control flow commands it is necessary to perform operations that result in logical values TRUE or88-91 FALSE In Matlab the result of a logical operation is 1 if it is true and 0 if it is false Table 7 shows therelational and logical operations2 Another way to get to know more about them is to type help relop Therelational operators lt lt= gt gt= == and ~= can be used to compare two arrays of the same size or anarray to a scalar The logical operators amp | and ~ allow for the logical combination or negation of relationaloperators In addition three functions are also available xor any and all (use help to find out more)Important The logical amp and | have the equal precedence in Matlab which means that those operatorsassociate from left to right A common situation isgtgt b = 10gtgt 1 | b gt 0 amp 0ans =0gtgt (1 | b gt 0) amp 0 this indicates the same as aboveans =0gtgt 1 | (b gt 0 amp 0)ans =1This shows that you should always use brackets to indicate in which way the operators should be evaluatedCommand Resulta = (b gt c) a is 1 if b is larger than c Similar are lt gt= and lt=a = (b == c) a is 1 if b is equal to ca = (b ~= c) a is 1 if b is not equal ca = ~b logical complement a is 1 if b is 0a = (b amp c) logical AND a is 1 if b = TRUE AND c = TRUEa = (b | c) logical OR a is 1 if b = TRUE OR c = TRUETable 7 Relational and logical operationsExercise 23Predict and check the result of each of the operations of Table 7 for b = 0 and c = -1 _Exercise 24Define two vectors with seven elements (randn(17)) and perform all logical operations including xor anyand all _Exercise 25While doing logical operations between a vector and a scalar each element of the vector is compared to thescalar Predict and check the result of each logical operator for the vector b = [2 31 -40 0] and the scalarc = 0 _Before moving on check whether you now understand the following relations

gtgt a = randperm(10) a random permutation of the numbers from 1 to 10gtgt b = 110gtgt b - (a lt= 7) subtracts from b a 0-1 vector taking 1 for a lt= 7 and 0 otherwisegtgt (a gt= 2) amp (a lt 4) returns ones at positions where 2 lt= a lt 4gtgt ~(b gt 4) returns ones at positions where b lt= 4gtgt (a == b) | b == 3 returns ones at positions where a is equal to b or b is equal to 3gtgt any (a gt 5) returns 1 when ANY of the a elements are larger than 5gtgt any (b lt 5 amp a gt 8) returns 1 when there in the evaluated expressiongtgt (b lt 5 amp a gt 8) appears at least one 1gtgt all (b gt 2) returns 1 when ALL b elements are larger than 22rdquoequal tordquo in the table on page 88 of rdquoThe Student Edition of Matlabrdquo must be rdquo==rdquo instead of rdquo=rdquo2262 Conditional code executionSelection control structures if-blocks are used to decide which instruction to execute next depending whether117-119 expression is TRUE or not The general description is given below In the examples below the command dispis frequently used This command displays on the screen the text between the quotesbull if endSyntaxif logical_expressionstatement1statement2endExampleif (a gt 0)b = adisp (rsquoa is positiversquo)endbull if else endSyntaxif logical_expressionblock of statementsevaluated if TRUEelseblock of statementsevaluated if FALSEendExampleif (temperature gt 100)disp (rsquoAbove boilingrsquo)toohigh = 1elsedisp (rsquoTemperature is OKrsquo)toohigh = 0endbull if elseif else endSyntaxif logical_expression1block of statements evaluatedif logical_expression1 is TRUEelseif logical_expression2block of statements evaluatedif logical_expression2 is TRUEelseblock of statements evaluatedif no other expression is TRUEendExampleif (height gt 190)disp (rsquovery tallrsquo)elseif (height gt 170)disp (rsquotallrsquo)elseif (height lt 150)disp (rsquosmallrsquo)

elsedisp (rsquoaveragersquo)endRemark To do the exercises below a script m-file will be useful It is an external file that contains asequence of Matlab commands What you need to do is to open an editor enter all commands needed forthe solution of a task save it with the extension rsquomrsquo (eg mytaskm) and then run it from the CommandWindow by typing mytask To open the Matlab editor go to the File menu-bar choose the Open optionand then m-file A new window will appear where you can write your scripts and save them on the disk Allcommands in the script will be executed in Matlab You will learn more on script m-files in section 91Important m-script file must be saved in one of the directories in Matlabrsquos pathAn example A script shortm can be created from the two lines given below and run by calling shortx = 0054plot (x sin(x) rsquo-rsquo)Exercise 26Create a script that asks for a number N and computes the drag coefficient C depending on the Reynoldrsquos23number N (make use of the if elseif construction) The command input might be useful here(read pages 32-33 from rdquoThe Student Edition of Matlabrdquoor use help)C =8gtgtgtltgtgtgt0 N _ 024N N 2 (0 01]24N (1 + 014N07) N 2 (01 1e3]043 N 2 (1e3 5e5]019 minus 8e4N N gt 5e5Check whether your script works correctly Compute the drag coefficient for eg N = -3e3 001 56 1e3 3e6(remember that eg 3e3 is a Matlab notation of 3 _ 103) _Exercise 27Write a script that asks for an integer and checks whether it can be divided by 2 or 3 Consider all possibilitiessuch as divisible by both 2 and 3 divisible by 2 and not by 3 etc (use the command rem) _Another selection structure is switch which switches between several cases depending on an expression which119-120 is either a scalar or a stringSyntaxswitch expressioncase choice1block of commands1case choice2a choice2bblock of commands2otherwiseblock of commandsendExamplemethod = 2switch methodcase 12disp(rsquoMethod is linearrsquo)case 3disp(rsquoMethod is cubicrsquo)case 4disp(rsquoMethod is nearestrsquo)otherwisedisp(rsquoUnknown methodrsquo)endThe statements following the first case where the expression matches the choice are executed Thisconstruction can be very handy to avoid long if elseif else end constructions Theexpression can be a scalar or a string A scalar expression matches a choice if expression == choice Astring expression matches a choice if strcmp(expression choice) returns 1 (is true) (strcmp is a commandcomparing two strings)Important Note that the switch-construction only allows the execution of one group of commandsExercise 28Assume that the months are represented by numbers from 1 to 12 Write a script that asks you to provide a

month and returns the number of days in that particular month Alternatively write a script that asks youto provide a month name (eg rsquoJunersquo) instead of a number Use the switch-construction _63 LoopsIteration control structures loops are used to repeat a block of statements until some condition is met Two114-117 types of loops existbull the for loop that repeats a group of statements a fixed number of timesSyntaxfor index = firststeplastblock of statementsendExamplesumx = 0for i=1length(x)sumx = sumx + x(i)end24You can specify any step including a negative value The index of the for-loop can be also a vectorSee some examples of possible variationsExample 1for i=12nendExample 2for i=n-13endExample 3for x=0054disp(x^2)endExample 4for x=[25 9 81]disp(sqrt(x))endbull while loop which evaluates a group of commands as long as expression is TRUESyntaxwhile expressionstatement1statement2statement3endExampleN = 100iter = 1msum = 0while iter lt= Nmsum = msum + iteriter = iter + 1endExercise 29Given the vectors x and y write a script computing the a matrix whose elements should be created accordingto a formula given below (make use of the length command to check the number of elements in both vectors)- aij = yixj (make sure that a division by zero will not occur)- bij = xi _ yj

- cij = 1 max (xi yj)_Exercise 30Determine the sum of the first 50 squared numbers with a control loop _Exercise 31Write a script to find the largest value n such that the sum p13 + p23 + + pn3 is less than 1000 _optionalExercise 32Write a script that transposes a matrix A Check its correctness with the Matlab operation Arsquo _Exercise 33

Write a script that asks for a temperature in degrees Celsius tc and computes the equivalent temperature indegrees Fahrenheit tf (use the formula tf = 95 _ tc + 32) The script should keep running until no numberis provided to convert The functions input and isempty (use help to learn more) should be useful here _end optional

64 Evaluation of logical and relational expressions in the control flow structuresThe relational and logical expressions may become more complicated It is not difficult to operate on them ifyou understand how they are evaluated To explain more details let us consider the following exampleif (~isempty(data)) amp (max(data) lt 5)endThis construction of the if-block is necessary to avoid comparison if data happens to be an empty matrix Insuch a case you cannot evaluate any expression and Matlab gives an error The amp operator returns 1 only ifboth expressions ~isempty (data) and max(data) lt 5 are true and 0 otherwise When data is an emptymatrix the next expression is not evaluated since the whole amp-expression is already known to be false Thesecond expression is checked only if data is a non-empty matrix Remember to put logical expression unitsbetween brackets to avoid wrong evaluations25Important The fact that computers make use of floating-point arithmetic means that often you should becareful when comparing two floating-point numbers just byif (x == y)end(Of course such a construction is allowed eg when you know that x and y represent integers) Instead of theabove construction you may try using thisif (abs (x - y) lt tolerance) eg tolerance = 1e-10endExercise 34Consider the following examplemax_iter = 50tolerance = 1e-4iter = 0xold = 01x = 1while (abs (x - xold) gt tolerance) amp (iter lt max_iter)xold = xx = cos(xold)iter = iter + 1endThis short program tries to solve the equation cos(x) = x (x is the solution found) Make the script solve cosfrom the presented code Note that the while-loop is repeated as long as both conditions are true If eitherthe condition (|x - xold| lt= tolerance) or (iter gt= max iter) is fulfilled then the loop is quitted Runthe script solve cos for different tolerance parameters eg 1e-3 1e-6 1e-8 1e-10 etc Use format long tocheck more precisely how much the found x is really different from cos(x) For each tolerance value checkthe number of performed iterations (iter value) _Exercise 35Create the script solve cos2 which is equal to the one given replacing the while-loop condition bywhile (abs (x - xold) gt tolerance) | (iter lt max_iter)Try to understand the difference and confirm your expectations by running solve cos2 What happens toiter _optional

65 Numerical analysis and the control flow structuresTake a look at the problem of a Taylor expansion The series will be determined numerically until the additionalterms are smaller than a defined precision Look at the Taylor expansion of 11minusx = 1 + x + x2 + withx = 042s = 0 x = 1 s = 0 x = 1x0 = 042 x0 = 042while (x gt 1e-6) or while (x gt (1e-6)s)s = s + x s = s + xx = x x0 x = x x0end endThe approximation of 11minusx is returned in s (first letter of sum) In the first case (on the left) the iteration

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 13: Introduction to Programming Using Matlab

whose columns are the corresponding eigenvectors of AS = svd (A) S is a vector containing the singular values of A[U S V] = svd (A) S is a diagonal matrix of the same dimension as Awith nonnegative diagonal elements in decreasing orderThe columns U and V are the accompanying singular vectorsx = linspace(a b n) generates a vector x of n equally spaced points between a and bx = logspace(a b n) generates a vector x starting at 10a and ended at 10b containing n valuesA = diag (v) gives a diagonal matrix with the elements v1 v2 vn on the diagonalA = eye (n) A is a n times n identity matrixA = zeros (n m) A is a n times m matrix with zeros (default m = n)A = rand (n m) A is a n times m matrix with elements uniformly distributed between 0 and 1A = randn (n m) ditto - with elements standard normal distributedv = max (A) v becomes a vector with the maximum value of the elements in each column of Aor v is the maximum of all elements if A is a vectorv = min (A) ditto - with minimumv = sum (A) ditto - with sumTable 3 Frequently used matrix operations and functions12Transposing a vector changes it from a row to a column or the other way around This idea can be extendedto a matrix where transposing interchanges rows with the corresponding columns as in the examplegtgt A2 A2rsquoA2 =1 2 3 4-1 1 3 5ans =1 -12 13 34 5gtgt size(A2) returns the size (dimensions) of a matrixans =2 4gtgt size(A2rsquo)ans =4 2There exists also some built-in matrices of size specified by the user (see Table 2) A few examples are givenbelowgtgt E = [] an empty matrix of 0-by-0 elementsE =[]gtgt I = eye(3) the identity matrixI =1 0 00 1 00 0 1gtgt B = rand(23) a matrix of random numbers you will get a different one00227 09101 0922200299 00640 03309gtgt O = ones(32)O =1 11 11 1gtgt r = [1 3 -2] R = diag(r) create a diagonal matrix with r on the diagonalR =1 0 00 3 00 0 -2gtgt v = linspace(124) a vector is also an example of a matrixv =10000 13333 16667 20000It is often needed to build a larger matrix from the smaller onesgtgt x = [4 -1] y = [-1 4]x =4

-1y =-1 4gtgt X = [x yrsquo] X consists of the columns x and yrsquoX =4 -1-1 4gtgt T = [ -1 3 4 4 5 6] t = 1313gtgt T2 = [T t] add to T a new row namely the row vector t getting T2T2 =-1 3 44 5 61 2 3gtgt G = [1 5 4 5 0 2] G is a matrix of the 3-by-2 size check size(G)gtgt T3 = [T2 G] T3 consists of T2 and new columns being the colums of GT3 = added at the end of T2-1 3 4 1 54 5 6 4 51 2 3 0 2gtgt [diag(56) ones(32)]ans =5 00 61 11 11 1A part can be extract from a matrix in a similar way as from a vector Each element in the matrix is indexedby a row and a column to which it belongs Mathematically the element from the i-th row and the j-thcolumn of the matrix A is denoted by Aij Matlab provides the A(ij) notationgtgt A = [13 46 79]A =1 2 34 5 67 8 9gtgt A(12) A(23) A(31)ans =2ans =6ans =7gtgt A(43) A is a 3-by-3 matrix Index exceeds matrix dimensionsgtgt A(23) = A(23) + 2A(11)A =1 2 34 5 87 8 9Having defined a matrix it is easy to extended it automatically For the matrix A it can be done eg asfollowsgtgt A(52) = 5 assign 5 to the position (52) the uninitializedA = elements become zeros1 2 34 5 87 8 90 0 00 5 0Different parts of the matrix A can be now extractedgtgt A(2) extract the 2nd column of Aans =25814

05gtgtgt A(34) extract the rows 3rd and 4th of Aans =7 8 90 0 0gtgt A(2312) extract a part of Aans =4 57 8If needed the other zero elements of the matrix A can be also defined by eggtgt A(4) = [1 2 3] assign vector [1 2 3] to the 4th row of Agtgt A(5[13]) = [4 5] a rsquoshortcutrsquo when assigning A(51) = 4 and A(53) = 5gtgt A how does the matrix A look like nowAs you have seen in the examples above it is possible to manipulate (groups of) matrix-elements Thecommands are shortly explained in Table 2Exercise 9Define the matrix A = [14 58 1 1 1 1] Predict and check the result ofgtgt B = A(3)gtgt C = A(1322)gtgt A(11) = 9gtgt A(2313) = [0 0 0 0 0 0]gtgt A(l212) = [l l 3 3]gtgt A = A(3314)_Exercise 10Define the matrices T=[ 3 4 1 8 -4 3] A = [diag(-123) T -4 4 1 2 1] Perform the followingoperations on the matrix Abull extract a vector consisting of the 2nd and 4th elements of the 3rd rowbull find the minimum of the 3rd columnbull find the maximum of the 2nd rowbull compute the sum of the 2nd columbull compute the mean of the 1st and 4th rowsbull extract the submatrix consisting of the 1st and 3rd rows and all columnsbull extract the submatrix consisting of the 1st and 2nd rows and the 3rd 4th and 5th columnsbull compute the total sum of the 1st and 2nd rowsbull add 3 to all elements of the 2nd and 3rd colums_Table 3 shows some frequently used matrix operations and functions A few examples are provided belowgtgt B = rand(23) a matrix of random numbers you will get a different oneB =09501 06068 0891302311 04860 07621gtgt B2 = [1 2 5 1 5 6]gtgt B + B2rsquo add two matrices why B2rsquo is needed instead of B2ans =19501 56068 5891322311 14860 67621gtgt S = ans4 divide all elements of the matrix ans by 4S =04875 14017 1472805578 03715 1690515gtgt C = [1 -1 4 7 0 -1]gtgt B C matrix multiplication is not defined for B and C Error using ==gt Inner matrix dimensions must agreegtgt B C but you can multiply element-by-elementans =09501 -06068 3565216180 0 -07621gtgt D = B Crsquo or you can make the multiplication legal Crsquo is now 3-by-2D =39085 5759627935 08559

gtgt D^3 this is equivalent to D D Dans =1992503 2041413990133 910548gtgt D^3 - 2 do for all elements raise to the power 3 and subtract 2ans =577069 1890638198005 -13731gtgtgtgt r = [1 3 -2]r B2 this is a legal operation r is a 1-by-3 matrix and B2 isans = 3-by-2 matrix B2 r is an illegal operation6 -7Remind that an n-by-k matrix A (having n rows and k columns) can be multiply by another matrix B onlyif B has k rows ie S is of the k-by-m size (m is arbitrary) As a result you get an n-by-m matrixA ˙B = C A 2 Rntimesk B 2 Rktimesm C 2 Rntimesm

RemarkYou can now compute the inner product between two vectors x and y xT y = Pi xi yi in a simple waygtgt f = [-1 3 5] a column vectorgtgt v = [-1 2 7] a column vectorgtgt frsquo v this is the inner productans =42gtgt f vrsquo be careful now a 3-by-1 matrix is multiplied by a 1-by-3gtgt matrix which results in a 3-by-3 matrix (the outer product)ans =1 -2 -7-3 6 21-5 10 35gtgt f v this is an element-by-element multiplication1635gtgt sum (f v) this is an another way to compute the inner productans =42Exercise 11Perform all operations from Table 3 using chosen matrices A and B vector v and scalars k a b n and m _Exercise 12Let A be a random 3 times 3 matrix and b a random 3 times 1 vector Given that Ax = b then x = Aminus1b Find x(there exist at least two possible commands to do this look at Table 3) _optionalThe concept of an empty matrix [] is also very useful in Matlab For instance a few columns or rows canbe removed from a matrix by assigning an empty matrix to it Try for example16Symbol Color Symbol Styley yellow dotted liner red o circlesg green - solid lineb blue - dashdotted lineTable 4 Plot colors and stylesgtgt C = [1 2 3 4 5 6 7 8 1 1 1 1]gtgt D = C D(2) = [] now a copy of C is in D remove the 2nd column of Dgtgt C ([13]) = [] remove the rows 1 and 3 from Cend optional

3 VisualizationMatlab can be used to visualize the results of an experiment Therefore you should define variables each ofthem containing all values of one parameter to plot31 Simple plotsWith the command plot a graphical display can be made plot(y) draws the points (1 y(1)) (2 y(2)) 184 (n y(n)) and connects the points with a straight line plot(xy) does the same for (x(1) y(1)) (x(2) y(2)) (x(n) y(n)) x and y have to be row- or column vectors of equal lengthThe commands loglog semilogx and semilogy are similar to plot except that they use logarithmic axesExercise 13Type the following commands after predicting the resultgtgt x = 0330

gtgt y = 2^[010] this is the same as y = [1 2 4 8 16 32 64 128 256 512 1024]gtgt plot(xy) to get a graphic representationgtgt semilogy(xy) to get logarithmic axesAs you can see the same figure is used for both plot commands The previous function is removed as soonas the next is displayed The command figure gives you an extra figure Repeat the previous commandsbut generate a new figure before plotting the second function so that you can see both functions in separatewindows You can also switch back to a figure using figure(n) where n is its number _Exercise 14Make a plot such that the coordinates (2 6) (25 18) (5 175) (42 125) and (212) are connected by aline _Exercise 15Plot the function y = sin(x) + x minus x cos(x) in two separate figures for the intervals 0 lt x lt 30 andminus100 lt x lt 100 _32 Several functions in one figureWhen more than one function is plotted in one figure it might be useful to use different markers and colors184-188197-201Table 4 shows a few possibilities help plot shows allThere are different ways to get more than one function into a figure The first one is with the command holdon After this command all functions will be plotted in the same figure until the command hold off is usedAn examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt plot (x1 y1 rsquordrsquo)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)17gtgt hold ongtgt plot (x2 y2 rsquoy-rsquo)gtgt plot (x1y1rsquok-rsquo)gtgt hold offA second method to display more than one function in one figure is to plot several functions at the same timeThe next commands will have the same results as the commands in the previous examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt plot (x1 y1rsquordrsquo x2 y2 rsquoy-rsquo x1 y1 rsquok-rsquo)It is also possible to get more than one figure in one figure window With the command subplot the windowcan be horizontally and vertically divided into any number of subfiguresgtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt subplot(131) plot (x1 y1rsquordrsquo)gtgt subplot(132) plot (x2 y2 rsquoy-rsquo)gtgt subplot(133) plot (x1 y1 rsquok-rsquo)optional

33 Other 2D plotting featuresIn the introduction of this chapter some commands similar to plot loglog semilogx and semilogy were201-211 mentioned There are however more ways to display dataExercise 16To get an impression of other visualizations type the following commands and describe the result (note thatthe command figure creates a new figure window)gtgt figure bar plot of a bell shaped curvegtgt x = -290229gtgt bar (x exp (-xx))gtgt figure stairstep plot of a sine wavegtgt x = 002510gtgt stairs (x sin (x))gtgt figure errorbar plotgtgt x = -2012gtgt y = erf (x) error function check help if you are interestedgtgt e = rand (size (x)) 10gtgt errorbar (x y e)

_end optional

34 PrintingBefore printing a figure you made you might want to add some information such as a title or change the189-196 lay-out a little Table 5 shows some of the commands that can be usedExercise 17Plot the functions y1 = sin(4x) y2 = x cos(x) y3 = (x + 1)minus1px for x = 0 025 10 and a single point(x y) = (4 5) in one figure with different colors and styles Make a legend containing the three functionsMake labels for both axes and a title Add a text to the single point saying single point Change the minimumand maximum values of the axes such that function y3 can be looked at in more detail _When the displayed figure is to your liking you can print it to paper The easiest way to do this is to click onFile in the menu-bar and to choose Print If in the print window you click OK your figure will be printed onthe printer indicated in the print window18Command Resultgrid onoff adds a grid to the plot at the tick marks or removes itaxis([xmin xmax ymin ymax]) sets the minimum and maximum values of the axesbox offon removes the axes box or shows itxlabel(rsquotextrsquo) plots the label text on the x axisylabel(rsquotextrsquo) plots the label text on the y axistitle(rsquotextrsquo) plots a title above the graphtext(xyrsquotextrsquo) adds text at the point (xy)gtext(rsquotextrsquo) adds text at a manually (with a mouse) indicated pointlegend(rsquofun1rsquorsquofun2rsquo) plots a legend box (move it with your mouse) to name your functionslegend off deletes the legend boxTable 5 Plot-manipulationsThere is also a print command which can be used to send a figure to a printer or output it to a file Youcan optionally specify a print device (ie an output format such as tiff or postscript) and options that controlvarious characteristics of the printed file (ie which Figure to print etc) You can also print to a file if youspecify the file name If you do not provide an extension print adds one Since they are many parametersthey will not be explained here (check help print to learn more) Instead try to understand the examplesgtgt print -dwinc print the current Figure to the current printer in colorgtgt print -f1 -deps myfileeps print Figure no1 to the file myfileeps in blackgtgt print -f1 -depsc myfileceps print Figure no1 to the file myfilecoleps in colorgtgt print -dtiff myfile1tiff print the current Figure to the file myfile1tiffgtgt print -dpsc myfile1cps print the current Figure to the file myfile1ps in colorgtgt print -f2 -djpeg myfile2 print Figure no2 to the file myfile2jpgExercise 18Exercise with printing (especially to a file) the figure from Exercise 16 _

4 Curve fitting and interpolationThere are two ways to describe data with an analytical function- curve fitting or regression finding a smooth curve that best fits (approximates) the data accordingto a criterion (eg best least square fit) The curve does not have to go through any of the data points- interpolation the data are assumed to be correct desired in a way to describe what happens betweenthe data points In other words given a finite set of points the goal of interpolation is to find a functionfrom a given class of functions (eg polynomials) which passes through the specified pointsThe figure below illustrates the difference between regression (curve fitting) and interpolationminus5 0 5minus6minus4minus20246810fiting a 3rd order polynomialinterpolation

41 Curve fittingMatlab interprets the best fit of a curve by the lsquoleast squares curve fittingrsquo The curve used is restricted153-15619to polynomials With the command polyfit any polynomial can be fitted to the data polyfit (x y n)finds the coefficients of a polynomial of degree n that fits the data (finds the linear relation between x and y)Letrsquos start with finding a linear regression of some datagtgt x = 010gtgt y = [-10 24 102 158 284 276 299 405 483 522 751]gtgt p = polyfit (x y 1) find the fitting polynomial of order 1p = 06772 -03914

The output of polyfit is a row vector of the polynomial coefficients the solution of this example is thereforey = 06772x minus 03914Exercise 19Execute the above example Plot the data and the fitted curve in a figure Determine the 2nd and 9th orderpolynomial of these data as well and display the solution in a figureHint x1 = linspace (xmin xmax n) results in a vector with n element evenly distributed from xmintill xmax z = polyval (p x1) calculates the values of the polynomial for every element of x1 _Exercise 20Define x and y as followsgtgt x = -55gtgt y = 02x^3 - x + 2 a 3rd order polynomialgtgt y = y + randn(111) add some noise to yDetermine the 3rd order polynomial fitting y (note that because of added noise the coefficients are differentthat originally chosen) Try some other polynomials as well Plot the results in a figure _42 InterpolationThe simplest way to examine an interpolation is by displaying the function plots with the command plot157-161 The neighboring data points are connected with straight lines This is called a linear interpolation Whenmore data-points are taken into account the effect of interpolation becomes less visible Analyzegtgt x1 = linspace(0 2pi2)gtgt x2 = linspace(0 2pi4)gtgt x3 = linspace(0 2pi16)gtgt x4 = linspace(0 2pi256)gtgt plot(x1sin(x1)x2sin(x2)x3sin(x3)x4sin(x4))gtgt legend(rsquo2 pointsrsquorsquo4 pointsrsquorsquo16 pointsrsquorsquo256 pointsrsquo)

5 Numerical analysisNumerical analysis can be used whenever it is impossible or very difficult to determine the analytical solutionMatlab can be used to find for example the minimum maximum or integral of a certain function51 Evaluation of a functionAs said before the command plot plots a function by connecting defined data points Sometimes however a168-173 function is constant and not very interesting over some range and then acts unexpectedly wildly over anotherWith plot this function might be misinterpreted The command fplot is then useful An examplegtgt x = 0pi82pigtgt y = sin (8x)gtgt plot (x y rsquobrsquo)gtgt hold ongtgt fplot (rsquosin (8z)rsquo [0 2pi] rsquorrsquo)gtgt title (rsquosin (8z)rsquo)gtgt hold off20Command Resultfplot (rsquofunrsquo [min x max x]) plots the function fun for min x till max xfmin (rsquofunrsquo min x max x) gives the x-value of the miminum of thefunction fun between min x and max xfzero (rsquofunrsquo x0) gives the x-value for which the functionfun is zero in the neighborhood of x0Table 6 Evaluation of a functionExecution of these commands results in a figure with an almost straight blue line and a red sine fplot canalso be used to plot a defined functiongtgt f = rsquosin (8z)rsquogtgt fplot (f [0 2pi] rsquorrsquo)gtgt title (f)Other useful commands for a detailed study of a range of a function are listed in Table 6Exercise 21The command fmax does not exist Use one or more of the commands from Table 6 to determine the maximumof the function x cos(x) for 10 lt x lt 15 _52 Integration and differentiationThe integral- or the surface underneath a 2D function- can be determined with the command trapz trapz173-182 does this by measuring the surface between the x-axis and the -by a straight line connected- data points Theaccuracy of this method depends on the distance between the data pointsgtgt x = 00510 y = 05 sqrt (x) + x sin (x) area1 = trapz (x y)

area1 =181655gtgt x = 000510 y = 05 sqrt (x) + x sin (x) area2 = trapz (x y)area2 =183846Differentiation is done by determining the slope in each data point Numerically this is done by first fitting apolynomial followed by differentiating this functiongtgt x = 010gtgt y = [-10 24 102 -158 284 276 775 35 483 522 751]gtgt p = polyfit (x y 5)p = 00026 -00554 03634 -06888 02747 00877gtgt dp = polyder (p)dp = 00132 -02216 10903 -13776 02747gtgt x1 = linspace (0 10 200)gtgt z = polyval (p x1)gtgt dz = polyval (dp x1)gtgt plot (x y rsquog-rsquo x1 z rsquobrsquo x1 dz rsquorrsquo)gtgt legend (rsquodata pointsrsquo rsquocurve fitrsquo rsquoderivativersquo)Exercise 22Determine the integral and derivative of the 4th polynomial fitted through (xy) with x = [4 5 6 7 8 9 1011 12 13] y = [1284 1200 724 -096 -1116 -2096 -2700 -2496 -956 2544] _

6 Control flowAs you know it is possible to execute more than one command at the same time (see section 11) Theseparate commands should then be divided by commarsquos (to display the output) or by semicolons (to suppress21output display) Control flow loops increase the number of possibilities A control flow structure is a block ofcommands that allows conditional code execution and making loops61 Logical and relational operatorsTo use control flow commands it is necessary to perform operations that result in logical values TRUE or88-91 FALSE In Matlab the result of a logical operation is 1 if it is true and 0 if it is false Table 7 shows therelational and logical operations2 Another way to get to know more about them is to type help relop Therelational operators lt lt= gt gt= == and ~= can be used to compare two arrays of the same size or anarray to a scalar The logical operators amp | and ~ allow for the logical combination or negation of relationaloperators In addition three functions are also available xor any and all (use help to find out more)Important The logical amp and | have the equal precedence in Matlab which means that those operatorsassociate from left to right A common situation isgtgt b = 10gtgt 1 | b gt 0 amp 0ans =0gtgt (1 | b gt 0) amp 0 this indicates the same as aboveans =0gtgt 1 | (b gt 0 amp 0)ans =1This shows that you should always use brackets to indicate in which way the operators should be evaluatedCommand Resulta = (b gt c) a is 1 if b is larger than c Similar are lt gt= and lt=a = (b == c) a is 1 if b is equal to ca = (b ~= c) a is 1 if b is not equal ca = ~b logical complement a is 1 if b is 0a = (b amp c) logical AND a is 1 if b = TRUE AND c = TRUEa = (b | c) logical OR a is 1 if b = TRUE OR c = TRUETable 7 Relational and logical operationsExercise 23Predict and check the result of each of the operations of Table 7 for b = 0 and c = -1 _Exercise 24Define two vectors with seven elements (randn(17)) and perform all logical operations including xor anyand all _Exercise 25While doing logical operations between a vector and a scalar each element of the vector is compared to thescalar Predict and check the result of each logical operator for the vector b = [2 31 -40 0] and the scalarc = 0 _Before moving on check whether you now understand the following relations

gtgt a = randperm(10) a random permutation of the numbers from 1 to 10gtgt b = 110gtgt b - (a lt= 7) subtracts from b a 0-1 vector taking 1 for a lt= 7 and 0 otherwisegtgt (a gt= 2) amp (a lt 4) returns ones at positions where 2 lt= a lt 4gtgt ~(b gt 4) returns ones at positions where b lt= 4gtgt (a == b) | b == 3 returns ones at positions where a is equal to b or b is equal to 3gtgt any (a gt 5) returns 1 when ANY of the a elements are larger than 5gtgt any (b lt 5 amp a gt 8) returns 1 when there in the evaluated expressiongtgt (b lt 5 amp a gt 8) appears at least one 1gtgt all (b gt 2) returns 1 when ALL b elements are larger than 22rdquoequal tordquo in the table on page 88 of rdquoThe Student Edition of Matlabrdquo must be rdquo==rdquo instead of rdquo=rdquo2262 Conditional code executionSelection control structures if-blocks are used to decide which instruction to execute next depending whether117-119 expression is TRUE or not The general description is given below In the examples below the command dispis frequently used This command displays on the screen the text between the quotesbull if endSyntaxif logical_expressionstatement1statement2endExampleif (a gt 0)b = adisp (rsquoa is positiversquo)endbull if else endSyntaxif logical_expressionblock of statementsevaluated if TRUEelseblock of statementsevaluated if FALSEendExampleif (temperature gt 100)disp (rsquoAbove boilingrsquo)toohigh = 1elsedisp (rsquoTemperature is OKrsquo)toohigh = 0endbull if elseif else endSyntaxif logical_expression1block of statements evaluatedif logical_expression1 is TRUEelseif logical_expression2block of statements evaluatedif logical_expression2 is TRUEelseblock of statements evaluatedif no other expression is TRUEendExampleif (height gt 190)disp (rsquovery tallrsquo)elseif (height gt 170)disp (rsquotallrsquo)elseif (height lt 150)disp (rsquosmallrsquo)

elsedisp (rsquoaveragersquo)endRemark To do the exercises below a script m-file will be useful It is an external file that contains asequence of Matlab commands What you need to do is to open an editor enter all commands needed forthe solution of a task save it with the extension rsquomrsquo (eg mytaskm) and then run it from the CommandWindow by typing mytask To open the Matlab editor go to the File menu-bar choose the Open optionand then m-file A new window will appear where you can write your scripts and save them on the disk Allcommands in the script will be executed in Matlab You will learn more on script m-files in section 91Important m-script file must be saved in one of the directories in Matlabrsquos pathAn example A script shortm can be created from the two lines given below and run by calling shortx = 0054plot (x sin(x) rsquo-rsquo)Exercise 26Create a script that asks for a number N and computes the drag coefficient C depending on the Reynoldrsquos23number N (make use of the if elseif construction) The command input might be useful here(read pages 32-33 from rdquoThe Student Edition of Matlabrdquoor use help)C =8gtgtgtltgtgtgt0 N _ 024N N 2 (0 01]24N (1 + 014N07) N 2 (01 1e3]043 N 2 (1e3 5e5]019 minus 8e4N N gt 5e5Check whether your script works correctly Compute the drag coefficient for eg N = -3e3 001 56 1e3 3e6(remember that eg 3e3 is a Matlab notation of 3 _ 103) _Exercise 27Write a script that asks for an integer and checks whether it can be divided by 2 or 3 Consider all possibilitiessuch as divisible by both 2 and 3 divisible by 2 and not by 3 etc (use the command rem) _Another selection structure is switch which switches between several cases depending on an expression which119-120 is either a scalar or a stringSyntaxswitch expressioncase choice1block of commands1case choice2a choice2bblock of commands2otherwiseblock of commandsendExamplemethod = 2switch methodcase 12disp(rsquoMethod is linearrsquo)case 3disp(rsquoMethod is cubicrsquo)case 4disp(rsquoMethod is nearestrsquo)otherwisedisp(rsquoUnknown methodrsquo)endThe statements following the first case where the expression matches the choice are executed Thisconstruction can be very handy to avoid long if elseif else end constructions Theexpression can be a scalar or a string A scalar expression matches a choice if expression == choice Astring expression matches a choice if strcmp(expression choice) returns 1 (is true) (strcmp is a commandcomparing two strings)Important Note that the switch-construction only allows the execution of one group of commandsExercise 28Assume that the months are represented by numbers from 1 to 12 Write a script that asks you to provide a

month and returns the number of days in that particular month Alternatively write a script that asks youto provide a month name (eg rsquoJunersquo) instead of a number Use the switch-construction _63 LoopsIteration control structures loops are used to repeat a block of statements until some condition is met Two114-117 types of loops existbull the for loop that repeats a group of statements a fixed number of timesSyntaxfor index = firststeplastblock of statementsendExamplesumx = 0for i=1length(x)sumx = sumx + x(i)end24You can specify any step including a negative value The index of the for-loop can be also a vectorSee some examples of possible variationsExample 1for i=12nendExample 2for i=n-13endExample 3for x=0054disp(x^2)endExample 4for x=[25 9 81]disp(sqrt(x))endbull while loop which evaluates a group of commands as long as expression is TRUESyntaxwhile expressionstatement1statement2statement3endExampleN = 100iter = 1msum = 0while iter lt= Nmsum = msum + iteriter = iter + 1endExercise 29Given the vectors x and y write a script computing the a matrix whose elements should be created accordingto a formula given below (make use of the length command to check the number of elements in both vectors)- aij = yixj (make sure that a division by zero will not occur)- bij = xi _ yj

- cij = 1 max (xi yj)_Exercise 30Determine the sum of the first 50 squared numbers with a control loop _Exercise 31Write a script to find the largest value n such that the sum p13 + p23 + + pn3 is less than 1000 _optionalExercise 32Write a script that transposes a matrix A Check its correctness with the Matlab operation Arsquo _Exercise 33

Write a script that asks for a temperature in degrees Celsius tc and computes the equivalent temperature indegrees Fahrenheit tf (use the formula tf = 95 _ tc + 32) The script should keep running until no numberis provided to convert The functions input and isempty (use help to learn more) should be useful here _end optional

64 Evaluation of logical and relational expressions in the control flow structuresThe relational and logical expressions may become more complicated It is not difficult to operate on them ifyou understand how they are evaluated To explain more details let us consider the following exampleif (~isempty(data)) amp (max(data) lt 5)endThis construction of the if-block is necessary to avoid comparison if data happens to be an empty matrix Insuch a case you cannot evaluate any expression and Matlab gives an error The amp operator returns 1 only ifboth expressions ~isempty (data) and max(data) lt 5 are true and 0 otherwise When data is an emptymatrix the next expression is not evaluated since the whole amp-expression is already known to be false Thesecond expression is checked only if data is a non-empty matrix Remember to put logical expression unitsbetween brackets to avoid wrong evaluations25Important The fact that computers make use of floating-point arithmetic means that often you should becareful when comparing two floating-point numbers just byif (x == y)end(Of course such a construction is allowed eg when you know that x and y represent integers) Instead of theabove construction you may try using thisif (abs (x - y) lt tolerance) eg tolerance = 1e-10endExercise 34Consider the following examplemax_iter = 50tolerance = 1e-4iter = 0xold = 01x = 1while (abs (x - xold) gt tolerance) amp (iter lt max_iter)xold = xx = cos(xold)iter = iter + 1endThis short program tries to solve the equation cos(x) = x (x is the solution found) Make the script solve cosfrom the presented code Note that the while-loop is repeated as long as both conditions are true If eitherthe condition (|x - xold| lt= tolerance) or (iter gt= max iter) is fulfilled then the loop is quitted Runthe script solve cos for different tolerance parameters eg 1e-3 1e-6 1e-8 1e-10 etc Use format long tocheck more precisely how much the found x is really different from cos(x) For each tolerance value checkthe number of performed iterations (iter value) _Exercise 35Create the script solve cos2 which is equal to the one given replacing the while-loop condition bywhile (abs (x - xold) gt tolerance) | (iter lt max_iter)Try to understand the difference and confirm your expectations by running solve cos2 What happens toiter _optional

65 Numerical analysis and the control flow structuresTake a look at the problem of a Taylor expansion The series will be determined numerically until the additionalterms are smaller than a defined precision Look at the Taylor expansion of 11minusx = 1 + x + x2 + withx = 042s = 0 x = 1 s = 0 x = 1x0 = 042 x0 = 042while (x gt 1e-6) or while (x gt (1e-6)s)s = s + x s = s + xx = x x0 x = x x0end endThe approximation of 11minusx is returned in s (first letter of sum) In the first case (on the left) the iteration

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 14: Introduction to Programming Using Matlab

-1y =-1 4gtgt X = [x yrsquo] X consists of the columns x and yrsquoX =4 -1-1 4gtgt T = [ -1 3 4 4 5 6] t = 1313gtgt T2 = [T t] add to T a new row namely the row vector t getting T2T2 =-1 3 44 5 61 2 3gtgt G = [1 5 4 5 0 2] G is a matrix of the 3-by-2 size check size(G)gtgt T3 = [T2 G] T3 consists of T2 and new columns being the colums of GT3 = added at the end of T2-1 3 4 1 54 5 6 4 51 2 3 0 2gtgt [diag(56) ones(32)]ans =5 00 61 11 11 1A part can be extract from a matrix in a similar way as from a vector Each element in the matrix is indexedby a row and a column to which it belongs Mathematically the element from the i-th row and the j-thcolumn of the matrix A is denoted by Aij Matlab provides the A(ij) notationgtgt A = [13 46 79]A =1 2 34 5 67 8 9gtgt A(12) A(23) A(31)ans =2ans =6ans =7gtgt A(43) A is a 3-by-3 matrix Index exceeds matrix dimensionsgtgt A(23) = A(23) + 2A(11)A =1 2 34 5 87 8 9Having defined a matrix it is easy to extended it automatically For the matrix A it can be done eg asfollowsgtgt A(52) = 5 assign 5 to the position (52) the uninitializedA = elements become zeros1 2 34 5 87 8 90 0 00 5 0Different parts of the matrix A can be now extractedgtgt A(2) extract the 2nd column of Aans =25814

05gtgtgt A(34) extract the rows 3rd and 4th of Aans =7 8 90 0 0gtgt A(2312) extract a part of Aans =4 57 8If needed the other zero elements of the matrix A can be also defined by eggtgt A(4) = [1 2 3] assign vector [1 2 3] to the 4th row of Agtgt A(5[13]) = [4 5] a rsquoshortcutrsquo when assigning A(51) = 4 and A(53) = 5gtgt A how does the matrix A look like nowAs you have seen in the examples above it is possible to manipulate (groups of) matrix-elements Thecommands are shortly explained in Table 2Exercise 9Define the matrix A = [14 58 1 1 1 1] Predict and check the result ofgtgt B = A(3)gtgt C = A(1322)gtgt A(11) = 9gtgt A(2313) = [0 0 0 0 0 0]gtgt A(l212) = [l l 3 3]gtgt A = A(3314)_Exercise 10Define the matrices T=[ 3 4 1 8 -4 3] A = [diag(-123) T -4 4 1 2 1] Perform the followingoperations on the matrix Abull extract a vector consisting of the 2nd and 4th elements of the 3rd rowbull find the minimum of the 3rd columnbull find the maximum of the 2nd rowbull compute the sum of the 2nd columbull compute the mean of the 1st and 4th rowsbull extract the submatrix consisting of the 1st and 3rd rows and all columnsbull extract the submatrix consisting of the 1st and 2nd rows and the 3rd 4th and 5th columnsbull compute the total sum of the 1st and 2nd rowsbull add 3 to all elements of the 2nd and 3rd colums_Table 3 shows some frequently used matrix operations and functions A few examples are provided belowgtgt B = rand(23) a matrix of random numbers you will get a different oneB =09501 06068 0891302311 04860 07621gtgt B2 = [1 2 5 1 5 6]gtgt B + B2rsquo add two matrices why B2rsquo is needed instead of B2ans =19501 56068 5891322311 14860 67621gtgt S = ans4 divide all elements of the matrix ans by 4S =04875 14017 1472805578 03715 1690515gtgt C = [1 -1 4 7 0 -1]gtgt B C matrix multiplication is not defined for B and C Error using ==gt Inner matrix dimensions must agreegtgt B C but you can multiply element-by-elementans =09501 -06068 3565216180 0 -07621gtgt D = B Crsquo or you can make the multiplication legal Crsquo is now 3-by-2D =39085 5759627935 08559

gtgt D^3 this is equivalent to D D Dans =1992503 2041413990133 910548gtgt D^3 - 2 do for all elements raise to the power 3 and subtract 2ans =577069 1890638198005 -13731gtgtgtgt r = [1 3 -2]r B2 this is a legal operation r is a 1-by-3 matrix and B2 isans = 3-by-2 matrix B2 r is an illegal operation6 -7Remind that an n-by-k matrix A (having n rows and k columns) can be multiply by another matrix B onlyif B has k rows ie S is of the k-by-m size (m is arbitrary) As a result you get an n-by-m matrixA ˙B = C A 2 Rntimesk B 2 Rktimesm C 2 Rntimesm

RemarkYou can now compute the inner product between two vectors x and y xT y = Pi xi yi in a simple waygtgt f = [-1 3 5] a column vectorgtgt v = [-1 2 7] a column vectorgtgt frsquo v this is the inner productans =42gtgt f vrsquo be careful now a 3-by-1 matrix is multiplied by a 1-by-3gtgt matrix which results in a 3-by-3 matrix (the outer product)ans =1 -2 -7-3 6 21-5 10 35gtgt f v this is an element-by-element multiplication1635gtgt sum (f v) this is an another way to compute the inner productans =42Exercise 11Perform all operations from Table 3 using chosen matrices A and B vector v and scalars k a b n and m _Exercise 12Let A be a random 3 times 3 matrix and b a random 3 times 1 vector Given that Ax = b then x = Aminus1b Find x(there exist at least two possible commands to do this look at Table 3) _optionalThe concept of an empty matrix [] is also very useful in Matlab For instance a few columns or rows canbe removed from a matrix by assigning an empty matrix to it Try for example16Symbol Color Symbol Styley yellow dotted liner red o circlesg green - solid lineb blue - dashdotted lineTable 4 Plot colors and stylesgtgt C = [1 2 3 4 5 6 7 8 1 1 1 1]gtgt D = C D(2) = [] now a copy of C is in D remove the 2nd column of Dgtgt C ([13]) = [] remove the rows 1 and 3 from Cend optional

3 VisualizationMatlab can be used to visualize the results of an experiment Therefore you should define variables each ofthem containing all values of one parameter to plot31 Simple plotsWith the command plot a graphical display can be made plot(y) draws the points (1 y(1)) (2 y(2)) 184 (n y(n)) and connects the points with a straight line plot(xy) does the same for (x(1) y(1)) (x(2) y(2)) (x(n) y(n)) x and y have to be row- or column vectors of equal lengthThe commands loglog semilogx and semilogy are similar to plot except that they use logarithmic axesExercise 13Type the following commands after predicting the resultgtgt x = 0330

gtgt y = 2^[010] this is the same as y = [1 2 4 8 16 32 64 128 256 512 1024]gtgt plot(xy) to get a graphic representationgtgt semilogy(xy) to get logarithmic axesAs you can see the same figure is used for both plot commands The previous function is removed as soonas the next is displayed The command figure gives you an extra figure Repeat the previous commandsbut generate a new figure before plotting the second function so that you can see both functions in separatewindows You can also switch back to a figure using figure(n) where n is its number _Exercise 14Make a plot such that the coordinates (2 6) (25 18) (5 175) (42 125) and (212) are connected by aline _Exercise 15Plot the function y = sin(x) + x minus x cos(x) in two separate figures for the intervals 0 lt x lt 30 andminus100 lt x lt 100 _32 Several functions in one figureWhen more than one function is plotted in one figure it might be useful to use different markers and colors184-188197-201Table 4 shows a few possibilities help plot shows allThere are different ways to get more than one function into a figure The first one is with the command holdon After this command all functions will be plotted in the same figure until the command hold off is usedAn examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt plot (x1 y1 rsquordrsquo)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)17gtgt hold ongtgt plot (x2 y2 rsquoy-rsquo)gtgt plot (x1y1rsquok-rsquo)gtgt hold offA second method to display more than one function in one figure is to plot several functions at the same timeThe next commands will have the same results as the commands in the previous examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt plot (x1 y1rsquordrsquo x2 y2 rsquoy-rsquo x1 y1 rsquok-rsquo)It is also possible to get more than one figure in one figure window With the command subplot the windowcan be horizontally and vertically divided into any number of subfiguresgtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt subplot(131) plot (x1 y1rsquordrsquo)gtgt subplot(132) plot (x2 y2 rsquoy-rsquo)gtgt subplot(133) plot (x1 y1 rsquok-rsquo)optional

33 Other 2D plotting featuresIn the introduction of this chapter some commands similar to plot loglog semilogx and semilogy were201-211 mentioned There are however more ways to display dataExercise 16To get an impression of other visualizations type the following commands and describe the result (note thatthe command figure creates a new figure window)gtgt figure bar plot of a bell shaped curvegtgt x = -290229gtgt bar (x exp (-xx))gtgt figure stairstep plot of a sine wavegtgt x = 002510gtgt stairs (x sin (x))gtgt figure errorbar plotgtgt x = -2012gtgt y = erf (x) error function check help if you are interestedgtgt e = rand (size (x)) 10gtgt errorbar (x y e)

_end optional

34 PrintingBefore printing a figure you made you might want to add some information such as a title or change the189-196 lay-out a little Table 5 shows some of the commands that can be usedExercise 17Plot the functions y1 = sin(4x) y2 = x cos(x) y3 = (x + 1)minus1px for x = 0 025 10 and a single point(x y) = (4 5) in one figure with different colors and styles Make a legend containing the three functionsMake labels for both axes and a title Add a text to the single point saying single point Change the minimumand maximum values of the axes such that function y3 can be looked at in more detail _When the displayed figure is to your liking you can print it to paper The easiest way to do this is to click onFile in the menu-bar and to choose Print If in the print window you click OK your figure will be printed onthe printer indicated in the print window18Command Resultgrid onoff adds a grid to the plot at the tick marks or removes itaxis([xmin xmax ymin ymax]) sets the minimum and maximum values of the axesbox offon removes the axes box or shows itxlabel(rsquotextrsquo) plots the label text on the x axisylabel(rsquotextrsquo) plots the label text on the y axistitle(rsquotextrsquo) plots a title above the graphtext(xyrsquotextrsquo) adds text at the point (xy)gtext(rsquotextrsquo) adds text at a manually (with a mouse) indicated pointlegend(rsquofun1rsquorsquofun2rsquo) plots a legend box (move it with your mouse) to name your functionslegend off deletes the legend boxTable 5 Plot-manipulationsThere is also a print command which can be used to send a figure to a printer or output it to a file Youcan optionally specify a print device (ie an output format such as tiff or postscript) and options that controlvarious characteristics of the printed file (ie which Figure to print etc) You can also print to a file if youspecify the file name If you do not provide an extension print adds one Since they are many parametersthey will not be explained here (check help print to learn more) Instead try to understand the examplesgtgt print -dwinc print the current Figure to the current printer in colorgtgt print -f1 -deps myfileeps print Figure no1 to the file myfileeps in blackgtgt print -f1 -depsc myfileceps print Figure no1 to the file myfilecoleps in colorgtgt print -dtiff myfile1tiff print the current Figure to the file myfile1tiffgtgt print -dpsc myfile1cps print the current Figure to the file myfile1ps in colorgtgt print -f2 -djpeg myfile2 print Figure no2 to the file myfile2jpgExercise 18Exercise with printing (especially to a file) the figure from Exercise 16 _

4 Curve fitting and interpolationThere are two ways to describe data with an analytical function- curve fitting or regression finding a smooth curve that best fits (approximates) the data accordingto a criterion (eg best least square fit) The curve does not have to go through any of the data points- interpolation the data are assumed to be correct desired in a way to describe what happens betweenthe data points In other words given a finite set of points the goal of interpolation is to find a functionfrom a given class of functions (eg polynomials) which passes through the specified pointsThe figure below illustrates the difference between regression (curve fitting) and interpolationminus5 0 5minus6minus4minus20246810fiting a 3rd order polynomialinterpolation

41 Curve fittingMatlab interprets the best fit of a curve by the lsquoleast squares curve fittingrsquo The curve used is restricted153-15619to polynomials With the command polyfit any polynomial can be fitted to the data polyfit (x y n)finds the coefficients of a polynomial of degree n that fits the data (finds the linear relation between x and y)Letrsquos start with finding a linear regression of some datagtgt x = 010gtgt y = [-10 24 102 158 284 276 299 405 483 522 751]gtgt p = polyfit (x y 1) find the fitting polynomial of order 1p = 06772 -03914

The output of polyfit is a row vector of the polynomial coefficients the solution of this example is thereforey = 06772x minus 03914Exercise 19Execute the above example Plot the data and the fitted curve in a figure Determine the 2nd and 9th orderpolynomial of these data as well and display the solution in a figureHint x1 = linspace (xmin xmax n) results in a vector with n element evenly distributed from xmintill xmax z = polyval (p x1) calculates the values of the polynomial for every element of x1 _Exercise 20Define x and y as followsgtgt x = -55gtgt y = 02x^3 - x + 2 a 3rd order polynomialgtgt y = y + randn(111) add some noise to yDetermine the 3rd order polynomial fitting y (note that because of added noise the coefficients are differentthat originally chosen) Try some other polynomials as well Plot the results in a figure _42 InterpolationThe simplest way to examine an interpolation is by displaying the function plots with the command plot157-161 The neighboring data points are connected with straight lines This is called a linear interpolation Whenmore data-points are taken into account the effect of interpolation becomes less visible Analyzegtgt x1 = linspace(0 2pi2)gtgt x2 = linspace(0 2pi4)gtgt x3 = linspace(0 2pi16)gtgt x4 = linspace(0 2pi256)gtgt plot(x1sin(x1)x2sin(x2)x3sin(x3)x4sin(x4))gtgt legend(rsquo2 pointsrsquorsquo4 pointsrsquorsquo16 pointsrsquorsquo256 pointsrsquo)

5 Numerical analysisNumerical analysis can be used whenever it is impossible or very difficult to determine the analytical solutionMatlab can be used to find for example the minimum maximum or integral of a certain function51 Evaluation of a functionAs said before the command plot plots a function by connecting defined data points Sometimes however a168-173 function is constant and not very interesting over some range and then acts unexpectedly wildly over anotherWith plot this function might be misinterpreted The command fplot is then useful An examplegtgt x = 0pi82pigtgt y = sin (8x)gtgt plot (x y rsquobrsquo)gtgt hold ongtgt fplot (rsquosin (8z)rsquo [0 2pi] rsquorrsquo)gtgt title (rsquosin (8z)rsquo)gtgt hold off20Command Resultfplot (rsquofunrsquo [min x max x]) plots the function fun for min x till max xfmin (rsquofunrsquo min x max x) gives the x-value of the miminum of thefunction fun between min x and max xfzero (rsquofunrsquo x0) gives the x-value for which the functionfun is zero in the neighborhood of x0Table 6 Evaluation of a functionExecution of these commands results in a figure with an almost straight blue line and a red sine fplot canalso be used to plot a defined functiongtgt f = rsquosin (8z)rsquogtgt fplot (f [0 2pi] rsquorrsquo)gtgt title (f)Other useful commands for a detailed study of a range of a function are listed in Table 6Exercise 21The command fmax does not exist Use one or more of the commands from Table 6 to determine the maximumof the function x cos(x) for 10 lt x lt 15 _52 Integration and differentiationThe integral- or the surface underneath a 2D function- can be determined with the command trapz trapz173-182 does this by measuring the surface between the x-axis and the -by a straight line connected- data points Theaccuracy of this method depends on the distance between the data pointsgtgt x = 00510 y = 05 sqrt (x) + x sin (x) area1 = trapz (x y)

area1 =181655gtgt x = 000510 y = 05 sqrt (x) + x sin (x) area2 = trapz (x y)area2 =183846Differentiation is done by determining the slope in each data point Numerically this is done by first fitting apolynomial followed by differentiating this functiongtgt x = 010gtgt y = [-10 24 102 -158 284 276 775 35 483 522 751]gtgt p = polyfit (x y 5)p = 00026 -00554 03634 -06888 02747 00877gtgt dp = polyder (p)dp = 00132 -02216 10903 -13776 02747gtgt x1 = linspace (0 10 200)gtgt z = polyval (p x1)gtgt dz = polyval (dp x1)gtgt plot (x y rsquog-rsquo x1 z rsquobrsquo x1 dz rsquorrsquo)gtgt legend (rsquodata pointsrsquo rsquocurve fitrsquo rsquoderivativersquo)Exercise 22Determine the integral and derivative of the 4th polynomial fitted through (xy) with x = [4 5 6 7 8 9 1011 12 13] y = [1284 1200 724 -096 -1116 -2096 -2700 -2496 -956 2544] _

6 Control flowAs you know it is possible to execute more than one command at the same time (see section 11) Theseparate commands should then be divided by commarsquos (to display the output) or by semicolons (to suppress21output display) Control flow loops increase the number of possibilities A control flow structure is a block ofcommands that allows conditional code execution and making loops61 Logical and relational operatorsTo use control flow commands it is necessary to perform operations that result in logical values TRUE or88-91 FALSE In Matlab the result of a logical operation is 1 if it is true and 0 if it is false Table 7 shows therelational and logical operations2 Another way to get to know more about them is to type help relop Therelational operators lt lt= gt gt= == and ~= can be used to compare two arrays of the same size or anarray to a scalar The logical operators amp | and ~ allow for the logical combination or negation of relationaloperators In addition three functions are also available xor any and all (use help to find out more)Important The logical amp and | have the equal precedence in Matlab which means that those operatorsassociate from left to right A common situation isgtgt b = 10gtgt 1 | b gt 0 amp 0ans =0gtgt (1 | b gt 0) amp 0 this indicates the same as aboveans =0gtgt 1 | (b gt 0 amp 0)ans =1This shows that you should always use brackets to indicate in which way the operators should be evaluatedCommand Resulta = (b gt c) a is 1 if b is larger than c Similar are lt gt= and lt=a = (b == c) a is 1 if b is equal to ca = (b ~= c) a is 1 if b is not equal ca = ~b logical complement a is 1 if b is 0a = (b amp c) logical AND a is 1 if b = TRUE AND c = TRUEa = (b | c) logical OR a is 1 if b = TRUE OR c = TRUETable 7 Relational and logical operationsExercise 23Predict and check the result of each of the operations of Table 7 for b = 0 and c = -1 _Exercise 24Define two vectors with seven elements (randn(17)) and perform all logical operations including xor anyand all _Exercise 25While doing logical operations between a vector and a scalar each element of the vector is compared to thescalar Predict and check the result of each logical operator for the vector b = [2 31 -40 0] and the scalarc = 0 _Before moving on check whether you now understand the following relations

gtgt a = randperm(10) a random permutation of the numbers from 1 to 10gtgt b = 110gtgt b - (a lt= 7) subtracts from b a 0-1 vector taking 1 for a lt= 7 and 0 otherwisegtgt (a gt= 2) amp (a lt 4) returns ones at positions where 2 lt= a lt 4gtgt ~(b gt 4) returns ones at positions where b lt= 4gtgt (a == b) | b == 3 returns ones at positions where a is equal to b or b is equal to 3gtgt any (a gt 5) returns 1 when ANY of the a elements are larger than 5gtgt any (b lt 5 amp a gt 8) returns 1 when there in the evaluated expressiongtgt (b lt 5 amp a gt 8) appears at least one 1gtgt all (b gt 2) returns 1 when ALL b elements are larger than 22rdquoequal tordquo in the table on page 88 of rdquoThe Student Edition of Matlabrdquo must be rdquo==rdquo instead of rdquo=rdquo2262 Conditional code executionSelection control structures if-blocks are used to decide which instruction to execute next depending whether117-119 expression is TRUE or not The general description is given below In the examples below the command dispis frequently used This command displays on the screen the text between the quotesbull if endSyntaxif logical_expressionstatement1statement2endExampleif (a gt 0)b = adisp (rsquoa is positiversquo)endbull if else endSyntaxif logical_expressionblock of statementsevaluated if TRUEelseblock of statementsevaluated if FALSEendExampleif (temperature gt 100)disp (rsquoAbove boilingrsquo)toohigh = 1elsedisp (rsquoTemperature is OKrsquo)toohigh = 0endbull if elseif else endSyntaxif logical_expression1block of statements evaluatedif logical_expression1 is TRUEelseif logical_expression2block of statements evaluatedif logical_expression2 is TRUEelseblock of statements evaluatedif no other expression is TRUEendExampleif (height gt 190)disp (rsquovery tallrsquo)elseif (height gt 170)disp (rsquotallrsquo)elseif (height lt 150)disp (rsquosmallrsquo)

elsedisp (rsquoaveragersquo)endRemark To do the exercises below a script m-file will be useful It is an external file that contains asequence of Matlab commands What you need to do is to open an editor enter all commands needed forthe solution of a task save it with the extension rsquomrsquo (eg mytaskm) and then run it from the CommandWindow by typing mytask To open the Matlab editor go to the File menu-bar choose the Open optionand then m-file A new window will appear where you can write your scripts and save them on the disk Allcommands in the script will be executed in Matlab You will learn more on script m-files in section 91Important m-script file must be saved in one of the directories in Matlabrsquos pathAn example A script shortm can be created from the two lines given below and run by calling shortx = 0054plot (x sin(x) rsquo-rsquo)Exercise 26Create a script that asks for a number N and computes the drag coefficient C depending on the Reynoldrsquos23number N (make use of the if elseif construction) The command input might be useful here(read pages 32-33 from rdquoThe Student Edition of Matlabrdquoor use help)C =8gtgtgtltgtgtgt0 N _ 024N N 2 (0 01]24N (1 + 014N07) N 2 (01 1e3]043 N 2 (1e3 5e5]019 minus 8e4N N gt 5e5Check whether your script works correctly Compute the drag coefficient for eg N = -3e3 001 56 1e3 3e6(remember that eg 3e3 is a Matlab notation of 3 _ 103) _Exercise 27Write a script that asks for an integer and checks whether it can be divided by 2 or 3 Consider all possibilitiessuch as divisible by both 2 and 3 divisible by 2 and not by 3 etc (use the command rem) _Another selection structure is switch which switches between several cases depending on an expression which119-120 is either a scalar or a stringSyntaxswitch expressioncase choice1block of commands1case choice2a choice2bblock of commands2otherwiseblock of commandsendExamplemethod = 2switch methodcase 12disp(rsquoMethod is linearrsquo)case 3disp(rsquoMethod is cubicrsquo)case 4disp(rsquoMethod is nearestrsquo)otherwisedisp(rsquoUnknown methodrsquo)endThe statements following the first case where the expression matches the choice are executed Thisconstruction can be very handy to avoid long if elseif else end constructions Theexpression can be a scalar or a string A scalar expression matches a choice if expression == choice Astring expression matches a choice if strcmp(expression choice) returns 1 (is true) (strcmp is a commandcomparing two strings)Important Note that the switch-construction only allows the execution of one group of commandsExercise 28Assume that the months are represented by numbers from 1 to 12 Write a script that asks you to provide a

month and returns the number of days in that particular month Alternatively write a script that asks youto provide a month name (eg rsquoJunersquo) instead of a number Use the switch-construction _63 LoopsIteration control structures loops are used to repeat a block of statements until some condition is met Two114-117 types of loops existbull the for loop that repeats a group of statements a fixed number of timesSyntaxfor index = firststeplastblock of statementsendExamplesumx = 0for i=1length(x)sumx = sumx + x(i)end24You can specify any step including a negative value The index of the for-loop can be also a vectorSee some examples of possible variationsExample 1for i=12nendExample 2for i=n-13endExample 3for x=0054disp(x^2)endExample 4for x=[25 9 81]disp(sqrt(x))endbull while loop which evaluates a group of commands as long as expression is TRUESyntaxwhile expressionstatement1statement2statement3endExampleN = 100iter = 1msum = 0while iter lt= Nmsum = msum + iteriter = iter + 1endExercise 29Given the vectors x and y write a script computing the a matrix whose elements should be created accordingto a formula given below (make use of the length command to check the number of elements in both vectors)- aij = yixj (make sure that a division by zero will not occur)- bij = xi _ yj

- cij = 1 max (xi yj)_Exercise 30Determine the sum of the first 50 squared numbers with a control loop _Exercise 31Write a script to find the largest value n such that the sum p13 + p23 + + pn3 is less than 1000 _optionalExercise 32Write a script that transposes a matrix A Check its correctness with the Matlab operation Arsquo _Exercise 33

Write a script that asks for a temperature in degrees Celsius tc and computes the equivalent temperature indegrees Fahrenheit tf (use the formula tf = 95 _ tc + 32) The script should keep running until no numberis provided to convert The functions input and isempty (use help to learn more) should be useful here _end optional

64 Evaluation of logical and relational expressions in the control flow structuresThe relational and logical expressions may become more complicated It is not difficult to operate on them ifyou understand how they are evaluated To explain more details let us consider the following exampleif (~isempty(data)) amp (max(data) lt 5)endThis construction of the if-block is necessary to avoid comparison if data happens to be an empty matrix Insuch a case you cannot evaluate any expression and Matlab gives an error The amp operator returns 1 only ifboth expressions ~isempty (data) and max(data) lt 5 are true and 0 otherwise When data is an emptymatrix the next expression is not evaluated since the whole amp-expression is already known to be false Thesecond expression is checked only if data is a non-empty matrix Remember to put logical expression unitsbetween brackets to avoid wrong evaluations25Important The fact that computers make use of floating-point arithmetic means that often you should becareful when comparing two floating-point numbers just byif (x == y)end(Of course such a construction is allowed eg when you know that x and y represent integers) Instead of theabove construction you may try using thisif (abs (x - y) lt tolerance) eg tolerance = 1e-10endExercise 34Consider the following examplemax_iter = 50tolerance = 1e-4iter = 0xold = 01x = 1while (abs (x - xold) gt tolerance) amp (iter lt max_iter)xold = xx = cos(xold)iter = iter + 1endThis short program tries to solve the equation cos(x) = x (x is the solution found) Make the script solve cosfrom the presented code Note that the while-loop is repeated as long as both conditions are true If eitherthe condition (|x - xold| lt= tolerance) or (iter gt= max iter) is fulfilled then the loop is quitted Runthe script solve cos for different tolerance parameters eg 1e-3 1e-6 1e-8 1e-10 etc Use format long tocheck more precisely how much the found x is really different from cos(x) For each tolerance value checkthe number of performed iterations (iter value) _Exercise 35Create the script solve cos2 which is equal to the one given replacing the while-loop condition bywhile (abs (x - xold) gt tolerance) | (iter lt max_iter)Try to understand the difference and confirm your expectations by running solve cos2 What happens toiter _optional

65 Numerical analysis and the control flow structuresTake a look at the problem of a Taylor expansion The series will be determined numerically until the additionalterms are smaller than a defined precision Look at the Taylor expansion of 11minusx = 1 + x + x2 + withx = 042s = 0 x = 1 s = 0 x = 1x0 = 042 x0 = 042while (x gt 1e-6) or while (x gt (1e-6)s)s = s + x s = s + xx = x x0 x = x x0end endThe approximation of 11minusx is returned in s (first letter of sum) In the first case (on the left) the iteration

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 15: Introduction to Programming Using Matlab

05gtgtgt A(34) extract the rows 3rd and 4th of Aans =7 8 90 0 0gtgt A(2312) extract a part of Aans =4 57 8If needed the other zero elements of the matrix A can be also defined by eggtgt A(4) = [1 2 3] assign vector [1 2 3] to the 4th row of Agtgt A(5[13]) = [4 5] a rsquoshortcutrsquo when assigning A(51) = 4 and A(53) = 5gtgt A how does the matrix A look like nowAs you have seen in the examples above it is possible to manipulate (groups of) matrix-elements Thecommands are shortly explained in Table 2Exercise 9Define the matrix A = [14 58 1 1 1 1] Predict and check the result ofgtgt B = A(3)gtgt C = A(1322)gtgt A(11) = 9gtgt A(2313) = [0 0 0 0 0 0]gtgt A(l212) = [l l 3 3]gtgt A = A(3314)_Exercise 10Define the matrices T=[ 3 4 1 8 -4 3] A = [diag(-123) T -4 4 1 2 1] Perform the followingoperations on the matrix Abull extract a vector consisting of the 2nd and 4th elements of the 3rd rowbull find the minimum of the 3rd columnbull find the maximum of the 2nd rowbull compute the sum of the 2nd columbull compute the mean of the 1st and 4th rowsbull extract the submatrix consisting of the 1st and 3rd rows and all columnsbull extract the submatrix consisting of the 1st and 2nd rows and the 3rd 4th and 5th columnsbull compute the total sum of the 1st and 2nd rowsbull add 3 to all elements of the 2nd and 3rd colums_Table 3 shows some frequently used matrix operations and functions A few examples are provided belowgtgt B = rand(23) a matrix of random numbers you will get a different oneB =09501 06068 0891302311 04860 07621gtgt B2 = [1 2 5 1 5 6]gtgt B + B2rsquo add two matrices why B2rsquo is needed instead of B2ans =19501 56068 5891322311 14860 67621gtgt S = ans4 divide all elements of the matrix ans by 4S =04875 14017 1472805578 03715 1690515gtgt C = [1 -1 4 7 0 -1]gtgt B C matrix multiplication is not defined for B and C Error using ==gt Inner matrix dimensions must agreegtgt B C but you can multiply element-by-elementans =09501 -06068 3565216180 0 -07621gtgt D = B Crsquo or you can make the multiplication legal Crsquo is now 3-by-2D =39085 5759627935 08559

gtgt D^3 this is equivalent to D D Dans =1992503 2041413990133 910548gtgt D^3 - 2 do for all elements raise to the power 3 and subtract 2ans =577069 1890638198005 -13731gtgtgtgt r = [1 3 -2]r B2 this is a legal operation r is a 1-by-3 matrix and B2 isans = 3-by-2 matrix B2 r is an illegal operation6 -7Remind that an n-by-k matrix A (having n rows and k columns) can be multiply by another matrix B onlyif B has k rows ie S is of the k-by-m size (m is arbitrary) As a result you get an n-by-m matrixA ˙B = C A 2 Rntimesk B 2 Rktimesm C 2 Rntimesm

RemarkYou can now compute the inner product between two vectors x and y xT y = Pi xi yi in a simple waygtgt f = [-1 3 5] a column vectorgtgt v = [-1 2 7] a column vectorgtgt frsquo v this is the inner productans =42gtgt f vrsquo be careful now a 3-by-1 matrix is multiplied by a 1-by-3gtgt matrix which results in a 3-by-3 matrix (the outer product)ans =1 -2 -7-3 6 21-5 10 35gtgt f v this is an element-by-element multiplication1635gtgt sum (f v) this is an another way to compute the inner productans =42Exercise 11Perform all operations from Table 3 using chosen matrices A and B vector v and scalars k a b n and m _Exercise 12Let A be a random 3 times 3 matrix and b a random 3 times 1 vector Given that Ax = b then x = Aminus1b Find x(there exist at least two possible commands to do this look at Table 3) _optionalThe concept of an empty matrix [] is also very useful in Matlab For instance a few columns or rows canbe removed from a matrix by assigning an empty matrix to it Try for example16Symbol Color Symbol Styley yellow dotted liner red o circlesg green - solid lineb blue - dashdotted lineTable 4 Plot colors and stylesgtgt C = [1 2 3 4 5 6 7 8 1 1 1 1]gtgt D = C D(2) = [] now a copy of C is in D remove the 2nd column of Dgtgt C ([13]) = [] remove the rows 1 and 3 from Cend optional

3 VisualizationMatlab can be used to visualize the results of an experiment Therefore you should define variables each ofthem containing all values of one parameter to plot31 Simple plotsWith the command plot a graphical display can be made plot(y) draws the points (1 y(1)) (2 y(2)) 184 (n y(n)) and connects the points with a straight line plot(xy) does the same for (x(1) y(1)) (x(2) y(2)) (x(n) y(n)) x and y have to be row- or column vectors of equal lengthThe commands loglog semilogx and semilogy are similar to plot except that they use logarithmic axesExercise 13Type the following commands after predicting the resultgtgt x = 0330

gtgt y = 2^[010] this is the same as y = [1 2 4 8 16 32 64 128 256 512 1024]gtgt plot(xy) to get a graphic representationgtgt semilogy(xy) to get logarithmic axesAs you can see the same figure is used for both plot commands The previous function is removed as soonas the next is displayed The command figure gives you an extra figure Repeat the previous commandsbut generate a new figure before plotting the second function so that you can see both functions in separatewindows You can also switch back to a figure using figure(n) where n is its number _Exercise 14Make a plot such that the coordinates (2 6) (25 18) (5 175) (42 125) and (212) are connected by aline _Exercise 15Plot the function y = sin(x) + x minus x cos(x) in two separate figures for the intervals 0 lt x lt 30 andminus100 lt x lt 100 _32 Several functions in one figureWhen more than one function is plotted in one figure it might be useful to use different markers and colors184-188197-201Table 4 shows a few possibilities help plot shows allThere are different ways to get more than one function into a figure The first one is with the command holdon After this command all functions will be plotted in the same figure until the command hold off is usedAn examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt plot (x1 y1 rsquordrsquo)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)17gtgt hold ongtgt plot (x2 y2 rsquoy-rsquo)gtgt plot (x1y1rsquok-rsquo)gtgt hold offA second method to display more than one function in one figure is to plot several functions at the same timeThe next commands will have the same results as the commands in the previous examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt plot (x1 y1rsquordrsquo x2 y2 rsquoy-rsquo x1 y1 rsquok-rsquo)It is also possible to get more than one figure in one figure window With the command subplot the windowcan be horizontally and vertically divided into any number of subfiguresgtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt subplot(131) plot (x1 y1rsquordrsquo)gtgt subplot(132) plot (x2 y2 rsquoy-rsquo)gtgt subplot(133) plot (x1 y1 rsquok-rsquo)optional

33 Other 2D plotting featuresIn the introduction of this chapter some commands similar to plot loglog semilogx and semilogy were201-211 mentioned There are however more ways to display dataExercise 16To get an impression of other visualizations type the following commands and describe the result (note thatthe command figure creates a new figure window)gtgt figure bar plot of a bell shaped curvegtgt x = -290229gtgt bar (x exp (-xx))gtgt figure stairstep plot of a sine wavegtgt x = 002510gtgt stairs (x sin (x))gtgt figure errorbar plotgtgt x = -2012gtgt y = erf (x) error function check help if you are interestedgtgt e = rand (size (x)) 10gtgt errorbar (x y e)

_end optional

34 PrintingBefore printing a figure you made you might want to add some information such as a title or change the189-196 lay-out a little Table 5 shows some of the commands that can be usedExercise 17Plot the functions y1 = sin(4x) y2 = x cos(x) y3 = (x + 1)minus1px for x = 0 025 10 and a single point(x y) = (4 5) in one figure with different colors and styles Make a legend containing the three functionsMake labels for both axes and a title Add a text to the single point saying single point Change the minimumand maximum values of the axes such that function y3 can be looked at in more detail _When the displayed figure is to your liking you can print it to paper The easiest way to do this is to click onFile in the menu-bar and to choose Print If in the print window you click OK your figure will be printed onthe printer indicated in the print window18Command Resultgrid onoff adds a grid to the plot at the tick marks or removes itaxis([xmin xmax ymin ymax]) sets the minimum and maximum values of the axesbox offon removes the axes box or shows itxlabel(rsquotextrsquo) plots the label text on the x axisylabel(rsquotextrsquo) plots the label text on the y axistitle(rsquotextrsquo) plots a title above the graphtext(xyrsquotextrsquo) adds text at the point (xy)gtext(rsquotextrsquo) adds text at a manually (with a mouse) indicated pointlegend(rsquofun1rsquorsquofun2rsquo) plots a legend box (move it with your mouse) to name your functionslegend off deletes the legend boxTable 5 Plot-manipulationsThere is also a print command which can be used to send a figure to a printer or output it to a file Youcan optionally specify a print device (ie an output format such as tiff or postscript) and options that controlvarious characteristics of the printed file (ie which Figure to print etc) You can also print to a file if youspecify the file name If you do not provide an extension print adds one Since they are many parametersthey will not be explained here (check help print to learn more) Instead try to understand the examplesgtgt print -dwinc print the current Figure to the current printer in colorgtgt print -f1 -deps myfileeps print Figure no1 to the file myfileeps in blackgtgt print -f1 -depsc myfileceps print Figure no1 to the file myfilecoleps in colorgtgt print -dtiff myfile1tiff print the current Figure to the file myfile1tiffgtgt print -dpsc myfile1cps print the current Figure to the file myfile1ps in colorgtgt print -f2 -djpeg myfile2 print Figure no2 to the file myfile2jpgExercise 18Exercise with printing (especially to a file) the figure from Exercise 16 _

4 Curve fitting and interpolationThere are two ways to describe data with an analytical function- curve fitting or regression finding a smooth curve that best fits (approximates) the data accordingto a criterion (eg best least square fit) The curve does not have to go through any of the data points- interpolation the data are assumed to be correct desired in a way to describe what happens betweenthe data points In other words given a finite set of points the goal of interpolation is to find a functionfrom a given class of functions (eg polynomials) which passes through the specified pointsThe figure below illustrates the difference between regression (curve fitting) and interpolationminus5 0 5minus6minus4minus20246810fiting a 3rd order polynomialinterpolation

41 Curve fittingMatlab interprets the best fit of a curve by the lsquoleast squares curve fittingrsquo The curve used is restricted153-15619to polynomials With the command polyfit any polynomial can be fitted to the data polyfit (x y n)finds the coefficients of a polynomial of degree n that fits the data (finds the linear relation between x and y)Letrsquos start with finding a linear regression of some datagtgt x = 010gtgt y = [-10 24 102 158 284 276 299 405 483 522 751]gtgt p = polyfit (x y 1) find the fitting polynomial of order 1p = 06772 -03914

The output of polyfit is a row vector of the polynomial coefficients the solution of this example is thereforey = 06772x minus 03914Exercise 19Execute the above example Plot the data and the fitted curve in a figure Determine the 2nd and 9th orderpolynomial of these data as well and display the solution in a figureHint x1 = linspace (xmin xmax n) results in a vector with n element evenly distributed from xmintill xmax z = polyval (p x1) calculates the values of the polynomial for every element of x1 _Exercise 20Define x and y as followsgtgt x = -55gtgt y = 02x^3 - x + 2 a 3rd order polynomialgtgt y = y + randn(111) add some noise to yDetermine the 3rd order polynomial fitting y (note that because of added noise the coefficients are differentthat originally chosen) Try some other polynomials as well Plot the results in a figure _42 InterpolationThe simplest way to examine an interpolation is by displaying the function plots with the command plot157-161 The neighboring data points are connected with straight lines This is called a linear interpolation Whenmore data-points are taken into account the effect of interpolation becomes less visible Analyzegtgt x1 = linspace(0 2pi2)gtgt x2 = linspace(0 2pi4)gtgt x3 = linspace(0 2pi16)gtgt x4 = linspace(0 2pi256)gtgt plot(x1sin(x1)x2sin(x2)x3sin(x3)x4sin(x4))gtgt legend(rsquo2 pointsrsquorsquo4 pointsrsquorsquo16 pointsrsquorsquo256 pointsrsquo)

5 Numerical analysisNumerical analysis can be used whenever it is impossible or very difficult to determine the analytical solutionMatlab can be used to find for example the minimum maximum or integral of a certain function51 Evaluation of a functionAs said before the command plot plots a function by connecting defined data points Sometimes however a168-173 function is constant and not very interesting over some range and then acts unexpectedly wildly over anotherWith plot this function might be misinterpreted The command fplot is then useful An examplegtgt x = 0pi82pigtgt y = sin (8x)gtgt plot (x y rsquobrsquo)gtgt hold ongtgt fplot (rsquosin (8z)rsquo [0 2pi] rsquorrsquo)gtgt title (rsquosin (8z)rsquo)gtgt hold off20Command Resultfplot (rsquofunrsquo [min x max x]) plots the function fun for min x till max xfmin (rsquofunrsquo min x max x) gives the x-value of the miminum of thefunction fun between min x and max xfzero (rsquofunrsquo x0) gives the x-value for which the functionfun is zero in the neighborhood of x0Table 6 Evaluation of a functionExecution of these commands results in a figure with an almost straight blue line and a red sine fplot canalso be used to plot a defined functiongtgt f = rsquosin (8z)rsquogtgt fplot (f [0 2pi] rsquorrsquo)gtgt title (f)Other useful commands for a detailed study of a range of a function are listed in Table 6Exercise 21The command fmax does not exist Use one or more of the commands from Table 6 to determine the maximumof the function x cos(x) for 10 lt x lt 15 _52 Integration and differentiationThe integral- or the surface underneath a 2D function- can be determined with the command trapz trapz173-182 does this by measuring the surface between the x-axis and the -by a straight line connected- data points Theaccuracy of this method depends on the distance between the data pointsgtgt x = 00510 y = 05 sqrt (x) + x sin (x) area1 = trapz (x y)

area1 =181655gtgt x = 000510 y = 05 sqrt (x) + x sin (x) area2 = trapz (x y)area2 =183846Differentiation is done by determining the slope in each data point Numerically this is done by first fitting apolynomial followed by differentiating this functiongtgt x = 010gtgt y = [-10 24 102 -158 284 276 775 35 483 522 751]gtgt p = polyfit (x y 5)p = 00026 -00554 03634 -06888 02747 00877gtgt dp = polyder (p)dp = 00132 -02216 10903 -13776 02747gtgt x1 = linspace (0 10 200)gtgt z = polyval (p x1)gtgt dz = polyval (dp x1)gtgt plot (x y rsquog-rsquo x1 z rsquobrsquo x1 dz rsquorrsquo)gtgt legend (rsquodata pointsrsquo rsquocurve fitrsquo rsquoderivativersquo)Exercise 22Determine the integral and derivative of the 4th polynomial fitted through (xy) with x = [4 5 6 7 8 9 1011 12 13] y = [1284 1200 724 -096 -1116 -2096 -2700 -2496 -956 2544] _

6 Control flowAs you know it is possible to execute more than one command at the same time (see section 11) Theseparate commands should then be divided by commarsquos (to display the output) or by semicolons (to suppress21output display) Control flow loops increase the number of possibilities A control flow structure is a block ofcommands that allows conditional code execution and making loops61 Logical and relational operatorsTo use control flow commands it is necessary to perform operations that result in logical values TRUE or88-91 FALSE In Matlab the result of a logical operation is 1 if it is true and 0 if it is false Table 7 shows therelational and logical operations2 Another way to get to know more about them is to type help relop Therelational operators lt lt= gt gt= == and ~= can be used to compare two arrays of the same size or anarray to a scalar The logical operators amp | and ~ allow for the logical combination or negation of relationaloperators In addition three functions are also available xor any and all (use help to find out more)Important The logical amp and | have the equal precedence in Matlab which means that those operatorsassociate from left to right A common situation isgtgt b = 10gtgt 1 | b gt 0 amp 0ans =0gtgt (1 | b gt 0) amp 0 this indicates the same as aboveans =0gtgt 1 | (b gt 0 amp 0)ans =1This shows that you should always use brackets to indicate in which way the operators should be evaluatedCommand Resulta = (b gt c) a is 1 if b is larger than c Similar are lt gt= and lt=a = (b == c) a is 1 if b is equal to ca = (b ~= c) a is 1 if b is not equal ca = ~b logical complement a is 1 if b is 0a = (b amp c) logical AND a is 1 if b = TRUE AND c = TRUEa = (b | c) logical OR a is 1 if b = TRUE OR c = TRUETable 7 Relational and logical operationsExercise 23Predict and check the result of each of the operations of Table 7 for b = 0 and c = -1 _Exercise 24Define two vectors with seven elements (randn(17)) and perform all logical operations including xor anyand all _Exercise 25While doing logical operations between a vector and a scalar each element of the vector is compared to thescalar Predict and check the result of each logical operator for the vector b = [2 31 -40 0] and the scalarc = 0 _Before moving on check whether you now understand the following relations

gtgt a = randperm(10) a random permutation of the numbers from 1 to 10gtgt b = 110gtgt b - (a lt= 7) subtracts from b a 0-1 vector taking 1 for a lt= 7 and 0 otherwisegtgt (a gt= 2) amp (a lt 4) returns ones at positions where 2 lt= a lt 4gtgt ~(b gt 4) returns ones at positions where b lt= 4gtgt (a == b) | b == 3 returns ones at positions where a is equal to b or b is equal to 3gtgt any (a gt 5) returns 1 when ANY of the a elements are larger than 5gtgt any (b lt 5 amp a gt 8) returns 1 when there in the evaluated expressiongtgt (b lt 5 amp a gt 8) appears at least one 1gtgt all (b gt 2) returns 1 when ALL b elements are larger than 22rdquoequal tordquo in the table on page 88 of rdquoThe Student Edition of Matlabrdquo must be rdquo==rdquo instead of rdquo=rdquo2262 Conditional code executionSelection control structures if-blocks are used to decide which instruction to execute next depending whether117-119 expression is TRUE or not The general description is given below In the examples below the command dispis frequently used This command displays on the screen the text between the quotesbull if endSyntaxif logical_expressionstatement1statement2endExampleif (a gt 0)b = adisp (rsquoa is positiversquo)endbull if else endSyntaxif logical_expressionblock of statementsevaluated if TRUEelseblock of statementsevaluated if FALSEendExampleif (temperature gt 100)disp (rsquoAbove boilingrsquo)toohigh = 1elsedisp (rsquoTemperature is OKrsquo)toohigh = 0endbull if elseif else endSyntaxif logical_expression1block of statements evaluatedif logical_expression1 is TRUEelseif logical_expression2block of statements evaluatedif logical_expression2 is TRUEelseblock of statements evaluatedif no other expression is TRUEendExampleif (height gt 190)disp (rsquovery tallrsquo)elseif (height gt 170)disp (rsquotallrsquo)elseif (height lt 150)disp (rsquosmallrsquo)

elsedisp (rsquoaveragersquo)endRemark To do the exercises below a script m-file will be useful It is an external file that contains asequence of Matlab commands What you need to do is to open an editor enter all commands needed forthe solution of a task save it with the extension rsquomrsquo (eg mytaskm) and then run it from the CommandWindow by typing mytask To open the Matlab editor go to the File menu-bar choose the Open optionand then m-file A new window will appear where you can write your scripts and save them on the disk Allcommands in the script will be executed in Matlab You will learn more on script m-files in section 91Important m-script file must be saved in one of the directories in Matlabrsquos pathAn example A script shortm can be created from the two lines given below and run by calling shortx = 0054plot (x sin(x) rsquo-rsquo)Exercise 26Create a script that asks for a number N and computes the drag coefficient C depending on the Reynoldrsquos23number N (make use of the if elseif construction) The command input might be useful here(read pages 32-33 from rdquoThe Student Edition of Matlabrdquoor use help)C =8gtgtgtltgtgtgt0 N _ 024N N 2 (0 01]24N (1 + 014N07) N 2 (01 1e3]043 N 2 (1e3 5e5]019 minus 8e4N N gt 5e5Check whether your script works correctly Compute the drag coefficient for eg N = -3e3 001 56 1e3 3e6(remember that eg 3e3 is a Matlab notation of 3 _ 103) _Exercise 27Write a script that asks for an integer and checks whether it can be divided by 2 or 3 Consider all possibilitiessuch as divisible by both 2 and 3 divisible by 2 and not by 3 etc (use the command rem) _Another selection structure is switch which switches between several cases depending on an expression which119-120 is either a scalar or a stringSyntaxswitch expressioncase choice1block of commands1case choice2a choice2bblock of commands2otherwiseblock of commandsendExamplemethod = 2switch methodcase 12disp(rsquoMethod is linearrsquo)case 3disp(rsquoMethod is cubicrsquo)case 4disp(rsquoMethod is nearestrsquo)otherwisedisp(rsquoUnknown methodrsquo)endThe statements following the first case where the expression matches the choice are executed Thisconstruction can be very handy to avoid long if elseif else end constructions Theexpression can be a scalar or a string A scalar expression matches a choice if expression == choice Astring expression matches a choice if strcmp(expression choice) returns 1 (is true) (strcmp is a commandcomparing two strings)Important Note that the switch-construction only allows the execution of one group of commandsExercise 28Assume that the months are represented by numbers from 1 to 12 Write a script that asks you to provide a

month and returns the number of days in that particular month Alternatively write a script that asks youto provide a month name (eg rsquoJunersquo) instead of a number Use the switch-construction _63 LoopsIteration control structures loops are used to repeat a block of statements until some condition is met Two114-117 types of loops existbull the for loop that repeats a group of statements a fixed number of timesSyntaxfor index = firststeplastblock of statementsendExamplesumx = 0for i=1length(x)sumx = sumx + x(i)end24You can specify any step including a negative value The index of the for-loop can be also a vectorSee some examples of possible variationsExample 1for i=12nendExample 2for i=n-13endExample 3for x=0054disp(x^2)endExample 4for x=[25 9 81]disp(sqrt(x))endbull while loop which evaluates a group of commands as long as expression is TRUESyntaxwhile expressionstatement1statement2statement3endExampleN = 100iter = 1msum = 0while iter lt= Nmsum = msum + iteriter = iter + 1endExercise 29Given the vectors x and y write a script computing the a matrix whose elements should be created accordingto a formula given below (make use of the length command to check the number of elements in both vectors)- aij = yixj (make sure that a division by zero will not occur)- bij = xi _ yj

- cij = 1 max (xi yj)_Exercise 30Determine the sum of the first 50 squared numbers with a control loop _Exercise 31Write a script to find the largest value n such that the sum p13 + p23 + + pn3 is less than 1000 _optionalExercise 32Write a script that transposes a matrix A Check its correctness with the Matlab operation Arsquo _Exercise 33

Write a script that asks for a temperature in degrees Celsius tc and computes the equivalent temperature indegrees Fahrenheit tf (use the formula tf = 95 _ tc + 32) The script should keep running until no numberis provided to convert The functions input and isempty (use help to learn more) should be useful here _end optional

64 Evaluation of logical and relational expressions in the control flow structuresThe relational and logical expressions may become more complicated It is not difficult to operate on them ifyou understand how they are evaluated To explain more details let us consider the following exampleif (~isempty(data)) amp (max(data) lt 5)endThis construction of the if-block is necessary to avoid comparison if data happens to be an empty matrix Insuch a case you cannot evaluate any expression and Matlab gives an error The amp operator returns 1 only ifboth expressions ~isempty (data) and max(data) lt 5 are true and 0 otherwise When data is an emptymatrix the next expression is not evaluated since the whole amp-expression is already known to be false Thesecond expression is checked only if data is a non-empty matrix Remember to put logical expression unitsbetween brackets to avoid wrong evaluations25Important The fact that computers make use of floating-point arithmetic means that often you should becareful when comparing two floating-point numbers just byif (x == y)end(Of course such a construction is allowed eg when you know that x and y represent integers) Instead of theabove construction you may try using thisif (abs (x - y) lt tolerance) eg tolerance = 1e-10endExercise 34Consider the following examplemax_iter = 50tolerance = 1e-4iter = 0xold = 01x = 1while (abs (x - xold) gt tolerance) amp (iter lt max_iter)xold = xx = cos(xold)iter = iter + 1endThis short program tries to solve the equation cos(x) = x (x is the solution found) Make the script solve cosfrom the presented code Note that the while-loop is repeated as long as both conditions are true If eitherthe condition (|x - xold| lt= tolerance) or (iter gt= max iter) is fulfilled then the loop is quitted Runthe script solve cos for different tolerance parameters eg 1e-3 1e-6 1e-8 1e-10 etc Use format long tocheck more precisely how much the found x is really different from cos(x) For each tolerance value checkthe number of performed iterations (iter value) _Exercise 35Create the script solve cos2 which is equal to the one given replacing the while-loop condition bywhile (abs (x - xold) gt tolerance) | (iter lt max_iter)Try to understand the difference and confirm your expectations by running solve cos2 What happens toiter _optional

65 Numerical analysis and the control flow structuresTake a look at the problem of a Taylor expansion The series will be determined numerically until the additionalterms are smaller than a defined precision Look at the Taylor expansion of 11minusx = 1 + x + x2 + withx = 042s = 0 x = 1 s = 0 x = 1x0 = 042 x0 = 042while (x gt 1e-6) or while (x gt (1e-6)s)s = s + x s = s + xx = x x0 x = x x0end endThe approximation of 11minusx is returned in s (first letter of sum) In the first case (on the left) the iteration

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 16: Introduction to Programming Using Matlab

gtgt D^3 this is equivalent to D D Dans =1992503 2041413990133 910548gtgt D^3 - 2 do for all elements raise to the power 3 and subtract 2ans =577069 1890638198005 -13731gtgtgtgt r = [1 3 -2]r B2 this is a legal operation r is a 1-by-3 matrix and B2 isans = 3-by-2 matrix B2 r is an illegal operation6 -7Remind that an n-by-k matrix A (having n rows and k columns) can be multiply by another matrix B onlyif B has k rows ie S is of the k-by-m size (m is arbitrary) As a result you get an n-by-m matrixA ˙B = C A 2 Rntimesk B 2 Rktimesm C 2 Rntimesm

RemarkYou can now compute the inner product between two vectors x and y xT y = Pi xi yi in a simple waygtgt f = [-1 3 5] a column vectorgtgt v = [-1 2 7] a column vectorgtgt frsquo v this is the inner productans =42gtgt f vrsquo be careful now a 3-by-1 matrix is multiplied by a 1-by-3gtgt matrix which results in a 3-by-3 matrix (the outer product)ans =1 -2 -7-3 6 21-5 10 35gtgt f v this is an element-by-element multiplication1635gtgt sum (f v) this is an another way to compute the inner productans =42Exercise 11Perform all operations from Table 3 using chosen matrices A and B vector v and scalars k a b n and m _Exercise 12Let A be a random 3 times 3 matrix and b a random 3 times 1 vector Given that Ax = b then x = Aminus1b Find x(there exist at least two possible commands to do this look at Table 3) _optionalThe concept of an empty matrix [] is also very useful in Matlab For instance a few columns or rows canbe removed from a matrix by assigning an empty matrix to it Try for example16Symbol Color Symbol Styley yellow dotted liner red o circlesg green - solid lineb blue - dashdotted lineTable 4 Plot colors and stylesgtgt C = [1 2 3 4 5 6 7 8 1 1 1 1]gtgt D = C D(2) = [] now a copy of C is in D remove the 2nd column of Dgtgt C ([13]) = [] remove the rows 1 and 3 from Cend optional

3 VisualizationMatlab can be used to visualize the results of an experiment Therefore you should define variables each ofthem containing all values of one parameter to plot31 Simple plotsWith the command plot a graphical display can be made plot(y) draws the points (1 y(1)) (2 y(2)) 184 (n y(n)) and connects the points with a straight line plot(xy) does the same for (x(1) y(1)) (x(2) y(2)) (x(n) y(n)) x and y have to be row- or column vectors of equal lengthThe commands loglog semilogx and semilogy are similar to plot except that they use logarithmic axesExercise 13Type the following commands after predicting the resultgtgt x = 0330

gtgt y = 2^[010] this is the same as y = [1 2 4 8 16 32 64 128 256 512 1024]gtgt plot(xy) to get a graphic representationgtgt semilogy(xy) to get logarithmic axesAs you can see the same figure is used for both plot commands The previous function is removed as soonas the next is displayed The command figure gives you an extra figure Repeat the previous commandsbut generate a new figure before plotting the second function so that you can see both functions in separatewindows You can also switch back to a figure using figure(n) where n is its number _Exercise 14Make a plot such that the coordinates (2 6) (25 18) (5 175) (42 125) and (212) are connected by aline _Exercise 15Plot the function y = sin(x) + x minus x cos(x) in two separate figures for the intervals 0 lt x lt 30 andminus100 lt x lt 100 _32 Several functions in one figureWhen more than one function is plotted in one figure it might be useful to use different markers and colors184-188197-201Table 4 shows a few possibilities help plot shows allThere are different ways to get more than one function into a figure The first one is with the command holdon After this command all functions will be plotted in the same figure until the command hold off is usedAn examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt plot (x1 y1 rsquordrsquo)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)17gtgt hold ongtgt plot (x2 y2 rsquoy-rsquo)gtgt plot (x1y1rsquok-rsquo)gtgt hold offA second method to display more than one function in one figure is to plot several functions at the same timeThe next commands will have the same results as the commands in the previous examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt plot (x1 y1rsquordrsquo x2 y2 rsquoy-rsquo x1 y1 rsquok-rsquo)It is also possible to get more than one figure in one figure window With the command subplot the windowcan be horizontally and vertically divided into any number of subfiguresgtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt subplot(131) plot (x1 y1rsquordrsquo)gtgt subplot(132) plot (x2 y2 rsquoy-rsquo)gtgt subplot(133) plot (x1 y1 rsquok-rsquo)optional

33 Other 2D plotting featuresIn the introduction of this chapter some commands similar to plot loglog semilogx and semilogy were201-211 mentioned There are however more ways to display dataExercise 16To get an impression of other visualizations type the following commands and describe the result (note thatthe command figure creates a new figure window)gtgt figure bar plot of a bell shaped curvegtgt x = -290229gtgt bar (x exp (-xx))gtgt figure stairstep plot of a sine wavegtgt x = 002510gtgt stairs (x sin (x))gtgt figure errorbar plotgtgt x = -2012gtgt y = erf (x) error function check help if you are interestedgtgt e = rand (size (x)) 10gtgt errorbar (x y e)

_end optional

34 PrintingBefore printing a figure you made you might want to add some information such as a title or change the189-196 lay-out a little Table 5 shows some of the commands that can be usedExercise 17Plot the functions y1 = sin(4x) y2 = x cos(x) y3 = (x + 1)minus1px for x = 0 025 10 and a single point(x y) = (4 5) in one figure with different colors and styles Make a legend containing the three functionsMake labels for both axes and a title Add a text to the single point saying single point Change the minimumand maximum values of the axes such that function y3 can be looked at in more detail _When the displayed figure is to your liking you can print it to paper The easiest way to do this is to click onFile in the menu-bar and to choose Print If in the print window you click OK your figure will be printed onthe printer indicated in the print window18Command Resultgrid onoff adds a grid to the plot at the tick marks or removes itaxis([xmin xmax ymin ymax]) sets the minimum and maximum values of the axesbox offon removes the axes box or shows itxlabel(rsquotextrsquo) plots the label text on the x axisylabel(rsquotextrsquo) plots the label text on the y axistitle(rsquotextrsquo) plots a title above the graphtext(xyrsquotextrsquo) adds text at the point (xy)gtext(rsquotextrsquo) adds text at a manually (with a mouse) indicated pointlegend(rsquofun1rsquorsquofun2rsquo) plots a legend box (move it with your mouse) to name your functionslegend off deletes the legend boxTable 5 Plot-manipulationsThere is also a print command which can be used to send a figure to a printer or output it to a file Youcan optionally specify a print device (ie an output format such as tiff or postscript) and options that controlvarious characteristics of the printed file (ie which Figure to print etc) You can also print to a file if youspecify the file name If you do not provide an extension print adds one Since they are many parametersthey will not be explained here (check help print to learn more) Instead try to understand the examplesgtgt print -dwinc print the current Figure to the current printer in colorgtgt print -f1 -deps myfileeps print Figure no1 to the file myfileeps in blackgtgt print -f1 -depsc myfileceps print Figure no1 to the file myfilecoleps in colorgtgt print -dtiff myfile1tiff print the current Figure to the file myfile1tiffgtgt print -dpsc myfile1cps print the current Figure to the file myfile1ps in colorgtgt print -f2 -djpeg myfile2 print Figure no2 to the file myfile2jpgExercise 18Exercise with printing (especially to a file) the figure from Exercise 16 _

4 Curve fitting and interpolationThere are two ways to describe data with an analytical function- curve fitting or regression finding a smooth curve that best fits (approximates) the data accordingto a criterion (eg best least square fit) The curve does not have to go through any of the data points- interpolation the data are assumed to be correct desired in a way to describe what happens betweenthe data points In other words given a finite set of points the goal of interpolation is to find a functionfrom a given class of functions (eg polynomials) which passes through the specified pointsThe figure below illustrates the difference between regression (curve fitting) and interpolationminus5 0 5minus6minus4minus20246810fiting a 3rd order polynomialinterpolation

41 Curve fittingMatlab interprets the best fit of a curve by the lsquoleast squares curve fittingrsquo The curve used is restricted153-15619to polynomials With the command polyfit any polynomial can be fitted to the data polyfit (x y n)finds the coefficients of a polynomial of degree n that fits the data (finds the linear relation between x and y)Letrsquos start with finding a linear regression of some datagtgt x = 010gtgt y = [-10 24 102 158 284 276 299 405 483 522 751]gtgt p = polyfit (x y 1) find the fitting polynomial of order 1p = 06772 -03914

The output of polyfit is a row vector of the polynomial coefficients the solution of this example is thereforey = 06772x minus 03914Exercise 19Execute the above example Plot the data and the fitted curve in a figure Determine the 2nd and 9th orderpolynomial of these data as well and display the solution in a figureHint x1 = linspace (xmin xmax n) results in a vector with n element evenly distributed from xmintill xmax z = polyval (p x1) calculates the values of the polynomial for every element of x1 _Exercise 20Define x and y as followsgtgt x = -55gtgt y = 02x^3 - x + 2 a 3rd order polynomialgtgt y = y + randn(111) add some noise to yDetermine the 3rd order polynomial fitting y (note that because of added noise the coefficients are differentthat originally chosen) Try some other polynomials as well Plot the results in a figure _42 InterpolationThe simplest way to examine an interpolation is by displaying the function plots with the command plot157-161 The neighboring data points are connected with straight lines This is called a linear interpolation Whenmore data-points are taken into account the effect of interpolation becomes less visible Analyzegtgt x1 = linspace(0 2pi2)gtgt x2 = linspace(0 2pi4)gtgt x3 = linspace(0 2pi16)gtgt x4 = linspace(0 2pi256)gtgt plot(x1sin(x1)x2sin(x2)x3sin(x3)x4sin(x4))gtgt legend(rsquo2 pointsrsquorsquo4 pointsrsquorsquo16 pointsrsquorsquo256 pointsrsquo)

5 Numerical analysisNumerical analysis can be used whenever it is impossible or very difficult to determine the analytical solutionMatlab can be used to find for example the minimum maximum or integral of a certain function51 Evaluation of a functionAs said before the command plot plots a function by connecting defined data points Sometimes however a168-173 function is constant and not very interesting over some range and then acts unexpectedly wildly over anotherWith plot this function might be misinterpreted The command fplot is then useful An examplegtgt x = 0pi82pigtgt y = sin (8x)gtgt plot (x y rsquobrsquo)gtgt hold ongtgt fplot (rsquosin (8z)rsquo [0 2pi] rsquorrsquo)gtgt title (rsquosin (8z)rsquo)gtgt hold off20Command Resultfplot (rsquofunrsquo [min x max x]) plots the function fun for min x till max xfmin (rsquofunrsquo min x max x) gives the x-value of the miminum of thefunction fun between min x and max xfzero (rsquofunrsquo x0) gives the x-value for which the functionfun is zero in the neighborhood of x0Table 6 Evaluation of a functionExecution of these commands results in a figure with an almost straight blue line and a red sine fplot canalso be used to plot a defined functiongtgt f = rsquosin (8z)rsquogtgt fplot (f [0 2pi] rsquorrsquo)gtgt title (f)Other useful commands for a detailed study of a range of a function are listed in Table 6Exercise 21The command fmax does not exist Use one or more of the commands from Table 6 to determine the maximumof the function x cos(x) for 10 lt x lt 15 _52 Integration and differentiationThe integral- or the surface underneath a 2D function- can be determined with the command trapz trapz173-182 does this by measuring the surface between the x-axis and the -by a straight line connected- data points Theaccuracy of this method depends on the distance between the data pointsgtgt x = 00510 y = 05 sqrt (x) + x sin (x) area1 = trapz (x y)

area1 =181655gtgt x = 000510 y = 05 sqrt (x) + x sin (x) area2 = trapz (x y)area2 =183846Differentiation is done by determining the slope in each data point Numerically this is done by first fitting apolynomial followed by differentiating this functiongtgt x = 010gtgt y = [-10 24 102 -158 284 276 775 35 483 522 751]gtgt p = polyfit (x y 5)p = 00026 -00554 03634 -06888 02747 00877gtgt dp = polyder (p)dp = 00132 -02216 10903 -13776 02747gtgt x1 = linspace (0 10 200)gtgt z = polyval (p x1)gtgt dz = polyval (dp x1)gtgt plot (x y rsquog-rsquo x1 z rsquobrsquo x1 dz rsquorrsquo)gtgt legend (rsquodata pointsrsquo rsquocurve fitrsquo rsquoderivativersquo)Exercise 22Determine the integral and derivative of the 4th polynomial fitted through (xy) with x = [4 5 6 7 8 9 1011 12 13] y = [1284 1200 724 -096 -1116 -2096 -2700 -2496 -956 2544] _

6 Control flowAs you know it is possible to execute more than one command at the same time (see section 11) Theseparate commands should then be divided by commarsquos (to display the output) or by semicolons (to suppress21output display) Control flow loops increase the number of possibilities A control flow structure is a block ofcommands that allows conditional code execution and making loops61 Logical and relational operatorsTo use control flow commands it is necessary to perform operations that result in logical values TRUE or88-91 FALSE In Matlab the result of a logical operation is 1 if it is true and 0 if it is false Table 7 shows therelational and logical operations2 Another way to get to know more about them is to type help relop Therelational operators lt lt= gt gt= == and ~= can be used to compare two arrays of the same size or anarray to a scalar The logical operators amp | and ~ allow for the logical combination or negation of relationaloperators In addition three functions are also available xor any and all (use help to find out more)Important The logical amp and | have the equal precedence in Matlab which means that those operatorsassociate from left to right A common situation isgtgt b = 10gtgt 1 | b gt 0 amp 0ans =0gtgt (1 | b gt 0) amp 0 this indicates the same as aboveans =0gtgt 1 | (b gt 0 amp 0)ans =1This shows that you should always use brackets to indicate in which way the operators should be evaluatedCommand Resulta = (b gt c) a is 1 if b is larger than c Similar are lt gt= and lt=a = (b == c) a is 1 if b is equal to ca = (b ~= c) a is 1 if b is not equal ca = ~b logical complement a is 1 if b is 0a = (b amp c) logical AND a is 1 if b = TRUE AND c = TRUEa = (b | c) logical OR a is 1 if b = TRUE OR c = TRUETable 7 Relational and logical operationsExercise 23Predict and check the result of each of the operations of Table 7 for b = 0 and c = -1 _Exercise 24Define two vectors with seven elements (randn(17)) and perform all logical operations including xor anyand all _Exercise 25While doing logical operations between a vector and a scalar each element of the vector is compared to thescalar Predict and check the result of each logical operator for the vector b = [2 31 -40 0] and the scalarc = 0 _Before moving on check whether you now understand the following relations

gtgt a = randperm(10) a random permutation of the numbers from 1 to 10gtgt b = 110gtgt b - (a lt= 7) subtracts from b a 0-1 vector taking 1 for a lt= 7 and 0 otherwisegtgt (a gt= 2) amp (a lt 4) returns ones at positions where 2 lt= a lt 4gtgt ~(b gt 4) returns ones at positions where b lt= 4gtgt (a == b) | b == 3 returns ones at positions where a is equal to b or b is equal to 3gtgt any (a gt 5) returns 1 when ANY of the a elements are larger than 5gtgt any (b lt 5 amp a gt 8) returns 1 when there in the evaluated expressiongtgt (b lt 5 amp a gt 8) appears at least one 1gtgt all (b gt 2) returns 1 when ALL b elements are larger than 22rdquoequal tordquo in the table on page 88 of rdquoThe Student Edition of Matlabrdquo must be rdquo==rdquo instead of rdquo=rdquo2262 Conditional code executionSelection control structures if-blocks are used to decide which instruction to execute next depending whether117-119 expression is TRUE or not The general description is given below In the examples below the command dispis frequently used This command displays on the screen the text between the quotesbull if endSyntaxif logical_expressionstatement1statement2endExampleif (a gt 0)b = adisp (rsquoa is positiversquo)endbull if else endSyntaxif logical_expressionblock of statementsevaluated if TRUEelseblock of statementsevaluated if FALSEendExampleif (temperature gt 100)disp (rsquoAbove boilingrsquo)toohigh = 1elsedisp (rsquoTemperature is OKrsquo)toohigh = 0endbull if elseif else endSyntaxif logical_expression1block of statements evaluatedif logical_expression1 is TRUEelseif logical_expression2block of statements evaluatedif logical_expression2 is TRUEelseblock of statements evaluatedif no other expression is TRUEendExampleif (height gt 190)disp (rsquovery tallrsquo)elseif (height gt 170)disp (rsquotallrsquo)elseif (height lt 150)disp (rsquosmallrsquo)

elsedisp (rsquoaveragersquo)endRemark To do the exercises below a script m-file will be useful It is an external file that contains asequence of Matlab commands What you need to do is to open an editor enter all commands needed forthe solution of a task save it with the extension rsquomrsquo (eg mytaskm) and then run it from the CommandWindow by typing mytask To open the Matlab editor go to the File menu-bar choose the Open optionand then m-file A new window will appear where you can write your scripts and save them on the disk Allcommands in the script will be executed in Matlab You will learn more on script m-files in section 91Important m-script file must be saved in one of the directories in Matlabrsquos pathAn example A script shortm can be created from the two lines given below and run by calling shortx = 0054plot (x sin(x) rsquo-rsquo)Exercise 26Create a script that asks for a number N and computes the drag coefficient C depending on the Reynoldrsquos23number N (make use of the if elseif construction) The command input might be useful here(read pages 32-33 from rdquoThe Student Edition of Matlabrdquoor use help)C =8gtgtgtltgtgtgt0 N _ 024N N 2 (0 01]24N (1 + 014N07) N 2 (01 1e3]043 N 2 (1e3 5e5]019 minus 8e4N N gt 5e5Check whether your script works correctly Compute the drag coefficient for eg N = -3e3 001 56 1e3 3e6(remember that eg 3e3 is a Matlab notation of 3 _ 103) _Exercise 27Write a script that asks for an integer and checks whether it can be divided by 2 or 3 Consider all possibilitiessuch as divisible by both 2 and 3 divisible by 2 and not by 3 etc (use the command rem) _Another selection structure is switch which switches between several cases depending on an expression which119-120 is either a scalar or a stringSyntaxswitch expressioncase choice1block of commands1case choice2a choice2bblock of commands2otherwiseblock of commandsendExamplemethod = 2switch methodcase 12disp(rsquoMethod is linearrsquo)case 3disp(rsquoMethod is cubicrsquo)case 4disp(rsquoMethod is nearestrsquo)otherwisedisp(rsquoUnknown methodrsquo)endThe statements following the first case where the expression matches the choice are executed Thisconstruction can be very handy to avoid long if elseif else end constructions Theexpression can be a scalar or a string A scalar expression matches a choice if expression == choice Astring expression matches a choice if strcmp(expression choice) returns 1 (is true) (strcmp is a commandcomparing two strings)Important Note that the switch-construction only allows the execution of one group of commandsExercise 28Assume that the months are represented by numbers from 1 to 12 Write a script that asks you to provide a

month and returns the number of days in that particular month Alternatively write a script that asks youto provide a month name (eg rsquoJunersquo) instead of a number Use the switch-construction _63 LoopsIteration control structures loops are used to repeat a block of statements until some condition is met Two114-117 types of loops existbull the for loop that repeats a group of statements a fixed number of timesSyntaxfor index = firststeplastblock of statementsendExamplesumx = 0for i=1length(x)sumx = sumx + x(i)end24You can specify any step including a negative value The index of the for-loop can be also a vectorSee some examples of possible variationsExample 1for i=12nendExample 2for i=n-13endExample 3for x=0054disp(x^2)endExample 4for x=[25 9 81]disp(sqrt(x))endbull while loop which evaluates a group of commands as long as expression is TRUESyntaxwhile expressionstatement1statement2statement3endExampleN = 100iter = 1msum = 0while iter lt= Nmsum = msum + iteriter = iter + 1endExercise 29Given the vectors x and y write a script computing the a matrix whose elements should be created accordingto a formula given below (make use of the length command to check the number of elements in both vectors)- aij = yixj (make sure that a division by zero will not occur)- bij = xi _ yj

- cij = 1 max (xi yj)_Exercise 30Determine the sum of the first 50 squared numbers with a control loop _Exercise 31Write a script to find the largest value n such that the sum p13 + p23 + + pn3 is less than 1000 _optionalExercise 32Write a script that transposes a matrix A Check its correctness with the Matlab operation Arsquo _Exercise 33

Write a script that asks for a temperature in degrees Celsius tc and computes the equivalent temperature indegrees Fahrenheit tf (use the formula tf = 95 _ tc + 32) The script should keep running until no numberis provided to convert The functions input and isempty (use help to learn more) should be useful here _end optional

64 Evaluation of logical and relational expressions in the control flow structuresThe relational and logical expressions may become more complicated It is not difficult to operate on them ifyou understand how they are evaluated To explain more details let us consider the following exampleif (~isempty(data)) amp (max(data) lt 5)endThis construction of the if-block is necessary to avoid comparison if data happens to be an empty matrix Insuch a case you cannot evaluate any expression and Matlab gives an error The amp operator returns 1 only ifboth expressions ~isempty (data) and max(data) lt 5 are true and 0 otherwise When data is an emptymatrix the next expression is not evaluated since the whole amp-expression is already known to be false Thesecond expression is checked only if data is a non-empty matrix Remember to put logical expression unitsbetween brackets to avoid wrong evaluations25Important The fact that computers make use of floating-point arithmetic means that often you should becareful when comparing two floating-point numbers just byif (x == y)end(Of course such a construction is allowed eg when you know that x and y represent integers) Instead of theabove construction you may try using thisif (abs (x - y) lt tolerance) eg tolerance = 1e-10endExercise 34Consider the following examplemax_iter = 50tolerance = 1e-4iter = 0xold = 01x = 1while (abs (x - xold) gt tolerance) amp (iter lt max_iter)xold = xx = cos(xold)iter = iter + 1endThis short program tries to solve the equation cos(x) = x (x is the solution found) Make the script solve cosfrom the presented code Note that the while-loop is repeated as long as both conditions are true If eitherthe condition (|x - xold| lt= tolerance) or (iter gt= max iter) is fulfilled then the loop is quitted Runthe script solve cos for different tolerance parameters eg 1e-3 1e-6 1e-8 1e-10 etc Use format long tocheck more precisely how much the found x is really different from cos(x) For each tolerance value checkthe number of performed iterations (iter value) _Exercise 35Create the script solve cos2 which is equal to the one given replacing the while-loop condition bywhile (abs (x - xold) gt tolerance) | (iter lt max_iter)Try to understand the difference and confirm your expectations by running solve cos2 What happens toiter _optional

65 Numerical analysis and the control flow structuresTake a look at the problem of a Taylor expansion The series will be determined numerically until the additionalterms are smaller than a defined precision Look at the Taylor expansion of 11minusx = 1 + x + x2 + withx = 042s = 0 x = 1 s = 0 x = 1x0 = 042 x0 = 042while (x gt 1e-6) or while (x gt (1e-6)s)s = s + x s = s + xx = x x0 x = x x0end endThe approximation of 11minusx is returned in s (first letter of sum) In the first case (on the left) the iteration

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 17: Introduction to Programming Using Matlab

gtgt y = 2^[010] this is the same as y = [1 2 4 8 16 32 64 128 256 512 1024]gtgt plot(xy) to get a graphic representationgtgt semilogy(xy) to get logarithmic axesAs you can see the same figure is used for both plot commands The previous function is removed as soonas the next is displayed The command figure gives you an extra figure Repeat the previous commandsbut generate a new figure before plotting the second function so that you can see both functions in separatewindows You can also switch back to a figure using figure(n) where n is its number _Exercise 14Make a plot such that the coordinates (2 6) (25 18) (5 175) (42 125) and (212) are connected by aline _Exercise 15Plot the function y = sin(x) + x minus x cos(x) in two separate figures for the intervals 0 lt x lt 30 andminus100 lt x lt 100 _32 Several functions in one figureWhen more than one function is plotted in one figure it might be useful to use different markers and colors184-188197-201Table 4 shows a few possibilities help plot shows allThere are different ways to get more than one function into a figure The first one is with the command holdon After this command all functions will be plotted in the same figure until the command hold off is usedAn examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt plot (x1 y1 rsquordrsquo)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)17gtgt hold ongtgt plot (x2 y2 rsquoy-rsquo)gtgt plot (x1y1rsquok-rsquo)gtgt hold offA second method to display more than one function in one figure is to plot several functions at the same timeThe next commands will have the same results as the commands in the previous examplegtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt plot (x1 y1rsquordrsquo x2 y2 rsquoy-rsquo x1 y1 rsquok-rsquo)It is also possible to get more than one figure in one figure window With the command subplot the windowcan be horizontally and vertically divided into any number of subfiguresgtgt x1 = 1131gtgt y1 = sin (x1)gtgt x2 = 1033gtgt y2 = sin (-x2+pi3)gtgt subplot(131) plot (x1 y1rsquordrsquo)gtgt subplot(132) plot (x2 y2 rsquoy-rsquo)gtgt subplot(133) plot (x1 y1 rsquok-rsquo)optional

33 Other 2D plotting featuresIn the introduction of this chapter some commands similar to plot loglog semilogx and semilogy were201-211 mentioned There are however more ways to display dataExercise 16To get an impression of other visualizations type the following commands and describe the result (note thatthe command figure creates a new figure window)gtgt figure bar plot of a bell shaped curvegtgt x = -290229gtgt bar (x exp (-xx))gtgt figure stairstep plot of a sine wavegtgt x = 002510gtgt stairs (x sin (x))gtgt figure errorbar plotgtgt x = -2012gtgt y = erf (x) error function check help if you are interestedgtgt e = rand (size (x)) 10gtgt errorbar (x y e)

_end optional

34 PrintingBefore printing a figure you made you might want to add some information such as a title or change the189-196 lay-out a little Table 5 shows some of the commands that can be usedExercise 17Plot the functions y1 = sin(4x) y2 = x cos(x) y3 = (x + 1)minus1px for x = 0 025 10 and a single point(x y) = (4 5) in one figure with different colors and styles Make a legend containing the three functionsMake labels for both axes and a title Add a text to the single point saying single point Change the minimumand maximum values of the axes such that function y3 can be looked at in more detail _When the displayed figure is to your liking you can print it to paper The easiest way to do this is to click onFile in the menu-bar and to choose Print If in the print window you click OK your figure will be printed onthe printer indicated in the print window18Command Resultgrid onoff adds a grid to the plot at the tick marks or removes itaxis([xmin xmax ymin ymax]) sets the minimum and maximum values of the axesbox offon removes the axes box or shows itxlabel(rsquotextrsquo) plots the label text on the x axisylabel(rsquotextrsquo) plots the label text on the y axistitle(rsquotextrsquo) plots a title above the graphtext(xyrsquotextrsquo) adds text at the point (xy)gtext(rsquotextrsquo) adds text at a manually (with a mouse) indicated pointlegend(rsquofun1rsquorsquofun2rsquo) plots a legend box (move it with your mouse) to name your functionslegend off deletes the legend boxTable 5 Plot-manipulationsThere is also a print command which can be used to send a figure to a printer or output it to a file Youcan optionally specify a print device (ie an output format such as tiff or postscript) and options that controlvarious characteristics of the printed file (ie which Figure to print etc) You can also print to a file if youspecify the file name If you do not provide an extension print adds one Since they are many parametersthey will not be explained here (check help print to learn more) Instead try to understand the examplesgtgt print -dwinc print the current Figure to the current printer in colorgtgt print -f1 -deps myfileeps print Figure no1 to the file myfileeps in blackgtgt print -f1 -depsc myfileceps print Figure no1 to the file myfilecoleps in colorgtgt print -dtiff myfile1tiff print the current Figure to the file myfile1tiffgtgt print -dpsc myfile1cps print the current Figure to the file myfile1ps in colorgtgt print -f2 -djpeg myfile2 print Figure no2 to the file myfile2jpgExercise 18Exercise with printing (especially to a file) the figure from Exercise 16 _

4 Curve fitting and interpolationThere are two ways to describe data with an analytical function- curve fitting or regression finding a smooth curve that best fits (approximates) the data accordingto a criterion (eg best least square fit) The curve does not have to go through any of the data points- interpolation the data are assumed to be correct desired in a way to describe what happens betweenthe data points In other words given a finite set of points the goal of interpolation is to find a functionfrom a given class of functions (eg polynomials) which passes through the specified pointsThe figure below illustrates the difference between regression (curve fitting) and interpolationminus5 0 5minus6minus4minus20246810fiting a 3rd order polynomialinterpolation

41 Curve fittingMatlab interprets the best fit of a curve by the lsquoleast squares curve fittingrsquo The curve used is restricted153-15619to polynomials With the command polyfit any polynomial can be fitted to the data polyfit (x y n)finds the coefficients of a polynomial of degree n that fits the data (finds the linear relation between x and y)Letrsquos start with finding a linear regression of some datagtgt x = 010gtgt y = [-10 24 102 158 284 276 299 405 483 522 751]gtgt p = polyfit (x y 1) find the fitting polynomial of order 1p = 06772 -03914

The output of polyfit is a row vector of the polynomial coefficients the solution of this example is thereforey = 06772x minus 03914Exercise 19Execute the above example Plot the data and the fitted curve in a figure Determine the 2nd and 9th orderpolynomial of these data as well and display the solution in a figureHint x1 = linspace (xmin xmax n) results in a vector with n element evenly distributed from xmintill xmax z = polyval (p x1) calculates the values of the polynomial for every element of x1 _Exercise 20Define x and y as followsgtgt x = -55gtgt y = 02x^3 - x + 2 a 3rd order polynomialgtgt y = y + randn(111) add some noise to yDetermine the 3rd order polynomial fitting y (note that because of added noise the coefficients are differentthat originally chosen) Try some other polynomials as well Plot the results in a figure _42 InterpolationThe simplest way to examine an interpolation is by displaying the function plots with the command plot157-161 The neighboring data points are connected with straight lines This is called a linear interpolation Whenmore data-points are taken into account the effect of interpolation becomes less visible Analyzegtgt x1 = linspace(0 2pi2)gtgt x2 = linspace(0 2pi4)gtgt x3 = linspace(0 2pi16)gtgt x4 = linspace(0 2pi256)gtgt plot(x1sin(x1)x2sin(x2)x3sin(x3)x4sin(x4))gtgt legend(rsquo2 pointsrsquorsquo4 pointsrsquorsquo16 pointsrsquorsquo256 pointsrsquo)

5 Numerical analysisNumerical analysis can be used whenever it is impossible or very difficult to determine the analytical solutionMatlab can be used to find for example the minimum maximum or integral of a certain function51 Evaluation of a functionAs said before the command plot plots a function by connecting defined data points Sometimes however a168-173 function is constant and not very interesting over some range and then acts unexpectedly wildly over anotherWith plot this function might be misinterpreted The command fplot is then useful An examplegtgt x = 0pi82pigtgt y = sin (8x)gtgt plot (x y rsquobrsquo)gtgt hold ongtgt fplot (rsquosin (8z)rsquo [0 2pi] rsquorrsquo)gtgt title (rsquosin (8z)rsquo)gtgt hold off20Command Resultfplot (rsquofunrsquo [min x max x]) plots the function fun for min x till max xfmin (rsquofunrsquo min x max x) gives the x-value of the miminum of thefunction fun between min x and max xfzero (rsquofunrsquo x0) gives the x-value for which the functionfun is zero in the neighborhood of x0Table 6 Evaluation of a functionExecution of these commands results in a figure with an almost straight blue line and a red sine fplot canalso be used to plot a defined functiongtgt f = rsquosin (8z)rsquogtgt fplot (f [0 2pi] rsquorrsquo)gtgt title (f)Other useful commands for a detailed study of a range of a function are listed in Table 6Exercise 21The command fmax does not exist Use one or more of the commands from Table 6 to determine the maximumof the function x cos(x) for 10 lt x lt 15 _52 Integration and differentiationThe integral- or the surface underneath a 2D function- can be determined with the command trapz trapz173-182 does this by measuring the surface between the x-axis and the -by a straight line connected- data points Theaccuracy of this method depends on the distance between the data pointsgtgt x = 00510 y = 05 sqrt (x) + x sin (x) area1 = trapz (x y)

area1 =181655gtgt x = 000510 y = 05 sqrt (x) + x sin (x) area2 = trapz (x y)area2 =183846Differentiation is done by determining the slope in each data point Numerically this is done by first fitting apolynomial followed by differentiating this functiongtgt x = 010gtgt y = [-10 24 102 -158 284 276 775 35 483 522 751]gtgt p = polyfit (x y 5)p = 00026 -00554 03634 -06888 02747 00877gtgt dp = polyder (p)dp = 00132 -02216 10903 -13776 02747gtgt x1 = linspace (0 10 200)gtgt z = polyval (p x1)gtgt dz = polyval (dp x1)gtgt plot (x y rsquog-rsquo x1 z rsquobrsquo x1 dz rsquorrsquo)gtgt legend (rsquodata pointsrsquo rsquocurve fitrsquo rsquoderivativersquo)Exercise 22Determine the integral and derivative of the 4th polynomial fitted through (xy) with x = [4 5 6 7 8 9 1011 12 13] y = [1284 1200 724 -096 -1116 -2096 -2700 -2496 -956 2544] _

6 Control flowAs you know it is possible to execute more than one command at the same time (see section 11) Theseparate commands should then be divided by commarsquos (to display the output) or by semicolons (to suppress21output display) Control flow loops increase the number of possibilities A control flow structure is a block ofcommands that allows conditional code execution and making loops61 Logical and relational operatorsTo use control flow commands it is necessary to perform operations that result in logical values TRUE or88-91 FALSE In Matlab the result of a logical operation is 1 if it is true and 0 if it is false Table 7 shows therelational and logical operations2 Another way to get to know more about them is to type help relop Therelational operators lt lt= gt gt= == and ~= can be used to compare two arrays of the same size or anarray to a scalar The logical operators amp | and ~ allow for the logical combination or negation of relationaloperators In addition three functions are also available xor any and all (use help to find out more)Important The logical amp and | have the equal precedence in Matlab which means that those operatorsassociate from left to right A common situation isgtgt b = 10gtgt 1 | b gt 0 amp 0ans =0gtgt (1 | b gt 0) amp 0 this indicates the same as aboveans =0gtgt 1 | (b gt 0 amp 0)ans =1This shows that you should always use brackets to indicate in which way the operators should be evaluatedCommand Resulta = (b gt c) a is 1 if b is larger than c Similar are lt gt= and lt=a = (b == c) a is 1 if b is equal to ca = (b ~= c) a is 1 if b is not equal ca = ~b logical complement a is 1 if b is 0a = (b amp c) logical AND a is 1 if b = TRUE AND c = TRUEa = (b | c) logical OR a is 1 if b = TRUE OR c = TRUETable 7 Relational and logical operationsExercise 23Predict and check the result of each of the operations of Table 7 for b = 0 and c = -1 _Exercise 24Define two vectors with seven elements (randn(17)) and perform all logical operations including xor anyand all _Exercise 25While doing logical operations between a vector and a scalar each element of the vector is compared to thescalar Predict and check the result of each logical operator for the vector b = [2 31 -40 0] and the scalarc = 0 _Before moving on check whether you now understand the following relations

gtgt a = randperm(10) a random permutation of the numbers from 1 to 10gtgt b = 110gtgt b - (a lt= 7) subtracts from b a 0-1 vector taking 1 for a lt= 7 and 0 otherwisegtgt (a gt= 2) amp (a lt 4) returns ones at positions where 2 lt= a lt 4gtgt ~(b gt 4) returns ones at positions where b lt= 4gtgt (a == b) | b == 3 returns ones at positions where a is equal to b or b is equal to 3gtgt any (a gt 5) returns 1 when ANY of the a elements are larger than 5gtgt any (b lt 5 amp a gt 8) returns 1 when there in the evaluated expressiongtgt (b lt 5 amp a gt 8) appears at least one 1gtgt all (b gt 2) returns 1 when ALL b elements are larger than 22rdquoequal tordquo in the table on page 88 of rdquoThe Student Edition of Matlabrdquo must be rdquo==rdquo instead of rdquo=rdquo2262 Conditional code executionSelection control structures if-blocks are used to decide which instruction to execute next depending whether117-119 expression is TRUE or not The general description is given below In the examples below the command dispis frequently used This command displays on the screen the text between the quotesbull if endSyntaxif logical_expressionstatement1statement2endExampleif (a gt 0)b = adisp (rsquoa is positiversquo)endbull if else endSyntaxif logical_expressionblock of statementsevaluated if TRUEelseblock of statementsevaluated if FALSEendExampleif (temperature gt 100)disp (rsquoAbove boilingrsquo)toohigh = 1elsedisp (rsquoTemperature is OKrsquo)toohigh = 0endbull if elseif else endSyntaxif logical_expression1block of statements evaluatedif logical_expression1 is TRUEelseif logical_expression2block of statements evaluatedif logical_expression2 is TRUEelseblock of statements evaluatedif no other expression is TRUEendExampleif (height gt 190)disp (rsquovery tallrsquo)elseif (height gt 170)disp (rsquotallrsquo)elseif (height lt 150)disp (rsquosmallrsquo)

elsedisp (rsquoaveragersquo)endRemark To do the exercises below a script m-file will be useful It is an external file that contains asequence of Matlab commands What you need to do is to open an editor enter all commands needed forthe solution of a task save it with the extension rsquomrsquo (eg mytaskm) and then run it from the CommandWindow by typing mytask To open the Matlab editor go to the File menu-bar choose the Open optionand then m-file A new window will appear where you can write your scripts and save them on the disk Allcommands in the script will be executed in Matlab You will learn more on script m-files in section 91Important m-script file must be saved in one of the directories in Matlabrsquos pathAn example A script shortm can be created from the two lines given below and run by calling shortx = 0054plot (x sin(x) rsquo-rsquo)Exercise 26Create a script that asks for a number N and computes the drag coefficient C depending on the Reynoldrsquos23number N (make use of the if elseif construction) The command input might be useful here(read pages 32-33 from rdquoThe Student Edition of Matlabrdquoor use help)C =8gtgtgtltgtgtgt0 N _ 024N N 2 (0 01]24N (1 + 014N07) N 2 (01 1e3]043 N 2 (1e3 5e5]019 minus 8e4N N gt 5e5Check whether your script works correctly Compute the drag coefficient for eg N = -3e3 001 56 1e3 3e6(remember that eg 3e3 is a Matlab notation of 3 _ 103) _Exercise 27Write a script that asks for an integer and checks whether it can be divided by 2 or 3 Consider all possibilitiessuch as divisible by both 2 and 3 divisible by 2 and not by 3 etc (use the command rem) _Another selection structure is switch which switches between several cases depending on an expression which119-120 is either a scalar or a stringSyntaxswitch expressioncase choice1block of commands1case choice2a choice2bblock of commands2otherwiseblock of commandsendExamplemethod = 2switch methodcase 12disp(rsquoMethod is linearrsquo)case 3disp(rsquoMethod is cubicrsquo)case 4disp(rsquoMethod is nearestrsquo)otherwisedisp(rsquoUnknown methodrsquo)endThe statements following the first case where the expression matches the choice are executed Thisconstruction can be very handy to avoid long if elseif else end constructions Theexpression can be a scalar or a string A scalar expression matches a choice if expression == choice Astring expression matches a choice if strcmp(expression choice) returns 1 (is true) (strcmp is a commandcomparing two strings)Important Note that the switch-construction only allows the execution of one group of commandsExercise 28Assume that the months are represented by numbers from 1 to 12 Write a script that asks you to provide a

month and returns the number of days in that particular month Alternatively write a script that asks youto provide a month name (eg rsquoJunersquo) instead of a number Use the switch-construction _63 LoopsIteration control structures loops are used to repeat a block of statements until some condition is met Two114-117 types of loops existbull the for loop that repeats a group of statements a fixed number of timesSyntaxfor index = firststeplastblock of statementsendExamplesumx = 0for i=1length(x)sumx = sumx + x(i)end24You can specify any step including a negative value The index of the for-loop can be also a vectorSee some examples of possible variationsExample 1for i=12nendExample 2for i=n-13endExample 3for x=0054disp(x^2)endExample 4for x=[25 9 81]disp(sqrt(x))endbull while loop which evaluates a group of commands as long as expression is TRUESyntaxwhile expressionstatement1statement2statement3endExampleN = 100iter = 1msum = 0while iter lt= Nmsum = msum + iteriter = iter + 1endExercise 29Given the vectors x and y write a script computing the a matrix whose elements should be created accordingto a formula given below (make use of the length command to check the number of elements in both vectors)- aij = yixj (make sure that a division by zero will not occur)- bij = xi _ yj

- cij = 1 max (xi yj)_Exercise 30Determine the sum of the first 50 squared numbers with a control loop _Exercise 31Write a script to find the largest value n such that the sum p13 + p23 + + pn3 is less than 1000 _optionalExercise 32Write a script that transposes a matrix A Check its correctness with the Matlab operation Arsquo _Exercise 33

Write a script that asks for a temperature in degrees Celsius tc and computes the equivalent temperature indegrees Fahrenheit tf (use the formula tf = 95 _ tc + 32) The script should keep running until no numberis provided to convert The functions input and isempty (use help to learn more) should be useful here _end optional

64 Evaluation of logical and relational expressions in the control flow structuresThe relational and logical expressions may become more complicated It is not difficult to operate on them ifyou understand how they are evaluated To explain more details let us consider the following exampleif (~isempty(data)) amp (max(data) lt 5)endThis construction of the if-block is necessary to avoid comparison if data happens to be an empty matrix Insuch a case you cannot evaluate any expression and Matlab gives an error The amp operator returns 1 only ifboth expressions ~isempty (data) and max(data) lt 5 are true and 0 otherwise When data is an emptymatrix the next expression is not evaluated since the whole amp-expression is already known to be false Thesecond expression is checked only if data is a non-empty matrix Remember to put logical expression unitsbetween brackets to avoid wrong evaluations25Important The fact that computers make use of floating-point arithmetic means that often you should becareful when comparing two floating-point numbers just byif (x == y)end(Of course such a construction is allowed eg when you know that x and y represent integers) Instead of theabove construction you may try using thisif (abs (x - y) lt tolerance) eg tolerance = 1e-10endExercise 34Consider the following examplemax_iter = 50tolerance = 1e-4iter = 0xold = 01x = 1while (abs (x - xold) gt tolerance) amp (iter lt max_iter)xold = xx = cos(xold)iter = iter + 1endThis short program tries to solve the equation cos(x) = x (x is the solution found) Make the script solve cosfrom the presented code Note that the while-loop is repeated as long as both conditions are true If eitherthe condition (|x - xold| lt= tolerance) or (iter gt= max iter) is fulfilled then the loop is quitted Runthe script solve cos for different tolerance parameters eg 1e-3 1e-6 1e-8 1e-10 etc Use format long tocheck more precisely how much the found x is really different from cos(x) For each tolerance value checkthe number of performed iterations (iter value) _Exercise 35Create the script solve cos2 which is equal to the one given replacing the while-loop condition bywhile (abs (x - xold) gt tolerance) | (iter lt max_iter)Try to understand the difference and confirm your expectations by running solve cos2 What happens toiter _optional

65 Numerical analysis and the control flow structuresTake a look at the problem of a Taylor expansion The series will be determined numerically until the additionalterms are smaller than a defined precision Look at the Taylor expansion of 11minusx = 1 + x + x2 + withx = 042s = 0 x = 1 s = 0 x = 1x0 = 042 x0 = 042while (x gt 1e-6) or while (x gt (1e-6)s)s = s + x s = s + xx = x x0 x = x x0end endThe approximation of 11minusx is returned in s (first letter of sum) In the first case (on the left) the iteration

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 18: Introduction to Programming Using Matlab

_end optional

34 PrintingBefore printing a figure you made you might want to add some information such as a title or change the189-196 lay-out a little Table 5 shows some of the commands that can be usedExercise 17Plot the functions y1 = sin(4x) y2 = x cos(x) y3 = (x + 1)minus1px for x = 0 025 10 and a single point(x y) = (4 5) in one figure with different colors and styles Make a legend containing the three functionsMake labels for both axes and a title Add a text to the single point saying single point Change the minimumand maximum values of the axes such that function y3 can be looked at in more detail _When the displayed figure is to your liking you can print it to paper The easiest way to do this is to click onFile in the menu-bar and to choose Print If in the print window you click OK your figure will be printed onthe printer indicated in the print window18Command Resultgrid onoff adds a grid to the plot at the tick marks or removes itaxis([xmin xmax ymin ymax]) sets the minimum and maximum values of the axesbox offon removes the axes box or shows itxlabel(rsquotextrsquo) plots the label text on the x axisylabel(rsquotextrsquo) plots the label text on the y axistitle(rsquotextrsquo) plots a title above the graphtext(xyrsquotextrsquo) adds text at the point (xy)gtext(rsquotextrsquo) adds text at a manually (with a mouse) indicated pointlegend(rsquofun1rsquorsquofun2rsquo) plots a legend box (move it with your mouse) to name your functionslegend off deletes the legend boxTable 5 Plot-manipulationsThere is also a print command which can be used to send a figure to a printer or output it to a file Youcan optionally specify a print device (ie an output format such as tiff or postscript) and options that controlvarious characteristics of the printed file (ie which Figure to print etc) You can also print to a file if youspecify the file name If you do not provide an extension print adds one Since they are many parametersthey will not be explained here (check help print to learn more) Instead try to understand the examplesgtgt print -dwinc print the current Figure to the current printer in colorgtgt print -f1 -deps myfileeps print Figure no1 to the file myfileeps in blackgtgt print -f1 -depsc myfileceps print Figure no1 to the file myfilecoleps in colorgtgt print -dtiff myfile1tiff print the current Figure to the file myfile1tiffgtgt print -dpsc myfile1cps print the current Figure to the file myfile1ps in colorgtgt print -f2 -djpeg myfile2 print Figure no2 to the file myfile2jpgExercise 18Exercise with printing (especially to a file) the figure from Exercise 16 _

4 Curve fitting and interpolationThere are two ways to describe data with an analytical function- curve fitting or regression finding a smooth curve that best fits (approximates) the data accordingto a criterion (eg best least square fit) The curve does not have to go through any of the data points- interpolation the data are assumed to be correct desired in a way to describe what happens betweenthe data points In other words given a finite set of points the goal of interpolation is to find a functionfrom a given class of functions (eg polynomials) which passes through the specified pointsThe figure below illustrates the difference between regression (curve fitting) and interpolationminus5 0 5minus6minus4minus20246810fiting a 3rd order polynomialinterpolation

41 Curve fittingMatlab interprets the best fit of a curve by the lsquoleast squares curve fittingrsquo The curve used is restricted153-15619to polynomials With the command polyfit any polynomial can be fitted to the data polyfit (x y n)finds the coefficients of a polynomial of degree n that fits the data (finds the linear relation between x and y)Letrsquos start with finding a linear regression of some datagtgt x = 010gtgt y = [-10 24 102 158 284 276 299 405 483 522 751]gtgt p = polyfit (x y 1) find the fitting polynomial of order 1p = 06772 -03914

The output of polyfit is a row vector of the polynomial coefficients the solution of this example is thereforey = 06772x minus 03914Exercise 19Execute the above example Plot the data and the fitted curve in a figure Determine the 2nd and 9th orderpolynomial of these data as well and display the solution in a figureHint x1 = linspace (xmin xmax n) results in a vector with n element evenly distributed from xmintill xmax z = polyval (p x1) calculates the values of the polynomial for every element of x1 _Exercise 20Define x and y as followsgtgt x = -55gtgt y = 02x^3 - x + 2 a 3rd order polynomialgtgt y = y + randn(111) add some noise to yDetermine the 3rd order polynomial fitting y (note that because of added noise the coefficients are differentthat originally chosen) Try some other polynomials as well Plot the results in a figure _42 InterpolationThe simplest way to examine an interpolation is by displaying the function plots with the command plot157-161 The neighboring data points are connected with straight lines This is called a linear interpolation Whenmore data-points are taken into account the effect of interpolation becomes less visible Analyzegtgt x1 = linspace(0 2pi2)gtgt x2 = linspace(0 2pi4)gtgt x3 = linspace(0 2pi16)gtgt x4 = linspace(0 2pi256)gtgt plot(x1sin(x1)x2sin(x2)x3sin(x3)x4sin(x4))gtgt legend(rsquo2 pointsrsquorsquo4 pointsrsquorsquo16 pointsrsquorsquo256 pointsrsquo)

5 Numerical analysisNumerical analysis can be used whenever it is impossible or very difficult to determine the analytical solutionMatlab can be used to find for example the minimum maximum or integral of a certain function51 Evaluation of a functionAs said before the command plot plots a function by connecting defined data points Sometimes however a168-173 function is constant and not very interesting over some range and then acts unexpectedly wildly over anotherWith plot this function might be misinterpreted The command fplot is then useful An examplegtgt x = 0pi82pigtgt y = sin (8x)gtgt plot (x y rsquobrsquo)gtgt hold ongtgt fplot (rsquosin (8z)rsquo [0 2pi] rsquorrsquo)gtgt title (rsquosin (8z)rsquo)gtgt hold off20Command Resultfplot (rsquofunrsquo [min x max x]) plots the function fun for min x till max xfmin (rsquofunrsquo min x max x) gives the x-value of the miminum of thefunction fun between min x and max xfzero (rsquofunrsquo x0) gives the x-value for which the functionfun is zero in the neighborhood of x0Table 6 Evaluation of a functionExecution of these commands results in a figure with an almost straight blue line and a red sine fplot canalso be used to plot a defined functiongtgt f = rsquosin (8z)rsquogtgt fplot (f [0 2pi] rsquorrsquo)gtgt title (f)Other useful commands for a detailed study of a range of a function are listed in Table 6Exercise 21The command fmax does not exist Use one or more of the commands from Table 6 to determine the maximumof the function x cos(x) for 10 lt x lt 15 _52 Integration and differentiationThe integral- or the surface underneath a 2D function- can be determined with the command trapz trapz173-182 does this by measuring the surface between the x-axis and the -by a straight line connected- data points Theaccuracy of this method depends on the distance between the data pointsgtgt x = 00510 y = 05 sqrt (x) + x sin (x) area1 = trapz (x y)

area1 =181655gtgt x = 000510 y = 05 sqrt (x) + x sin (x) area2 = trapz (x y)area2 =183846Differentiation is done by determining the slope in each data point Numerically this is done by first fitting apolynomial followed by differentiating this functiongtgt x = 010gtgt y = [-10 24 102 -158 284 276 775 35 483 522 751]gtgt p = polyfit (x y 5)p = 00026 -00554 03634 -06888 02747 00877gtgt dp = polyder (p)dp = 00132 -02216 10903 -13776 02747gtgt x1 = linspace (0 10 200)gtgt z = polyval (p x1)gtgt dz = polyval (dp x1)gtgt plot (x y rsquog-rsquo x1 z rsquobrsquo x1 dz rsquorrsquo)gtgt legend (rsquodata pointsrsquo rsquocurve fitrsquo rsquoderivativersquo)Exercise 22Determine the integral and derivative of the 4th polynomial fitted through (xy) with x = [4 5 6 7 8 9 1011 12 13] y = [1284 1200 724 -096 -1116 -2096 -2700 -2496 -956 2544] _

6 Control flowAs you know it is possible to execute more than one command at the same time (see section 11) Theseparate commands should then be divided by commarsquos (to display the output) or by semicolons (to suppress21output display) Control flow loops increase the number of possibilities A control flow structure is a block ofcommands that allows conditional code execution and making loops61 Logical and relational operatorsTo use control flow commands it is necessary to perform operations that result in logical values TRUE or88-91 FALSE In Matlab the result of a logical operation is 1 if it is true and 0 if it is false Table 7 shows therelational and logical operations2 Another way to get to know more about them is to type help relop Therelational operators lt lt= gt gt= == and ~= can be used to compare two arrays of the same size or anarray to a scalar The logical operators amp | and ~ allow for the logical combination or negation of relationaloperators In addition three functions are also available xor any and all (use help to find out more)Important The logical amp and | have the equal precedence in Matlab which means that those operatorsassociate from left to right A common situation isgtgt b = 10gtgt 1 | b gt 0 amp 0ans =0gtgt (1 | b gt 0) amp 0 this indicates the same as aboveans =0gtgt 1 | (b gt 0 amp 0)ans =1This shows that you should always use brackets to indicate in which way the operators should be evaluatedCommand Resulta = (b gt c) a is 1 if b is larger than c Similar are lt gt= and lt=a = (b == c) a is 1 if b is equal to ca = (b ~= c) a is 1 if b is not equal ca = ~b logical complement a is 1 if b is 0a = (b amp c) logical AND a is 1 if b = TRUE AND c = TRUEa = (b | c) logical OR a is 1 if b = TRUE OR c = TRUETable 7 Relational and logical operationsExercise 23Predict and check the result of each of the operations of Table 7 for b = 0 and c = -1 _Exercise 24Define two vectors with seven elements (randn(17)) and perform all logical operations including xor anyand all _Exercise 25While doing logical operations between a vector and a scalar each element of the vector is compared to thescalar Predict and check the result of each logical operator for the vector b = [2 31 -40 0] and the scalarc = 0 _Before moving on check whether you now understand the following relations

gtgt a = randperm(10) a random permutation of the numbers from 1 to 10gtgt b = 110gtgt b - (a lt= 7) subtracts from b a 0-1 vector taking 1 for a lt= 7 and 0 otherwisegtgt (a gt= 2) amp (a lt 4) returns ones at positions where 2 lt= a lt 4gtgt ~(b gt 4) returns ones at positions where b lt= 4gtgt (a == b) | b == 3 returns ones at positions where a is equal to b or b is equal to 3gtgt any (a gt 5) returns 1 when ANY of the a elements are larger than 5gtgt any (b lt 5 amp a gt 8) returns 1 when there in the evaluated expressiongtgt (b lt 5 amp a gt 8) appears at least one 1gtgt all (b gt 2) returns 1 when ALL b elements are larger than 22rdquoequal tordquo in the table on page 88 of rdquoThe Student Edition of Matlabrdquo must be rdquo==rdquo instead of rdquo=rdquo2262 Conditional code executionSelection control structures if-blocks are used to decide which instruction to execute next depending whether117-119 expression is TRUE or not The general description is given below In the examples below the command dispis frequently used This command displays on the screen the text between the quotesbull if endSyntaxif logical_expressionstatement1statement2endExampleif (a gt 0)b = adisp (rsquoa is positiversquo)endbull if else endSyntaxif logical_expressionblock of statementsevaluated if TRUEelseblock of statementsevaluated if FALSEendExampleif (temperature gt 100)disp (rsquoAbove boilingrsquo)toohigh = 1elsedisp (rsquoTemperature is OKrsquo)toohigh = 0endbull if elseif else endSyntaxif logical_expression1block of statements evaluatedif logical_expression1 is TRUEelseif logical_expression2block of statements evaluatedif logical_expression2 is TRUEelseblock of statements evaluatedif no other expression is TRUEendExampleif (height gt 190)disp (rsquovery tallrsquo)elseif (height gt 170)disp (rsquotallrsquo)elseif (height lt 150)disp (rsquosmallrsquo)

elsedisp (rsquoaveragersquo)endRemark To do the exercises below a script m-file will be useful It is an external file that contains asequence of Matlab commands What you need to do is to open an editor enter all commands needed forthe solution of a task save it with the extension rsquomrsquo (eg mytaskm) and then run it from the CommandWindow by typing mytask To open the Matlab editor go to the File menu-bar choose the Open optionand then m-file A new window will appear where you can write your scripts and save them on the disk Allcommands in the script will be executed in Matlab You will learn more on script m-files in section 91Important m-script file must be saved in one of the directories in Matlabrsquos pathAn example A script shortm can be created from the two lines given below and run by calling shortx = 0054plot (x sin(x) rsquo-rsquo)Exercise 26Create a script that asks for a number N and computes the drag coefficient C depending on the Reynoldrsquos23number N (make use of the if elseif construction) The command input might be useful here(read pages 32-33 from rdquoThe Student Edition of Matlabrdquoor use help)C =8gtgtgtltgtgtgt0 N _ 024N N 2 (0 01]24N (1 + 014N07) N 2 (01 1e3]043 N 2 (1e3 5e5]019 minus 8e4N N gt 5e5Check whether your script works correctly Compute the drag coefficient for eg N = -3e3 001 56 1e3 3e6(remember that eg 3e3 is a Matlab notation of 3 _ 103) _Exercise 27Write a script that asks for an integer and checks whether it can be divided by 2 or 3 Consider all possibilitiessuch as divisible by both 2 and 3 divisible by 2 and not by 3 etc (use the command rem) _Another selection structure is switch which switches between several cases depending on an expression which119-120 is either a scalar or a stringSyntaxswitch expressioncase choice1block of commands1case choice2a choice2bblock of commands2otherwiseblock of commandsendExamplemethod = 2switch methodcase 12disp(rsquoMethod is linearrsquo)case 3disp(rsquoMethod is cubicrsquo)case 4disp(rsquoMethod is nearestrsquo)otherwisedisp(rsquoUnknown methodrsquo)endThe statements following the first case where the expression matches the choice are executed Thisconstruction can be very handy to avoid long if elseif else end constructions Theexpression can be a scalar or a string A scalar expression matches a choice if expression == choice Astring expression matches a choice if strcmp(expression choice) returns 1 (is true) (strcmp is a commandcomparing two strings)Important Note that the switch-construction only allows the execution of one group of commandsExercise 28Assume that the months are represented by numbers from 1 to 12 Write a script that asks you to provide a

month and returns the number of days in that particular month Alternatively write a script that asks youto provide a month name (eg rsquoJunersquo) instead of a number Use the switch-construction _63 LoopsIteration control structures loops are used to repeat a block of statements until some condition is met Two114-117 types of loops existbull the for loop that repeats a group of statements a fixed number of timesSyntaxfor index = firststeplastblock of statementsendExamplesumx = 0for i=1length(x)sumx = sumx + x(i)end24You can specify any step including a negative value The index of the for-loop can be also a vectorSee some examples of possible variationsExample 1for i=12nendExample 2for i=n-13endExample 3for x=0054disp(x^2)endExample 4for x=[25 9 81]disp(sqrt(x))endbull while loop which evaluates a group of commands as long as expression is TRUESyntaxwhile expressionstatement1statement2statement3endExampleN = 100iter = 1msum = 0while iter lt= Nmsum = msum + iteriter = iter + 1endExercise 29Given the vectors x and y write a script computing the a matrix whose elements should be created accordingto a formula given below (make use of the length command to check the number of elements in both vectors)- aij = yixj (make sure that a division by zero will not occur)- bij = xi _ yj

- cij = 1 max (xi yj)_Exercise 30Determine the sum of the first 50 squared numbers with a control loop _Exercise 31Write a script to find the largest value n such that the sum p13 + p23 + + pn3 is less than 1000 _optionalExercise 32Write a script that transposes a matrix A Check its correctness with the Matlab operation Arsquo _Exercise 33

Write a script that asks for a temperature in degrees Celsius tc and computes the equivalent temperature indegrees Fahrenheit tf (use the formula tf = 95 _ tc + 32) The script should keep running until no numberis provided to convert The functions input and isempty (use help to learn more) should be useful here _end optional

64 Evaluation of logical and relational expressions in the control flow structuresThe relational and logical expressions may become more complicated It is not difficult to operate on them ifyou understand how they are evaluated To explain more details let us consider the following exampleif (~isempty(data)) amp (max(data) lt 5)endThis construction of the if-block is necessary to avoid comparison if data happens to be an empty matrix Insuch a case you cannot evaluate any expression and Matlab gives an error The amp operator returns 1 only ifboth expressions ~isempty (data) and max(data) lt 5 are true and 0 otherwise When data is an emptymatrix the next expression is not evaluated since the whole amp-expression is already known to be false Thesecond expression is checked only if data is a non-empty matrix Remember to put logical expression unitsbetween brackets to avoid wrong evaluations25Important The fact that computers make use of floating-point arithmetic means that often you should becareful when comparing two floating-point numbers just byif (x == y)end(Of course such a construction is allowed eg when you know that x and y represent integers) Instead of theabove construction you may try using thisif (abs (x - y) lt tolerance) eg tolerance = 1e-10endExercise 34Consider the following examplemax_iter = 50tolerance = 1e-4iter = 0xold = 01x = 1while (abs (x - xold) gt tolerance) amp (iter lt max_iter)xold = xx = cos(xold)iter = iter + 1endThis short program tries to solve the equation cos(x) = x (x is the solution found) Make the script solve cosfrom the presented code Note that the while-loop is repeated as long as both conditions are true If eitherthe condition (|x - xold| lt= tolerance) or (iter gt= max iter) is fulfilled then the loop is quitted Runthe script solve cos for different tolerance parameters eg 1e-3 1e-6 1e-8 1e-10 etc Use format long tocheck more precisely how much the found x is really different from cos(x) For each tolerance value checkthe number of performed iterations (iter value) _Exercise 35Create the script solve cos2 which is equal to the one given replacing the while-loop condition bywhile (abs (x - xold) gt tolerance) | (iter lt max_iter)Try to understand the difference and confirm your expectations by running solve cos2 What happens toiter _optional

65 Numerical analysis and the control flow structuresTake a look at the problem of a Taylor expansion The series will be determined numerically until the additionalterms are smaller than a defined precision Look at the Taylor expansion of 11minusx = 1 + x + x2 + withx = 042s = 0 x = 1 s = 0 x = 1x0 = 042 x0 = 042while (x gt 1e-6) or while (x gt (1e-6)s)s = s + x s = s + xx = x x0 x = x x0end endThe approximation of 11minusx is returned in s (first letter of sum) In the first case (on the left) the iteration

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 19: Introduction to Programming Using Matlab

The output of polyfit is a row vector of the polynomial coefficients the solution of this example is thereforey = 06772x minus 03914Exercise 19Execute the above example Plot the data and the fitted curve in a figure Determine the 2nd and 9th orderpolynomial of these data as well and display the solution in a figureHint x1 = linspace (xmin xmax n) results in a vector with n element evenly distributed from xmintill xmax z = polyval (p x1) calculates the values of the polynomial for every element of x1 _Exercise 20Define x and y as followsgtgt x = -55gtgt y = 02x^3 - x + 2 a 3rd order polynomialgtgt y = y + randn(111) add some noise to yDetermine the 3rd order polynomial fitting y (note that because of added noise the coefficients are differentthat originally chosen) Try some other polynomials as well Plot the results in a figure _42 InterpolationThe simplest way to examine an interpolation is by displaying the function plots with the command plot157-161 The neighboring data points are connected with straight lines This is called a linear interpolation Whenmore data-points are taken into account the effect of interpolation becomes less visible Analyzegtgt x1 = linspace(0 2pi2)gtgt x2 = linspace(0 2pi4)gtgt x3 = linspace(0 2pi16)gtgt x4 = linspace(0 2pi256)gtgt plot(x1sin(x1)x2sin(x2)x3sin(x3)x4sin(x4))gtgt legend(rsquo2 pointsrsquorsquo4 pointsrsquorsquo16 pointsrsquorsquo256 pointsrsquo)

5 Numerical analysisNumerical analysis can be used whenever it is impossible or very difficult to determine the analytical solutionMatlab can be used to find for example the minimum maximum or integral of a certain function51 Evaluation of a functionAs said before the command plot plots a function by connecting defined data points Sometimes however a168-173 function is constant and not very interesting over some range and then acts unexpectedly wildly over anotherWith plot this function might be misinterpreted The command fplot is then useful An examplegtgt x = 0pi82pigtgt y = sin (8x)gtgt plot (x y rsquobrsquo)gtgt hold ongtgt fplot (rsquosin (8z)rsquo [0 2pi] rsquorrsquo)gtgt title (rsquosin (8z)rsquo)gtgt hold off20Command Resultfplot (rsquofunrsquo [min x max x]) plots the function fun for min x till max xfmin (rsquofunrsquo min x max x) gives the x-value of the miminum of thefunction fun between min x and max xfzero (rsquofunrsquo x0) gives the x-value for which the functionfun is zero in the neighborhood of x0Table 6 Evaluation of a functionExecution of these commands results in a figure with an almost straight blue line and a red sine fplot canalso be used to plot a defined functiongtgt f = rsquosin (8z)rsquogtgt fplot (f [0 2pi] rsquorrsquo)gtgt title (f)Other useful commands for a detailed study of a range of a function are listed in Table 6Exercise 21The command fmax does not exist Use one or more of the commands from Table 6 to determine the maximumof the function x cos(x) for 10 lt x lt 15 _52 Integration and differentiationThe integral- or the surface underneath a 2D function- can be determined with the command trapz trapz173-182 does this by measuring the surface between the x-axis and the -by a straight line connected- data points Theaccuracy of this method depends on the distance between the data pointsgtgt x = 00510 y = 05 sqrt (x) + x sin (x) area1 = trapz (x y)

area1 =181655gtgt x = 000510 y = 05 sqrt (x) + x sin (x) area2 = trapz (x y)area2 =183846Differentiation is done by determining the slope in each data point Numerically this is done by first fitting apolynomial followed by differentiating this functiongtgt x = 010gtgt y = [-10 24 102 -158 284 276 775 35 483 522 751]gtgt p = polyfit (x y 5)p = 00026 -00554 03634 -06888 02747 00877gtgt dp = polyder (p)dp = 00132 -02216 10903 -13776 02747gtgt x1 = linspace (0 10 200)gtgt z = polyval (p x1)gtgt dz = polyval (dp x1)gtgt plot (x y rsquog-rsquo x1 z rsquobrsquo x1 dz rsquorrsquo)gtgt legend (rsquodata pointsrsquo rsquocurve fitrsquo rsquoderivativersquo)Exercise 22Determine the integral and derivative of the 4th polynomial fitted through (xy) with x = [4 5 6 7 8 9 1011 12 13] y = [1284 1200 724 -096 -1116 -2096 -2700 -2496 -956 2544] _

6 Control flowAs you know it is possible to execute more than one command at the same time (see section 11) Theseparate commands should then be divided by commarsquos (to display the output) or by semicolons (to suppress21output display) Control flow loops increase the number of possibilities A control flow structure is a block ofcommands that allows conditional code execution and making loops61 Logical and relational operatorsTo use control flow commands it is necessary to perform operations that result in logical values TRUE or88-91 FALSE In Matlab the result of a logical operation is 1 if it is true and 0 if it is false Table 7 shows therelational and logical operations2 Another way to get to know more about them is to type help relop Therelational operators lt lt= gt gt= == and ~= can be used to compare two arrays of the same size or anarray to a scalar The logical operators amp | and ~ allow for the logical combination or negation of relationaloperators In addition three functions are also available xor any and all (use help to find out more)Important The logical amp and | have the equal precedence in Matlab which means that those operatorsassociate from left to right A common situation isgtgt b = 10gtgt 1 | b gt 0 amp 0ans =0gtgt (1 | b gt 0) amp 0 this indicates the same as aboveans =0gtgt 1 | (b gt 0 amp 0)ans =1This shows that you should always use brackets to indicate in which way the operators should be evaluatedCommand Resulta = (b gt c) a is 1 if b is larger than c Similar are lt gt= and lt=a = (b == c) a is 1 if b is equal to ca = (b ~= c) a is 1 if b is not equal ca = ~b logical complement a is 1 if b is 0a = (b amp c) logical AND a is 1 if b = TRUE AND c = TRUEa = (b | c) logical OR a is 1 if b = TRUE OR c = TRUETable 7 Relational and logical operationsExercise 23Predict and check the result of each of the operations of Table 7 for b = 0 and c = -1 _Exercise 24Define two vectors with seven elements (randn(17)) and perform all logical operations including xor anyand all _Exercise 25While doing logical operations between a vector and a scalar each element of the vector is compared to thescalar Predict and check the result of each logical operator for the vector b = [2 31 -40 0] and the scalarc = 0 _Before moving on check whether you now understand the following relations

gtgt a = randperm(10) a random permutation of the numbers from 1 to 10gtgt b = 110gtgt b - (a lt= 7) subtracts from b a 0-1 vector taking 1 for a lt= 7 and 0 otherwisegtgt (a gt= 2) amp (a lt 4) returns ones at positions where 2 lt= a lt 4gtgt ~(b gt 4) returns ones at positions where b lt= 4gtgt (a == b) | b == 3 returns ones at positions where a is equal to b or b is equal to 3gtgt any (a gt 5) returns 1 when ANY of the a elements are larger than 5gtgt any (b lt 5 amp a gt 8) returns 1 when there in the evaluated expressiongtgt (b lt 5 amp a gt 8) appears at least one 1gtgt all (b gt 2) returns 1 when ALL b elements are larger than 22rdquoequal tordquo in the table on page 88 of rdquoThe Student Edition of Matlabrdquo must be rdquo==rdquo instead of rdquo=rdquo2262 Conditional code executionSelection control structures if-blocks are used to decide which instruction to execute next depending whether117-119 expression is TRUE or not The general description is given below In the examples below the command dispis frequently used This command displays on the screen the text between the quotesbull if endSyntaxif logical_expressionstatement1statement2endExampleif (a gt 0)b = adisp (rsquoa is positiversquo)endbull if else endSyntaxif logical_expressionblock of statementsevaluated if TRUEelseblock of statementsevaluated if FALSEendExampleif (temperature gt 100)disp (rsquoAbove boilingrsquo)toohigh = 1elsedisp (rsquoTemperature is OKrsquo)toohigh = 0endbull if elseif else endSyntaxif logical_expression1block of statements evaluatedif logical_expression1 is TRUEelseif logical_expression2block of statements evaluatedif logical_expression2 is TRUEelseblock of statements evaluatedif no other expression is TRUEendExampleif (height gt 190)disp (rsquovery tallrsquo)elseif (height gt 170)disp (rsquotallrsquo)elseif (height lt 150)disp (rsquosmallrsquo)

elsedisp (rsquoaveragersquo)endRemark To do the exercises below a script m-file will be useful It is an external file that contains asequence of Matlab commands What you need to do is to open an editor enter all commands needed forthe solution of a task save it with the extension rsquomrsquo (eg mytaskm) and then run it from the CommandWindow by typing mytask To open the Matlab editor go to the File menu-bar choose the Open optionand then m-file A new window will appear where you can write your scripts and save them on the disk Allcommands in the script will be executed in Matlab You will learn more on script m-files in section 91Important m-script file must be saved in one of the directories in Matlabrsquos pathAn example A script shortm can be created from the two lines given below and run by calling shortx = 0054plot (x sin(x) rsquo-rsquo)Exercise 26Create a script that asks for a number N and computes the drag coefficient C depending on the Reynoldrsquos23number N (make use of the if elseif construction) The command input might be useful here(read pages 32-33 from rdquoThe Student Edition of Matlabrdquoor use help)C =8gtgtgtltgtgtgt0 N _ 024N N 2 (0 01]24N (1 + 014N07) N 2 (01 1e3]043 N 2 (1e3 5e5]019 minus 8e4N N gt 5e5Check whether your script works correctly Compute the drag coefficient for eg N = -3e3 001 56 1e3 3e6(remember that eg 3e3 is a Matlab notation of 3 _ 103) _Exercise 27Write a script that asks for an integer and checks whether it can be divided by 2 or 3 Consider all possibilitiessuch as divisible by both 2 and 3 divisible by 2 and not by 3 etc (use the command rem) _Another selection structure is switch which switches between several cases depending on an expression which119-120 is either a scalar or a stringSyntaxswitch expressioncase choice1block of commands1case choice2a choice2bblock of commands2otherwiseblock of commandsendExamplemethod = 2switch methodcase 12disp(rsquoMethod is linearrsquo)case 3disp(rsquoMethod is cubicrsquo)case 4disp(rsquoMethod is nearestrsquo)otherwisedisp(rsquoUnknown methodrsquo)endThe statements following the first case where the expression matches the choice are executed Thisconstruction can be very handy to avoid long if elseif else end constructions Theexpression can be a scalar or a string A scalar expression matches a choice if expression == choice Astring expression matches a choice if strcmp(expression choice) returns 1 (is true) (strcmp is a commandcomparing two strings)Important Note that the switch-construction only allows the execution of one group of commandsExercise 28Assume that the months are represented by numbers from 1 to 12 Write a script that asks you to provide a

month and returns the number of days in that particular month Alternatively write a script that asks youto provide a month name (eg rsquoJunersquo) instead of a number Use the switch-construction _63 LoopsIteration control structures loops are used to repeat a block of statements until some condition is met Two114-117 types of loops existbull the for loop that repeats a group of statements a fixed number of timesSyntaxfor index = firststeplastblock of statementsendExamplesumx = 0for i=1length(x)sumx = sumx + x(i)end24You can specify any step including a negative value The index of the for-loop can be also a vectorSee some examples of possible variationsExample 1for i=12nendExample 2for i=n-13endExample 3for x=0054disp(x^2)endExample 4for x=[25 9 81]disp(sqrt(x))endbull while loop which evaluates a group of commands as long as expression is TRUESyntaxwhile expressionstatement1statement2statement3endExampleN = 100iter = 1msum = 0while iter lt= Nmsum = msum + iteriter = iter + 1endExercise 29Given the vectors x and y write a script computing the a matrix whose elements should be created accordingto a formula given below (make use of the length command to check the number of elements in both vectors)- aij = yixj (make sure that a division by zero will not occur)- bij = xi _ yj

- cij = 1 max (xi yj)_Exercise 30Determine the sum of the first 50 squared numbers with a control loop _Exercise 31Write a script to find the largest value n such that the sum p13 + p23 + + pn3 is less than 1000 _optionalExercise 32Write a script that transposes a matrix A Check its correctness with the Matlab operation Arsquo _Exercise 33

Write a script that asks for a temperature in degrees Celsius tc and computes the equivalent temperature indegrees Fahrenheit tf (use the formula tf = 95 _ tc + 32) The script should keep running until no numberis provided to convert The functions input and isempty (use help to learn more) should be useful here _end optional

64 Evaluation of logical and relational expressions in the control flow structuresThe relational and logical expressions may become more complicated It is not difficult to operate on them ifyou understand how they are evaluated To explain more details let us consider the following exampleif (~isempty(data)) amp (max(data) lt 5)endThis construction of the if-block is necessary to avoid comparison if data happens to be an empty matrix Insuch a case you cannot evaluate any expression and Matlab gives an error The amp operator returns 1 only ifboth expressions ~isempty (data) and max(data) lt 5 are true and 0 otherwise When data is an emptymatrix the next expression is not evaluated since the whole amp-expression is already known to be false Thesecond expression is checked only if data is a non-empty matrix Remember to put logical expression unitsbetween brackets to avoid wrong evaluations25Important The fact that computers make use of floating-point arithmetic means that often you should becareful when comparing two floating-point numbers just byif (x == y)end(Of course such a construction is allowed eg when you know that x and y represent integers) Instead of theabove construction you may try using thisif (abs (x - y) lt tolerance) eg tolerance = 1e-10endExercise 34Consider the following examplemax_iter = 50tolerance = 1e-4iter = 0xold = 01x = 1while (abs (x - xold) gt tolerance) amp (iter lt max_iter)xold = xx = cos(xold)iter = iter + 1endThis short program tries to solve the equation cos(x) = x (x is the solution found) Make the script solve cosfrom the presented code Note that the while-loop is repeated as long as both conditions are true If eitherthe condition (|x - xold| lt= tolerance) or (iter gt= max iter) is fulfilled then the loop is quitted Runthe script solve cos for different tolerance parameters eg 1e-3 1e-6 1e-8 1e-10 etc Use format long tocheck more precisely how much the found x is really different from cos(x) For each tolerance value checkthe number of performed iterations (iter value) _Exercise 35Create the script solve cos2 which is equal to the one given replacing the while-loop condition bywhile (abs (x - xold) gt tolerance) | (iter lt max_iter)Try to understand the difference and confirm your expectations by running solve cos2 What happens toiter _optional

65 Numerical analysis and the control flow structuresTake a look at the problem of a Taylor expansion The series will be determined numerically until the additionalterms are smaller than a defined precision Look at the Taylor expansion of 11minusx = 1 + x + x2 + withx = 042s = 0 x = 1 s = 0 x = 1x0 = 042 x0 = 042while (x gt 1e-6) or while (x gt (1e-6)s)s = s + x s = s + xx = x x0 x = x x0end endThe approximation of 11minusx is returned in s (first letter of sum) In the first case (on the left) the iteration

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 20: Introduction to Programming Using Matlab

area1 =181655gtgt x = 000510 y = 05 sqrt (x) + x sin (x) area2 = trapz (x y)area2 =183846Differentiation is done by determining the slope in each data point Numerically this is done by first fitting apolynomial followed by differentiating this functiongtgt x = 010gtgt y = [-10 24 102 -158 284 276 775 35 483 522 751]gtgt p = polyfit (x y 5)p = 00026 -00554 03634 -06888 02747 00877gtgt dp = polyder (p)dp = 00132 -02216 10903 -13776 02747gtgt x1 = linspace (0 10 200)gtgt z = polyval (p x1)gtgt dz = polyval (dp x1)gtgt plot (x y rsquog-rsquo x1 z rsquobrsquo x1 dz rsquorrsquo)gtgt legend (rsquodata pointsrsquo rsquocurve fitrsquo rsquoderivativersquo)Exercise 22Determine the integral and derivative of the 4th polynomial fitted through (xy) with x = [4 5 6 7 8 9 1011 12 13] y = [1284 1200 724 -096 -1116 -2096 -2700 -2496 -956 2544] _

6 Control flowAs you know it is possible to execute more than one command at the same time (see section 11) Theseparate commands should then be divided by commarsquos (to display the output) or by semicolons (to suppress21output display) Control flow loops increase the number of possibilities A control flow structure is a block ofcommands that allows conditional code execution and making loops61 Logical and relational operatorsTo use control flow commands it is necessary to perform operations that result in logical values TRUE or88-91 FALSE In Matlab the result of a logical operation is 1 if it is true and 0 if it is false Table 7 shows therelational and logical operations2 Another way to get to know more about them is to type help relop Therelational operators lt lt= gt gt= == and ~= can be used to compare two arrays of the same size or anarray to a scalar The logical operators amp | and ~ allow for the logical combination or negation of relationaloperators In addition three functions are also available xor any and all (use help to find out more)Important The logical amp and | have the equal precedence in Matlab which means that those operatorsassociate from left to right A common situation isgtgt b = 10gtgt 1 | b gt 0 amp 0ans =0gtgt (1 | b gt 0) amp 0 this indicates the same as aboveans =0gtgt 1 | (b gt 0 amp 0)ans =1This shows that you should always use brackets to indicate in which way the operators should be evaluatedCommand Resulta = (b gt c) a is 1 if b is larger than c Similar are lt gt= and lt=a = (b == c) a is 1 if b is equal to ca = (b ~= c) a is 1 if b is not equal ca = ~b logical complement a is 1 if b is 0a = (b amp c) logical AND a is 1 if b = TRUE AND c = TRUEa = (b | c) logical OR a is 1 if b = TRUE OR c = TRUETable 7 Relational and logical operationsExercise 23Predict and check the result of each of the operations of Table 7 for b = 0 and c = -1 _Exercise 24Define two vectors with seven elements (randn(17)) and perform all logical operations including xor anyand all _Exercise 25While doing logical operations between a vector and a scalar each element of the vector is compared to thescalar Predict and check the result of each logical operator for the vector b = [2 31 -40 0] and the scalarc = 0 _Before moving on check whether you now understand the following relations

gtgt a = randperm(10) a random permutation of the numbers from 1 to 10gtgt b = 110gtgt b - (a lt= 7) subtracts from b a 0-1 vector taking 1 for a lt= 7 and 0 otherwisegtgt (a gt= 2) amp (a lt 4) returns ones at positions where 2 lt= a lt 4gtgt ~(b gt 4) returns ones at positions where b lt= 4gtgt (a == b) | b == 3 returns ones at positions where a is equal to b or b is equal to 3gtgt any (a gt 5) returns 1 when ANY of the a elements are larger than 5gtgt any (b lt 5 amp a gt 8) returns 1 when there in the evaluated expressiongtgt (b lt 5 amp a gt 8) appears at least one 1gtgt all (b gt 2) returns 1 when ALL b elements are larger than 22rdquoequal tordquo in the table on page 88 of rdquoThe Student Edition of Matlabrdquo must be rdquo==rdquo instead of rdquo=rdquo2262 Conditional code executionSelection control structures if-blocks are used to decide which instruction to execute next depending whether117-119 expression is TRUE or not The general description is given below In the examples below the command dispis frequently used This command displays on the screen the text between the quotesbull if endSyntaxif logical_expressionstatement1statement2endExampleif (a gt 0)b = adisp (rsquoa is positiversquo)endbull if else endSyntaxif logical_expressionblock of statementsevaluated if TRUEelseblock of statementsevaluated if FALSEendExampleif (temperature gt 100)disp (rsquoAbove boilingrsquo)toohigh = 1elsedisp (rsquoTemperature is OKrsquo)toohigh = 0endbull if elseif else endSyntaxif logical_expression1block of statements evaluatedif logical_expression1 is TRUEelseif logical_expression2block of statements evaluatedif logical_expression2 is TRUEelseblock of statements evaluatedif no other expression is TRUEendExampleif (height gt 190)disp (rsquovery tallrsquo)elseif (height gt 170)disp (rsquotallrsquo)elseif (height lt 150)disp (rsquosmallrsquo)

elsedisp (rsquoaveragersquo)endRemark To do the exercises below a script m-file will be useful It is an external file that contains asequence of Matlab commands What you need to do is to open an editor enter all commands needed forthe solution of a task save it with the extension rsquomrsquo (eg mytaskm) and then run it from the CommandWindow by typing mytask To open the Matlab editor go to the File menu-bar choose the Open optionand then m-file A new window will appear where you can write your scripts and save them on the disk Allcommands in the script will be executed in Matlab You will learn more on script m-files in section 91Important m-script file must be saved in one of the directories in Matlabrsquos pathAn example A script shortm can be created from the two lines given below and run by calling shortx = 0054plot (x sin(x) rsquo-rsquo)Exercise 26Create a script that asks for a number N and computes the drag coefficient C depending on the Reynoldrsquos23number N (make use of the if elseif construction) The command input might be useful here(read pages 32-33 from rdquoThe Student Edition of Matlabrdquoor use help)C =8gtgtgtltgtgtgt0 N _ 024N N 2 (0 01]24N (1 + 014N07) N 2 (01 1e3]043 N 2 (1e3 5e5]019 minus 8e4N N gt 5e5Check whether your script works correctly Compute the drag coefficient for eg N = -3e3 001 56 1e3 3e6(remember that eg 3e3 is a Matlab notation of 3 _ 103) _Exercise 27Write a script that asks for an integer and checks whether it can be divided by 2 or 3 Consider all possibilitiessuch as divisible by both 2 and 3 divisible by 2 and not by 3 etc (use the command rem) _Another selection structure is switch which switches between several cases depending on an expression which119-120 is either a scalar or a stringSyntaxswitch expressioncase choice1block of commands1case choice2a choice2bblock of commands2otherwiseblock of commandsendExamplemethod = 2switch methodcase 12disp(rsquoMethod is linearrsquo)case 3disp(rsquoMethod is cubicrsquo)case 4disp(rsquoMethod is nearestrsquo)otherwisedisp(rsquoUnknown methodrsquo)endThe statements following the first case where the expression matches the choice are executed Thisconstruction can be very handy to avoid long if elseif else end constructions Theexpression can be a scalar or a string A scalar expression matches a choice if expression == choice Astring expression matches a choice if strcmp(expression choice) returns 1 (is true) (strcmp is a commandcomparing two strings)Important Note that the switch-construction only allows the execution of one group of commandsExercise 28Assume that the months are represented by numbers from 1 to 12 Write a script that asks you to provide a

month and returns the number of days in that particular month Alternatively write a script that asks youto provide a month name (eg rsquoJunersquo) instead of a number Use the switch-construction _63 LoopsIteration control structures loops are used to repeat a block of statements until some condition is met Two114-117 types of loops existbull the for loop that repeats a group of statements a fixed number of timesSyntaxfor index = firststeplastblock of statementsendExamplesumx = 0for i=1length(x)sumx = sumx + x(i)end24You can specify any step including a negative value The index of the for-loop can be also a vectorSee some examples of possible variationsExample 1for i=12nendExample 2for i=n-13endExample 3for x=0054disp(x^2)endExample 4for x=[25 9 81]disp(sqrt(x))endbull while loop which evaluates a group of commands as long as expression is TRUESyntaxwhile expressionstatement1statement2statement3endExampleN = 100iter = 1msum = 0while iter lt= Nmsum = msum + iteriter = iter + 1endExercise 29Given the vectors x and y write a script computing the a matrix whose elements should be created accordingto a formula given below (make use of the length command to check the number of elements in both vectors)- aij = yixj (make sure that a division by zero will not occur)- bij = xi _ yj

- cij = 1 max (xi yj)_Exercise 30Determine the sum of the first 50 squared numbers with a control loop _Exercise 31Write a script to find the largest value n such that the sum p13 + p23 + + pn3 is less than 1000 _optionalExercise 32Write a script that transposes a matrix A Check its correctness with the Matlab operation Arsquo _Exercise 33

Write a script that asks for a temperature in degrees Celsius tc and computes the equivalent temperature indegrees Fahrenheit tf (use the formula tf = 95 _ tc + 32) The script should keep running until no numberis provided to convert The functions input and isempty (use help to learn more) should be useful here _end optional

64 Evaluation of logical and relational expressions in the control flow structuresThe relational and logical expressions may become more complicated It is not difficult to operate on them ifyou understand how they are evaluated To explain more details let us consider the following exampleif (~isempty(data)) amp (max(data) lt 5)endThis construction of the if-block is necessary to avoid comparison if data happens to be an empty matrix Insuch a case you cannot evaluate any expression and Matlab gives an error The amp operator returns 1 only ifboth expressions ~isempty (data) and max(data) lt 5 are true and 0 otherwise When data is an emptymatrix the next expression is not evaluated since the whole amp-expression is already known to be false Thesecond expression is checked only if data is a non-empty matrix Remember to put logical expression unitsbetween brackets to avoid wrong evaluations25Important The fact that computers make use of floating-point arithmetic means that often you should becareful when comparing two floating-point numbers just byif (x == y)end(Of course such a construction is allowed eg when you know that x and y represent integers) Instead of theabove construction you may try using thisif (abs (x - y) lt tolerance) eg tolerance = 1e-10endExercise 34Consider the following examplemax_iter = 50tolerance = 1e-4iter = 0xold = 01x = 1while (abs (x - xold) gt tolerance) amp (iter lt max_iter)xold = xx = cos(xold)iter = iter + 1endThis short program tries to solve the equation cos(x) = x (x is the solution found) Make the script solve cosfrom the presented code Note that the while-loop is repeated as long as both conditions are true If eitherthe condition (|x - xold| lt= tolerance) or (iter gt= max iter) is fulfilled then the loop is quitted Runthe script solve cos for different tolerance parameters eg 1e-3 1e-6 1e-8 1e-10 etc Use format long tocheck more precisely how much the found x is really different from cos(x) For each tolerance value checkthe number of performed iterations (iter value) _Exercise 35Create the script solve cos2 which is equal to the one given replacing the while-loop condition bywhile (abs (x - xold) gt tolerance) | (iter lt max_iter)Try to understand the difference and confirm your expectations by running solve cos2 What happens toiter _optional

65 Numerical analysis and the control flow structuresTake a look at the problem of a Taylor expansion The series will be determined numerically until the additionalterms are smaller than a defined precision Look at the Taylor expansion of 11minusx = 1 + x + x2 + withx = 042s = 0 x = 1 s = 0 x = 1x0 = 042 x0 = 042while (x gt 1e-6) or while (x gt (1e-6)s)s = s + x s = s + xx = x x0 x = x x0end endThe approximation of 11minusx is returned in s (first letter of sum) In the first case (on the left) the iteration

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 21: Introduction to Programming Using Matlab

gtgt a = randperm(10) a random permutation of the numbers from 1 to 10gtgt b = 110gtgt b - (a lt= 7) subtracts from b a 0-1 vector taking 1 for a lt= 7 and 0 otherwisegtgt (a gt= 2) amp (a lt 4) returns ones at positions where 2 lt= a lt 4gtgt ~(b gt 4) returns ones at positions where b lt= 4gtgt (a == b) | b == 3 returns ones at positions where a is equal to b or b is equal to 3gtgt any (a gt 5) returns 1 when ANY of the a elements are larger than 5gtgt any (b lt 5 amp a gt 8) returns 1 when there in the evaluated expressiongtgt (b lt 5 amp a gt 8) appears at least one 1gtgt all (b gt 2) returns 1 when ALL b elements are larger than 22rdquoequal tordquo in the table on page 88 of rdquoThe Student Edition of Matlabrdquo must be rdquo==rdquo instead of rdquo=rdquo2262 Conditional code executionSelection control structures if-blocks are used to decide which instruction to execute next depending whether117-119 expression is TRUE or not The general description is given below In the examples below the command dispis frequently used This command displays on the screen the text between the quotesbull if endSyntaxif logical_expressionstatement1statement2endExampleif (a gt 0)b = adisp (rsquoa is positiversquo)endbull if else endSyntaxif logical_expressionblock of statementsevaluated if TRUEelseblock of statementsevaluated if FALSEendExampleif (temperature gt 100)disp (rsquoAbove boilingrsquo)toohigh = 1elsedisp (rsquoTemperature is OKrsquo)toohigh = 0endbull if elseif else endSyntaxif logical_expression1block of statements evaluatedif logical_expression1 is TRUEelseif logical_expression2block of statements evaluatedif logical_expression2 is TRUEelseblock of statements evaluatedif no other expression is TRUEendExampleif (height gt 190)disp (rsquovery tallrsquo)elseif (height gt 170)disp (rsquotallrsquo)elseif (height lt 150)disp (rsquosmallrsquo)

elsedisp (rsquoaveragersquo)endRemark To do the exercises below a script m-file will be useful It is an external file that contains asequence of Matlab commands What you need to do is to open an editor enter all commands needed forthe solution of a task save it with the extension rsquomrsquo (eg mytaskm) and then run it from the CommandWindow by typing mytask To open the Matlab editor go to the File menu-bar choose the Open optionand then m-file A new window will appear where you can write your scripts and save them on the disk Allcommands in the script will be executed in Matlab You will learn more on script m-files in section 91Important m-script file must be saved in one of the directories in Matlabrsquos pathAn example A script shortm can be created from the two lines given below and run by calling shortx = 0054plot (x sin(x) rsquo-rsquo)Exercise 26Create a script that asks for a number N and computes the drag coefficient C depending on the Reynoldrsquos23number N (make use of the if elseif construction) The command input might be useful here(read pages 32-33 from rdquoThe Student Edition of Matlabrdquoor use help)C =8gtgtgtltgtgtgt0 N _ 024N N 2 (0 01]24N (1 + 014N07) N 2 (01 1e3]043 N 2 (1e3 5e5]019 minus 8e4N N gt 5e5Check whether your script works correctly Compute the drag coefficient for eg N = -3e3 001 56 1e3 3e6(remember that eg 3e3 is a Matlab notation of 3 _ 103) _Exercise 27Write a script that asks for an integer and checks whether it can be divided by 2 or 3 Consider all possibilitiessuch as divisible by both 2 and 3 divisible by 2 and not by 3 etc (use the command rem) _Another selection structure is switch which switches between several cases depending on an expression which119-120 is either a scalar or a stringSyntaxswitch expressioncase choice1block of commands1case choice2a choice2bblock of commands2otherwiseblock of commandsendExamplemethod = 2switch methodcase 12disp(rsquoMethod is linearrsquo)case 3disp(rsquoMethod is cubicrsquo)case 4disp(rsquoMethod is nearestrsquo)otherwisedisp(rsquoUnknown methodrsquo)endThe statements following the first case where the expression matches the choice are executed Thisconstruction can be very handy to avoid long if elseif else end constructions Theexpression can be a scalar or a string A scalar expression matches a choice if expression == choice Astring expression matches a choice if strcmp(expression choice) returns 1 (is true) (strcmp is a commandcomparing two strings)Important Note that the switch-construction only allows the execution of one group of commandsExercise 28Assume that the months are represented by numbers from 1 to 12 Write a script that asks you to provide a

month and returns the number of days in that particular month Alternatively write a script that asks youto provide a month name (eg rsquoJunersquo) instead of a number Use the switch-construction _63 LoopsIteration control structures loops are used to repeat a block of statements until some condition is met Two114-117 types of loops existbull the for loop that repeats a group of statements a fixed number of timesSyntaxfor index = firststeplastblock of statementsendExamplesumx = 0for i=1length(x)sumx = sumx + x(i)end24You can specify any step including a negative value The index of the for-loop can be also a vectorSee some examples of possible variationsExample 1for i=12nendExample 2for i=n-13endExample 3for x=0054disp(x^2)endExample 4for x=[25 9 81]disp(sqrt(x))endbull while loop which evaluates a group of commands as long as expression is TRUESyntaxwhile expressionstatement1statement2statement3endExampleN = 100iter = 1msum = 0while iter lt= Nmsum = msum + iteriter = iter + 1endExercise 29Given the vectors x and y write a script computing the a matrix whose elements should be created accordingto a formula given below (make use of the length command to check the number of elements in both vectors)- aij = yixj (make sure that a division by zero will not occur)- bij = xi _ yj

- cij = 1 max (xi yj)_Exercise 30Determine the sum of the first 50 squared numbers with a control loop _Exercise 31Write a script to find the largest value n such that the sum p13 + p23 + + pn3 is less than 1000 _optionalExercise 32Write a script that transposes a matrix A Check its correctness with the Matlab operation Arsquo _Exercise 33

Write a script that asks for a temperature in degrees Celsius tc and computes the equivalent temperature indegrees Fahrenheit tf (use the formula tf = 95 _ tc + 32) The script should keep running until no numberis provided to convert The functions input and isempty (use help to learn more) should be useful here _end optional

64 Evaluation of logical and relational expressions in the control flow structuresThe relational and logical expressions may become more complicated It is not difficult to operate on them ifyou understand how they are evaluated To explain more details let us consider the following exampleif (~isempty(data)) amp (max(data) lt 5)endThis construction of the if-block is necessary to avoid comparison if data happens to be an empty matrix Insuch a case you cannot evaluate any expression and Matlab gives an error The amp operator returns 1 only ifboth expressions ~isempty (data) and max(data) lt 5 are true and 0 otherwise When data is an emptymatrix the next expression is not evaluated since the whole amp-expression is already known to be false Thesecond expression is checked only if data is a non-empty matrix Remember to put logical expression unitsbetween brackets to avoid wrong evaluations25Important The fact that computers make use of floating-point arithmetic means that often you should becareful when comparing two floating-point numbers just byif (x == y)end(Of course such a construction is allowed eg when you know that x and y represent integers) Instead of theabove construction you may try using thisif (abs (x - y) lt tolerance) eg tolerance = 1e-10endExercise 34Consider the following examplemax_iter = 50tolerance = 1e-4iter = 0xold = 01x = 1while (abs (x - xold) gt tolerance) amp (iter lt max_iter)xold = xx = cos(xold)iter = iter + 1endThis short program tries to solve the equation cos(x) = x (x is the solution found) Make the script solve cosfrom the presented code Note that the while-loop is repeated as long as both conditions are true If eitherthe condition (|x - xold| lt= tolerance) or (iter gt= max iter) is fulfilled then the loop is quitted Runthe script solve cos for different tolerance parameters eg 1e-3 1e-6 1e-8 1e-10 etc Use format long tocheck more precisely how much the found x is really different from cos(x) For each tolerance value checkthe number of performed iterations (iter value) _Exercise 35Create the script solve cos2 which is equal to the one given replacing the while-loop condition bywhile (abs (x - xold) gt tolerance) | (iter lt max_iter)Try to understand the difference and confirm your expectations by running solve cos2 What happens toiter _optional

65 Numerical analysis and the control flow structuresTake a look at the problem of a Taylor expansion The series will be determined numerically until the additionalterms are smaller than a defined precision Look at the Taylor expansion of 11minusx = 1 + x + x2 + withx = 042s = 0 x = 1 s = 0 x = 1x0 = 042 x0 = 042while (x gt 1e-6) or while (x gt (1e-6)s)s = s + x s = s + xx = x x0 x = x x0end endThe approximation of 11minusx is returned in s (first letter of sum) In the first case (on the left) the iteration

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 22: Introduction to Programming Using Matlab

elsedisp (rsquoaveragersquo)endRemark To do the exercises below a script m-file will be useful It is an external file that contains asequence of Matlab commands What you need to do is to open an editor enter all commands needed forthe solution of a task save it with the extension rsquomrsquo (eg mytaskm) and then run it from the CommandWindow by typing mytask To open the Matlab editor go to the File menu-bar choose the Open optionand then m-file A new window will appear where you can write your scripts and save them on the disk Allcommands in the script will be executed in Matlab You will learn more on script m-files in section 91Important m-script file must be saved in one of the directories in Matlabrsquos pathAn example A script shortm can be created from the two lines given below and run by calling shortx = 0054plot (x sin(x) rsquo-rsquo)Exercise 26Create a script that asks for a number N and computes the drag coefficient C depending on the Reynoldrsquos23number N (make use of the if elseif construction) The command input might be useful here(read pages 32-33 from rdquoThe Student Edition of Matlabrdquoor use help)C =8gtgtgtltgtgtgt0 N _ 024N N 2 (0 01]24N (1 + 014N07) N 2 (01 1e3]043 N 2 (1e3 5e5]019 minus 8e4N N gt 5e5Check whether your script works correctly Compute the drag coefficient for eg N = -3e3 001 56 1e3 3e6(remember that eg 3e3 is a Matlab notation of 3 _ 103) _Exercise 27Write a script that asks for an integer and checks whether it can be divided by 2 or 3 Consider all possibilitiessuch as divisible by both 2 and 3 divisible by 2 and not by 3 etc (use the command rem) _Another selection structure is switch which switches between several cases depending on an expression which119-120 is either a scalar or a stringSyntaxswitch expressioncase choice1block of commands1case choice2a choice2bblock of commands2otherwiseblock of commandsendExamplemethod = 2switch methodcase 12disp(rsquoMethod is linearrsquo)case 3disp(rsquoMethod is cubicrsquo)case 4disp(rsquoMethod is nearestrsquo)otherwisedisp(rsquoUnknown methodrsquo)endThe statements following the first case where the expression matches the choice are executed Thisconstruction can be very handy to avoid long if elseif else end constructions Theexpression can be a scalar or a string A scalar expression matches a choice if expression == choice Astring expression matches a choice if strcmp(expression choice) returns 1 (is true) (strcmp is a commandcomparing two strings)Important Note that the switch-construction only allows the execution of one group of commandsExercise 28Assume that the months are represented by numbers from 1 to 12 Write a script that asks you to provide a

month and returns the number of days in that particular month Alternatively write a script that asks youto provide a month name (eg rsquoJunersquo) instead of a number Use the switch-construction _63 LoopsIteration control structures loops are used to repeat a block of statements until some condition is met Two114-117 types of loops existbull the for loop that repeats a group of statements a fixed number of timesSyntaxfor index = firststeplastblock of statementsendExamplesumx = 0for i=1length(x)sumx = sumx + x(i)end24You can specify any step including a negative value The index of the for-loop can be also a vectorSee some examples of possible variationsExample 1for i=12nendExample 2for i=n-13endExample 3for x=0054disp(x^2)endExample 4for x=[25 9 81]disp(sqrt(x))endbull while loop which evaluates a group of commands as long as expression is TRUESyntaxwhile expressionstatement1statement2statement3endExampleN = 100iter = 1msum = 0while iter lt= Nmsum = msum + iteriter = iter + 1endExercise 29Given the vectors x and y write a script computing the a matrix whose elements should be created accordingto a formula given below (make use of the length command to check the number of elements in both vectors)- aij = yixj (make sure that a division by zero will not occur)- bij = xi _ yj

- cij = 1 max (xi yj)_Exercise 30Determine the sum of the first 50 squared numbers with a control loop _Exercise 31Write a script to find the largest value n such that the sum p13 + p23 + + pn3 is less than 1000 _optionalExercise 32Write a script that transposes a matrix A Check its correctness with the Matlab operation Arsquo _Exercise 33

Write a script that asks for a temperature in degrees Celsius tc and computes the equivalent temperature indegrees Fahrenheit tf (use the formula tf = 95 _ tc + 32) The script should keep running until no numberis provided to convert The functions input and isempty (use help to learn more) should be useful here _end optional

64 Evaluation of logical and relational expressions in the control flow structuresThe relational and logical expressions may become more complicated It is not difficult to operate on them ifyou understand how they are evaluated To explain more details let us consider the following exampleif (~isempty(data)) amp (max(data) lt 5)endThis construction of the if-block is necessary to avoid comparison if data happens to be an empty matrix Insuch a case you cannot evaluate any expression and Matlab gives an error The amp operator returns 1 only ifboth expressions ~isempty (data) and max(data) lt 5 are true and 0 otherwise When data is an emptymatrix the next expression is not evaluated since the whole amp-expression is already known to be false Thesecond expression is checked only if data is a non-empty matrix Remember to put logical expression unitsbetween brackets to avoid wrong evaluations25Important The fact that computers make use of floating-point arithmetic means that often you should becareful when comparing two floating-point numbers just byif (x == y)end(Of course such a construction is allowed eg when you know that x and y represent integers) Instead of theabove construction you may try using thisif (abs (x - y) lt tolerance) eg tolerance = 1e-10endExercise 34Consider the following examplemax_iter = 50tolerance = 1e-4iter = 0xold = 01x = 1while (abs (x - xold) gt tolerance) amp (iter lt max_iter)xold = xx = cos(xold)iter = iter + 1endThis short program tries to solve the equation cos(x) = x (x is the solution found) Make the script solve cosfrom the presented code Note that the while-loop is repeated as long as both conditions are true If eitherthe condition (|x - xold| lt= tolerance) or (iter gt= max iter) is fulfilled then the loop is quitted Runthe script solve cos for different tolerance parameters eg 1e-3 1e-6 1e-8 1e-10 etc Use format long tocheck more precisely how much the found x is really different from cos(x) For each tolerance value checkthe number of performed iterations (iter value) _Exercise 35Create the script solve cos2 which is equal to the one given replacing the while-loop condition bywhile (abs (x - xold) gt tolerance) | (iter lt max_iter)Try to understand the difference and confirm your expectations by running solve cos2 What happens toiter _optional

65 Numerical analysis and the control flow structuresTake a look at the problem of a Taylor expansion The series will be determined numerically until the additionalterms are smaller than a defined precision Look at the Taylor expansion of 11minusx = 1 + x + x2 + withx = 042s = 0 x = 1 s = 0 x = 1x0 = 042 x0 = 042while (x gt 1e-6) or while (x gt (1e-6)s)s = s + x s = s + xx = x x0 x = x x0end endThe approximation of 11minusx is returned in s (first letter of sum) In the first case (on the left) the iteration

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 23: Introduction to Programming Using Matlab

month and returns the number of days in that particular month Alternatively write a script that asks youto provide a month name (eg rsquoJunersquo) instead of a number Use the switch-construction _63 LoopsIteration control structures loops are used to repeat a block of statements until some condition is met Two114-117 types of loops existbull the for loop that repeats a group of statements a fixed number of timesSyntaxfor index = firststeplastblock of statementsendExamplesumx = 0for i=1length(x)sumx = sumx + x(i)end24You can specify any step including a negative value The index of the for-loop can be also a vectorSee some examples of possible variationsExample 1for i=12nendExample 2for i=n-13endExample 3for x=0054disp(x^2)endExample 4for x=[25 9 81]disp(sqrt(x))endbull while loop which evaluates a group of commands as long as expression is TRUESyntaxwhile expressionstatement1statement2statement3endExampleN = 100iter = 1msum = 0while iter lt= Nmsum = msum + iteriter = iter + 1endExercise 29Given the vectors x and y write a script computing the a matrix whose elements should be created accordingto a formula given below (make use of the length command to check the number of elements in both vectors)- aij = yixj (make sure that a division by zero will not occur)- bij = xi _ yj

- cij = 1 max (xi yj)_Exercise 30Determine the sum of the first 50 squared numbers with a control loop _Exercise 31Write a script to find the largest value n such that the sum p13 + p23 + + pn3 is less than 1000 _optionalExercise 32Write a script that transposes a matrix A Check its correctness with the Matlab operation Arsquo _Exercise 33

Write a script that asks for a temperature in degrees Celsius tc and computes the equivalent temperature indegrees Fahrenheit tf (use the formula tf = 95 _ tc + 32) The script should keep running until no numberis provided to convert The functions input and isempty (use help to learn more) should be useful here _end optional

64 Evaluation of logical and relational expressions in the control flow structuresThe relational and logical expressions may become more complicated It is not difficult to operate on them ifyou understand how they are evaluated To explain more details let us consider the following exampleif (~isempty(data)) amp (max(data) lt 5)endThis construction of the if-block is necessary to avoid comparison if data happens to be an empty matrix Insuch a case you cannot evaluate any expression and Matlab gives an error The amp operator returns 1 only ifboth expressions ~isempty (data) and max(data) lt 5 are true and 0 otherwise When data is an emptymatrix the next expression is not evaluated since the whole amp-expression is already known to be false Thesecond expression is checked only if data is a non-empty matrix Remember to put logical expression unitsbetween brackets to avoid wrong evaluations25Important The fact that computers make use of floating-point arithmetic means that often you should becareful when comparing two floating-point numbers just byif (x == y)end(Of course such a construction is allowed eg when you know that x and y represent integers) Instead of theabove construction you may try using thisif (abs (x - y) lt tolerance) eg tolerance = 1e-10endExercise 34Consider the following examplemax_iter = 50tolerance = 1e-4iter = 0xold = 01x = 1while (abs (x - xold) gt tolerance) amp (iter lt max_iter)xold = xx = cos(xold)iter = iter + 1endThis short program tries to solve the equation cos(x) = x (x is the solution found) Make the script solve cosfrom the presented code Note that the while-loop is repeated as long as both conditions are true If eitherthe condition (|x - xold| lt= tolerance) or (iter gt= max iter) is fulfilled then the loop is quitted Runthe script solve cos for different tolerance parameters eg 1e-3 1e-6 1e-8 1e-10 etc Use format long tocheck more precisely how much the found x is really different from cos(x) For each tolerance value checkthe number of performed iterations (iter value) _Exercise 35Create the script solve cos2 which is equal to the one given replacing the while-loop condition bywhile (abs (x - xold) gt tolerance) | (iter lt max_iter)Try to understand the difference and confirm your expectations by running solve cos2 What happens toiter _optional

65 Numerical analysis and the control flow structuresTake a look at the problem of a Taylor expansion The series will be determined numerically until the additionalterms are smaller than a defined precision Look at the Taylor expansion of 11minusx = 1 + x + x2 + withx = 042s = 0 x = 1 s = 0 x = 1x0 = 042 x0 = 042while (x gt 1e-6) or while (x gt (1e-6)s)s = s + x s = s + xx = x x0 x = x x0end endThe approximation of 11minusx is returned in s (first letter of sum) In the first case (on the left) the iteration

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 24: Introduction to Programming Using Matlab

Write a script that asks for a temperature in degrees Celsius tc and computes the equivalent temperature indegrees Fahrenheit tf (use the formula tf = 95 _ tc + 32) The script should keep running until no numberis provided to convert The functions input and isempty (use help to learn more) should be useful here _end optional

64 Evaluation of logical and relational expressions in the control flow structuresThe relational and logical expressions may become more complicated It is not difficult to operate on them ifyou understand how they are evaluated To explain more details let us consider the following exampleif (~isempty(data)) amp (max(data) lt 5)endThis construction of the if-block is necessary to avoid comparison if data happens to be an empty matrix Insuch a case you cannot evaluate any expression and Matlab gives an error The amp operator returns 1 only ifboth expressions ~isempty (data) and max(data) lt 5 are true and 0 otherwise When data is an emptymatrix the next expression is not evaluated since the whole amp-expression is already known to be false Thesecond expression is checked only if data is a non-empty matrix Remember to put logical expression unitsbetween brackets to avoid wrong evaluations25Important The fact that computers make use of floating-point arithmetic means that often you should becareful when comparing two floating-point numbers just byif (x == y)end(Of course such a construction is allowed eg when you know that x and y represent integers) Instead of theabove construction you may try using thisif (abs (x - y) lt tolerance) eg tolerance = 1e-10endExercise 34Consider the following examplemax_iter = 50tolerance = 1e-4iter = 0xold = 01x = 1while (abs (x - xold) gt tolerance) amp (iter lt max_iter)xold = xx = cos(xold)iter = iter + 1endThis short program tries to solve the equation cos(x) = x (x is the solution found) Make the script solve cosfrom the presented code Note that the while-loop is repeated as long as both conditions are true If eitherthe condition (|x - xold| lt= tolerance) or (iter gt= max iter) is fulfilled then the loop is quitted Runthe script solve cos for different tolerance parameters eg 1e-3 1e-6 1e-8 1e-10 etc Use format long tocheck more precisely how much the found x is really different from cos(x) For each tolerance value checkthe number of performed iterations (iter value) _Exercise 35Create the script solve cos2 which is equal to the one given replacing the while-loop condition bywhile (abs (x - xold) gt tolerance) | (iter lt max_iter)Try to understand the difference and confirm your expectations by running solve cos2 What happens toiter _optional

65 Numerical analysis and the control flow structuresTake a look at the problem of a Taylor expansion The series will be determined numerically until the additionalterms are smaller than a defined precision Look at the Taylor expansion of 11minusx = 1 + x + x2 + withx = 042s = 0 x = 1 s = 0 x = 1x0 = 042 x0 = 042while (x gt 1e-6) or while (x gt (1e-6)s)s = s + x s = s + xx = x x0 x = x x0end endThe approximation of 11minusx is returned in s (first letter of sum) In the first case (on the left) the iteration

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 25: Introduction to Programming Using Matlab

process is stopped as soon as the next term t is smaller than an absolute value of 1e-6 In the other case thisvalue is relative to the outcome26Exercise 36Find the Taylor expansion of 11minusx and sin(x) = xminus x3

3 + x5

5 minus with the absolute precision of 1e-5 for x = 04and x = minus04 _It is also possible to determine the Taylor expansion of 11minusx = 1 + x + x2 + with 30 terms (x = 042)s = 1 x = 1 s = 1 x = 1 x0 = 042x0 = 042 n1 = 1 n2 = 30n = 30 step = 1for k = 1n for k = n1stepn2x = x x0 or x = x x0s = s + x s = s + xend endshowing that the index k can be indicated with a starting point step size and end pointend optional

7 Text71 Character stringsAlthough Matlab mainly works with numbers it might occasionally be necessary to operate on text Text94-99 is saved as a character string The string is a vector of ASCII values which are displayed as their characterstring representation Since text is a vector of characters it can be adressed in the same way as any vectorAn examplegtgt t = rsquoThis is a character stringrsquot =This is a character stringgtgt size (t)ans =1 27gtgt whosName Size Bytes Classt 1x27 54 char arraygtgt t(1019)ans =charactergtgt t([231017])ans =hi tTo see the underlying ASCII representation the string has to be converted using the command double or absgtgt double (t(112))ans =84 104 105 115 32 105 115 32 97 32 99 104The function char provides the reverse transformationgtgt t([1617])ans =ctgtgt t([1617])+3 to perform a mathematical operation ASCII codes are usedans =102 119gtgt t([1617])-3 ASCII codes againans =96 113gtgt char(t([1617])-2) transform ASCII codes to characters27ans =arExercise 37Perform the described commands Use string t to form a new string u that contains the word rdquocharacterrdquoonly Convert string u to form the same word spelled backwards ie u1 = retcarahc _The tables on page 97 and 98 of rdquoThe Student Edition of Matlabrdquo book give an overview of string conversionsand functions With eg findstr a string can be searched for a character or the start of a combination of

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 26: Introduction to Programming Using Matlab

characters Such an example with a few other examples on the use of different string functions is given belowgtgt findstr (t rsquocrsquo) finds a character rsquocrsquo in string t positions are returnedans =11 16gtgt findstr (t rsquoracterrsquo) finds the beginning of a string rsquoracterrsquo in tans =14gtgt findstr(tu) finds string u in string t returns the positionans =11gtgt strcat(uu1) concatenates multiple strings u and u1ans =characterretcarahcgtgt strcmp(uu1) comparison of two stringsans = 1 for identical strings 0 for different strings0gtgt q = num2str(3435) converts a number into a stringq =3435gtgt z = str2num(rsquo76rsquo) converts a string into a numberz =76gtgt whos q z q is now a string ie a character array z is a numberName Size Bytes Classq 1x5 10 char arrayz 1x1 8 double arrayExercise 38Perform the commands shown in the example above Define another string eg s = rsquoNothing wastes moreenergy then worryingrsquo and exercise with findstr Become familiar with num2str and str2num commandsCheck eg what happens with ss = num2str ([1 2 3 4 5 6]) or q = str2num(rsquo1 325 5 55rsquo) _72 Text input and outputThe input command can be used to prompt (ask) the user for numeric or string input31-33gtgt myname = input(rsquoEnter you name rsquorsquosrsquo)gtgt age = input(rsquoEnter your age rsquo)You will learn in section 92 that inputs can be passed on to functions This is a recommended approachsince using the input command for more complex programs makes automatic computation impossibleThere are two common text output functions disp and fprintf The disp function only displays the valueof one parameter either a numerical array or a string (the recognition is done automatically) For examplegtgt disp(rsquoThis is a statementrsquo) a stringThis is a statementgtgt disp(rand(3)) a matrix02221 00129 0851904885 00538 0503902290 03949 0423928The fprintf function (familiar to C programmers) is useful for writing data to a file (see section 111) or97 printing on screen when precise formatting is important Try for instance (an explanation will follow)gtgt x = 2gtgt fprintf(rsquoSquare root of g is 86fnrsquo x sqrt(x))Square root of 2 is 1414214gtgt str = rsquobeginningrsquogtgt fprintf(rsquoEvery s is difficultnrsquostr)Every beginning is difficultFormally fprintf converts formats and prints its arguments to a file or displays them on screen accordingto a format specification For displaying on screen the following syntax is usedfprintf (formata)The format string contains ordinary characters which are copied to the output and conversion specificationseach of which converts and prints the next successive argument to fprintf Each conversion specification isintroduced by the character rsquorsquo and ended by a conversion character Between the rsquorsquo and the conversioncharacter there may appear- a minus sign controlling the alignment within the field defined- a digit string specifying a minimum field length The converted number will be printed in a field at leastthis wide and wider if necessary- a period which separates the field width from the next digit string

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 27: Introduction to Programming Using Matlab

- a digit string - the precision which specifies the maximum number of characters to be printed from astring or the number of digits printed after decimal point of a single or double typeFormat specification is given below in terms of the conversion characters and their meaningsThe argumentd is converted into decimal notationu is converted into unsigned decimal notationc is taken to be a single characters is a stringe is taken to be a single or double and converted into decimal notation ofthe form [-]mnnnnnnE[plusmn]xx where the length of nrsquos is specified by the precisionf is taken to be a single or double and converted into decimal notation ofthe form[-]mmmnnnnn where the length of nrsquos is specified by the precisiong is specified by e or f whichever is shorter non-significant zeros are not printedThe special formats n r t b can be used to produce next line (ie makes sure that the next commandor output will be written on the next line) carriage return tab and backspace respectively Use to producea backslash character and to produce the percent characterAnalyze the following examplegtgt fprintf (rsquolook at 206enrsquo 1000sqrt(2))look at 1414214e+3gtgt fprintf (rsquolook at -206frsquo 1000sqrt(2))look at 1414213562 gtgtFor both commands the minimum field length is 20 the number of digits after the decimal point is 6 In thefirst case the value of 1000 _ p(2) is padded on the right in the second because of the - on the left Thedifference in the presentation of the value of 1000 _p(2) is caused by the conversion characters e and fExercise 39Try to exercise to understand how to use the input disp and fprintf commands For instance try to reada vector with real numbers using input Then try to display this vector both by calling disp and formattingan output by fprintf Make a few variations Try the same with a string _Exercise 40Study the following examples in order to become familiar with the fprintf possibilities and exercise yourselfto understand how to use these specifications29gtgt str = rsquolife is beautifulrsquogtgt fprintf(rsquoMy sentence is snrsquostr) note the n formatMy sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 30snrsquostr)My sentence is life is beautifulgtgt fprintf(rsquoMy sentence is 3010snrsquostr)My sentence is life is begtgt fprintf(rsquoMy sentence is -2010snrsquostr)My sentence is life is begtgtgtgt name = rsquoJohnrsquogtgt age = 30gtgt salary = 613050gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquoname age salary)gtgt My name is John I am 30 My salary is f 613050gtgtgtgt x = [0 05 1]gtgt y = [x exp(x)]gtgt fprintf(rsquo62f 128fnrsquoy)000 100000000050 164872127100 271828183gtgt fprintf(rsquo61e 124enrsquoy)00e+00 10000e+0050e-01 16487e+0010e+00 27183e+00gtgtgtgt x = 137gtgt y = [x sin(x)]gtgt fprintf(rsquo2d 104gnrsquoy)1 084154 -075687 0657

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 28: Introduction to Programming Using Matlab

_Warning fprintf uses its first argument to decide how many arguments follow and what their types areIf you provide a wrong type or there are not enough arguments you will get nonsense for an answers Sobe careful with formatting your output Look for instance what happens in the following case (age is notprovided)gtgt fprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonamesalary)My name is John I am 6130500e+03 My salary is f gtgtRemark The function sprintf is related to fprintf but writes to a string instead Analyze the examplegtgt str = sprintf(rsquoMy name is 4s I am 2d My salary is f 72fnrsquonameagesalary)str =My name is John I am 30 My salary is f 650050optional

8 Cell arrays and structures81 Cell arraysCell arrays are arrays whose elements are cells Each cell can contain any data including numeric arrays239-24599-102strings cell arrays etc For instance one cell can contain a string another a numeric array etc Below thereis a schematic representation of an exemplar cell array30rsquothis is a textrsquo-1 00 -1355900 6000 6100John Smithrsquoimplies effortrsquorsquoLivingrsquo1 + 3icell 22rsquoByersquorsquoHirsquo [77]3 1 -77 2 40 -1 67 3 7cell 11 cell 12 cell 13cell 21 cell 23

Cell arrays can be built up by assigning data to each cell The cell contents are accessed by brackets Forexamplegtgt A(11) = [3 1 -77 2 40 -1 67 3 7]gtgt A(21) = rsquothis is a textrsquogtgt B(11) = rsquoJohn Smithrsquo B(21) = 35 B(31) = [5900 6000 6100]gtgt A(12) = B cell array B becomes one of the cells of Agtgt C(11) = rsquoHirsquo C(21) = [-1 00 -1] C(12) = [77] C(22) = rsquoByersquogtgt A(22) = C cell array C becomes one of the cells of Agtgt A A represents now the first 2 columns of the exemplar cell arrayA =[4x3 double] 3x1 cellrsquothis is a textrsquo 2x2 cellgtgt A(22) access the cell but not its contentsans =2x2 cellgtgt A22 use to display the contentsans =rsquoHirsquo [1x2 double][2x2 double] rsquoByersquogtgt A2221 take the (21) element of the cell A22ans =-1 00 -1There exist two useful functions with meaningful names celldisp and cellplot If you are interested findout more via help or in rdquoThe Student Edition of Matlabrdquo on page 241The common application of cell arrays is the creation of text arrays Consider the following examplegtgt M = rsquoJanuaryrsquorsquoFebruaryrsquorsquoMarchrsquorsquoAprilrsquorsquoMayrsquorsquoJunersquorsquoJulyrsquorsquoAugustrsquorsquoSeptemberrsquorsquoOctoberrsquorsquoNovemberrsquorsquoDecemberrsquogtgt fprintf (rsquoIt is snrsquo M9)It is SeptemberExercise 41

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 29: Introduction to Programming Using Matlab

Exercise with the concept of a cell array first by typing the examples presented above Next create a cellarray W with the names of week days and using the command fprintf display on screen the current datewith the day of the week The goal of this exercise is also to use fprintf with a format for a day name and adate in the spirit of the above example _82 StructuresStructures are Matlab arrays with data objects composed of fields Each field contains one item of informa-245-249 tion For example one field might include a string representing a name another a scalar representing age oran array of the last few salaries Structures are especially useful for creating and handling a database One31of the possible ways to create a structure is by assigning data to individual fields Imagine that you want toconstruct a database with some information on workers of a companygtgt workername = rsquoJohn Smithrsquogtgt workerage = 35gtgt workersalary = [5900 6000 6100]gtgt worker =name rsquoJohn Smithrsquoage 35salary [5900 6000 6100]In this way a 1times1 structure array worker with three fields name age and salary is constructed To expandthe structure add a subscript after the structure namegtgt worker(2)name = rsquoLinda Murphyrsquo after this a 2nd subarray is createdgtgt worker(2)age = 41gtgt worker(2)salary = [7301 7301] field sizes do not need to matchgtgt worker1x2 struct array with fieldsnameagesalarySince the structure has now size 1 times 2 Matlab does not display contents of all fields The data is noworganized as followsworker arrayworker(1)name John Smithage 35salary5900 6000 6100worker(2)name Linda Murphyage 41salary7301 7301

Structures can also be build by using the struct function for examplegtgt employee=struct( rsquonamersquorsquoJohn Smithrsquorsquoagersquo35rsquosalaryrsquo[5900 6000 6100])To access an entire field include a field name after a period To access a subarray follow the standard way ofusing subscriptsgtgt worker(1)age35gtgt worker(2)salary(2)7301gtgt worker(2)name rsquoLinda Murphyrsquoage 41salary [7301 7301]An alternative way is to use the getfield functiongtgt getfield(worker2rsquosalaryrsquo)7301 730132There exist also the function setfield which allows assigning values (if you are interested read more on page248 in rdquoThe Student Edition of Matlabrdquo book)New fields can be added or deleted from every structure To delete a field use the command rmfield Analyzethe following examplegtgt worker2 = workergtgt worker2 = rmfield (worker rsquoagersquo)gtgt worker2(2)street = rsquoBakerstreet 5rsquogtgt worker2(2)name rsquoLinda Murphyrsquosalary [7301 7301]

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 30: Introduction to Programming Using Matlab

street rsquoBakerstreet 5rsquogtgt worker2(1)name rsquoJohn Smithrsquosalary [5900 6000 6100] in all other substructures address field is emptystreet [] you should assign new values for each substructureOperating on fields and field elements is done in the same way as on any other array Consider the followingexample where the average salary for each worker is computedavr_salary(1) = mean (worker(1)salary)avr_salary(2) = mean (worker(2)salary)Remark structures as a concept are common organizations of data in other programming languages Theyare created in different ways but the intention remains the sameExercise 42Construct a structure friend with the following fields name address age birthday Insert a few friendswith related information Remove eg the field age and add the field phone _end optional

9 Script and function m-files91 Script m-filesMatlab commands can be entered at the Matlab prompt When a problem is more complicated this becomes29-33 inefficient A solution is using script m-files They are useful when the number of commands increases or whenyou want to change values of some variables and re-evaluate them quickly Formally a script is an external filethat contains a sequence of Matlab commands (statements) However it is not a function since there areno inputoutput parameters and the script variables remain in the workspace So when you run a scriptthe commands in it are executed as if they have been entered through the keyboardExercise 43Create yourself a script open the Matlab editor (go to the File menu-bar choose the Open option andthen m-file the Matlab Editor Window will appear) enter the lines listed below and save as sinplotmx = 0026y = sin(x)plot (xy)title (rsquoPlot of y = sin(x)rsquo)and then run it bygtgt sinplotThe sinplot script affects the workspace Checkgtgt clear all variables are removed from the workspacegtgt who no variables presentgtgt sinplotgtgt whoYour variables arex y33_These generic names x and y may be easily used in further computations and this can cause side effects Sideeffects occur in general when a set of commands change variables other than the input arguments Since scriptscreate and change variables in the workspace (without warning) a bug hard to track down may easily appearSo it is important to remember that the commands within a script have access to all variables in theworkspace and all variables created in this script become a part of the workspace Therefore itis better to use function m-files (see section 92) when there is a specific problem to be solvedExercise 44Create yourself a script plotting the function y = 2cos(x) at the range [minus10 10] Choose a sufficient length forx in order to obtain a smooth plot _optionalThe diary command can be also useful when creating scripts diary on begins saving the text that is enteredand displayed in the Command Window into a file called diary Another name can be used alternatively whenit is provided instead of on and after the diary diary off stops the saving procedureExercise 45Check yourself the followinggtgt diary myplotmgtgt x = 0026gtgt y = sin(x)gtgt z = x y

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 31: Introduction to Programming Using Matlab

Error using ==gt Inner matrix dimensions must agreegtgt z = x y correctiongtgt plot (xz)gtgt title (rsquoPlot of y = x sin(x)rsquo)gtgt diary offNote that before running myplot its contents must be edited by removing the gtgt signs and the error note _end optionalExercise 46Write a script that for given a b and c returns the roots of the cubic equation a x2 + b x + c = 0 _92 Function m-fileFunctions m-files are true subprograms since they take input arguments andor return output parameters126-134 They can call other functions as well Variables defined and used inside a function different from the inputoutput arguments are invisible to other functions and the command environment The general syntax ofa function is presented belowfunction [outputArgs] = function_name (inputArgs)outputArgs are enclosed in [ ]ndash a comma-separated list of variable namesndash [ ] is optional when only one argument is presentndash functions without outputArgs are legal 3inputArgs are enclosed in ( )ndash a comma-separated list of variable namesndash functions without inputArgs are legalMatlab provides a structure for creating your own functions The first line of the file should be a definition ofa new function (also called a header) After that a continuous sequence of comment lines should appear Theirgoal is to explain what the function does especially when this is not trivial Not only a general description3in other programming languages functions without output arguments are called procedures34but also the expected input parameters returned output parameters and synopsis should appear there Thecomment lines (counted up to the first non-comment line) are important since they are displayed in responseto the help command Finally the remainder of the function is called the body Function m-files terminateexecution and return when they reached the end of the file or alternatively when the command return isencountered As an example the function average is defined as followsinput argumentthe first line must bethe function definitionhelp averagea blank line within the commentNotes information will NOT appearwhen you askAVERAGE computes the average value of a vector xfunction avr = average (x)output argument function namecomment and returns it in avr Notes an example of a functionn = length(x)avr = sum(x)nreturnfunction bodyImportant The name of the function and the name of the file stored on disk should be identical In ourcase the function should be stored in a file called averagemExercise 47Create the function average and store it on disk as averagem Remember about the comment lines Checkits usability by calling help average Run averagem by typing avr1 = average(110) _Here is an another example of a functionfunction [avrsd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)avr = sum(x)nsd = sqrt(sum((x - avr)^2)n)returnWarning The functions mean and std already exist in Matlab As long as a function name is used asvariable name Matlab can not perform the function Many other easily appealing names such as sum or

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 32: Introduction to Programming Using Matlab

prod are reserved by Matlab functions so be careful when choosing your names (see section 123)The return statement can be used to force an early return An exemplary use of the return is given belowfunction d = determinant(A)DETERMINANT Computes the determinant of a matrix A[mn] = size(A)if (m ~= n)disp (rsquoError Matrix should be squarersquo)returnelsed = det(A) standard Matlab functionendreturnAnalyze the use of the return command in the function checkarg which is presented in section 921 as wellExercise 48Create the function randint that randomly generates a matrix of integer numbers (use the command rand)These integers should come from the interval [a b] Exercise in documenting the function Use the followingfunction headerfunction r = randint(mnab) a m-by-n matrixIf this seems too difficult start first with the fixed interval eg [a b] = [0 5] (and remove a and b from thefunction definition) and then try to make it work for an arbitrary interval _When controlling the proper use of parameters the function error may become useful It displays an error129 message aborts function execution and returns to the command environment Here is an example35if (a gt= 1)error (rsquoa must be smaller than 1rsquo)endExercise 49The area of a triangle with sides of length a b and c is given by A = ps (s minus a) (s minus b) (s minus c) wheres = (a + b + c)2 Write a function that accepts a b and c as inputs and returns the value A as outputNote that the sides should be non-negative and should fulfill the triangle inequality Make use of the errorcommand Document the function _Exercise 50Change some scripts that you created into functions eg create the function drag computing the dragcoefficient (see Exercise 26) or solve cos (see Exercise 34) or cubic roots (see Exercise 46) _optionalA function m-file may contain more than one function The function appearing first in the m-file shares the filename as mentioned before Other functions are subfunctions and can be called from the primary function onlySo they cannot be accessed outside the file in which they are defined (neither from the Command Windownor via other m-files) A subfunction is created by defining a new function with the function statement afterthe body of the preceding function The use of subfunctions is recommended to keep the function readablewhen it becomes too long and too complicated For example average is now a subfunction within the filestatmfunction [asd] = stat(x)STAT Simple statistics Computes the average value and the standard deviation of a vector xn = length(x)a = average(xn)sd = sqrt(sum((x - avr)^2)n)returnfunction a = average (xn)AVERAGE subfunctiona = sum(x)nreturnend optional921 Special function variablesEach function has two internal variables nargin - the number of function input arguments that were used tocall the function and nargout - the number of output arguments Analyze the following functionfunction [out1out2] = checkarg (in1in2in3)CHECKARG Demo on using the nargin and nargout variablesif (nargin == 0)disp(rsquono input argumentsrsquo)returnelseif (nargin == 1)s = in1

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 33: Introduction to Programming Using Matlab

p = in1disp(rsquo1 input argumentrsquo)elseif (nargin == 2)s = in1+in2p = in1in2disp(rsquo2 input argumentsrsquo)elseif (nargin == 3)s = in1+in2+in3p = in1in2in3disp(rsquo3 input argumentsrsquo)else36error(rsquoToo many inputsrsquo)endif (nargout == 0)returnelseif (nargout == 1)out1 = selseout1 = sout2 = pendExercise 51Construct the function checkarg call it with different number of input and output arguments and try tounderstand its behavior For examplegtgt checkarggtgt s = checkarg(-6)gtgt s = checkarg(237)gtgt [sp] = checkarg(345)_922 Local and global variablesEach m-file function has access to a part of memory separate from Matlabrsquos workspace This is called thefunction workspace This means that each m-file function has its own local variables which are separate fromthose of other function and from the workspace To understand it better analyze the following diagramMatlab workspacegtgt a = -1gtgt b = 20gtgt c = myfun (ab)(a b) minus (x y)c minus zmyfunmfunction z = myfun (xy)z = x + cos(x-y)returnIn the Matlab workspace variables a b and c are available Variables x y and z are visible only in thefunction myfun However if several functions andor the workspace all declare a particular variable as globalthen they all share this variable (see help global) Any assignment to that variable is available to all otherfunctions andor the workspace However you should be careful when using global variables It is very easyto get confused and end up with serious errorsoptional923 Indirect function evaluationUsing indirect function evaluation makes programming even more general since functions can become inputarguments The crucial Matlab command here is feval an abbreviation of function evaluation The fevalcommand allows execution of a function specified by a string The general definition is as follows[y1yn] = feval (Fx1xn)where F is a name of a function defined in Matlab x1xn are input arguments and y1yn arepossible output parameters Consider an examplegtgt x = pigtgt y = cos(x)gtgt z = feval(rsquocosrsquox)The last command is also equivalent to the following two expressionsgtgt F = rsquocosrsquogtgt z = feval(Fx)37

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 34: Introduction to Programming Using Matlab

Indirect function evaluation is a nice tool to build a program with a function given as an argumentExercise 52Create the function funplot and try to understand how it worksfunction funplot (F xstart xend col)FUNPLOT makes a plot of the function F at the interval [xstart xend] The plot should be made in one of the standard Matlab colors so rsquocolrsquo is one of the following value rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquo or rsquorrsquo default values [xstartxend] = [010] col = rsquobrsquo Note illustrates the use of feval commandif (nargin == 0)error (rsquoNo function is providedrsquo)endif (nargin lt 2)xstart = 0xend = 10endif (nargin == 2)error (rsquoWrong number of arguments You should provide xstart and xendrsquo)endif (nargin lt 4)col = rsquobrsquoendif (xstart == xend)error (rsquoThe [xstart xend] should be a non-zero rangersquo)elseif (xstart gt xend)exchange = xendxend = xstartxstart = exchangeendswitch colcase rsquobrsquorsquokrsquorsquomrsquorsquogrsquorsquowrsquorsquoyrsquorsquorrsquo do nothing the right color choiceotherwiseerror (rsquoWrong col value providedrsquo)endx = linspace (xstart xend)y = feval (F x)plot (x y col)description = [rsquoPlot of rsquo F]title (description)returnNote the use of comments the nargin variable and the switch-constructionCall funplot for different built-in functions like sin exp etc Test it for your own functions as well Writefor example a function myfun that computes sin(x cos(x)) or log( |x sin(x)| )Explain why it would be wrong to use the fragment given below instead of its equivalent part in funplotif nargin lt 2xstart = 0xend = 10elseif nargin lt 338error (rsquoWrong number of arguments You should provide xstart and xendrsquo)elseif nargin lt 4col = rsquobrsquoend_end optional

93 Scripts vs functionsThe most important difference between a script and a function is that all scriptrsquos parameters and variablesare externally accessible (ie in the workspace) where function variables are not Therefore a script is agood tool for documenting work designing experiments and testing In general create a function to solve agiven problem for arbitrary parameters Use a script to run functions for specific parameters required by theassignment

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 35: Introduction to Programming Using Matlab

Exercise 53Create the function binom that computes the value of the binomial symbol 1048576n

k_ Make the function headerfunction b = binom (nk) Note that in order to write this function you will have to create the factorialfunction which computes the value of n = 1 _ 2 _ _ n This may become a separate function (enclosedin a new file) or a subfunction in the binomm file Try to implement both cases if you got acquainted withthe notion of a subfunction Having created the binom function write a script that displays on screen all thebinomial symbols for n = 8 and k = 1 2 8 or write a script that displays on screen the following rsquotrianglersquo(use the fprintf command)10485761

10485761_ 21_ 10485762

1048576 2_ 31_ 10485763

2_ 10485763

1048576 3_ 41_ 10485764

2_ 10485764

3_ 10485764

4_ _

10 Optimizing the performance of Matlab codeMatlab is a matrix language so it is designed for matrix operations For best performance you should takeadvantage of this fact101 Vectorization - speed-up of computationsVectorization is simply the use of compact expressions that operate on all elements of a vector without explicitly43-62 executing a loop Matlab is optimized such that vector or matrix operations are much more efficient thanloops Most built-in functions support vectorized operations So try to replace loops with vector operationswhen possible For example instead of usingfor i = 110t(i) = 2iy(i) = sin (t(i))endtry thist = 2220y = sin (t)Copying or transforming matrices can be vectorized as well Check the equivalence between the scalar versionn = 10A = rand(nn)B = ones(nn)for k=1nB(2k) = A(2k) A and B have the same sizeend39and the vectorized code of the last loopB(2) = A(2)or between the following loopfor k=1nB(k1) = A(kk)endand the vectorized expressionB(1n1) = diag(A(1n1n))Logical operations and proper use of the colon notation make the programs work faster However someexperience is needed to do this correctly Therefore the advice is start first with the scalar code andthen vectorize it where possible by removing loopsExercise 54Look at your script or function m-files already written especially your loop exercises Try to vectorize theircodes when possible _Exercise 55Try to vectorize the following codesbull code 1n = 20m = 10

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 36: Introduction to Programming Using Matlab

A = rand(nm)for i=1nfor k=1mif (A(ij) gt 05)A(ij) = 1elseA(ij) = 0endendendbull code 2n = 20m = 10A = randn(nm)x = randn(n1)p = zeros(1m)for i=1mp(i) = sum (x A(i)) what is p hereend_

102 Array preallocationIn rsquorealrsquo programming languages memory allocation is necessary In Matlab it is not needed but it improvesthe execution speed and besides practicing it is a good habit Preallocate the arrays which store outputresults This prevents Matlab from resizing an array each time you enlarge it Preallocation also helps toreduce memory fragmentation if you work with large matrices During the Matlab session memory can befragmented As a result there may be plenty of free memory but not enough continuous space to store a largevariableExercise 56Create two scripts with the listings given below run them and compare the results ie measured times of theirperformances The pair of commands tic and toc is used to measure the execution time of the operations40 script 1 script 2tic ticx = -25001250 x = -25001250s = zeros (size(x)) preallocate memoryfor i=1length(x) for i=1length(x)if (x(i) gt 0) if (x(i) gt 0)s(i) = sqrt(x(i)) s(i) = sqrt(x(i))else ends(i) = 0endend endtoc tocclear s x clear s xRemember that scripts work in the workspace interfering with the existing variables Therefore for a faircomparison the variables s and x should be removed after running each script Having done this try to107128 vectorize the code _

11 File inputoutput operationsMatlab file input and output (IO) functions read and write arbitrary binary and formatted text files This404-406 enables you to read data collected in other formats and to save data for other programs as well Before readingor writing a file you must open it with the fopen commandgtgt fid = fopen (file_name permission)The permission string specifies the type of access you want to have- rsquorrsquo - for reading only- rsquowrsquo - for writing only- rsquoarsquo - for appending only- rsquor+rsquo - both for reading and writingHere is an examplegtgt fid = fopen (rsquoresultstxtrsquorsquowrsquo) tries to open the file resultstxt for writingThe fopen statement returns an integer file identifier which is a handle to the file (used later for addressingand accessing your file) When fopen fails (eg by trying to open a non-existing file) the file identifier becomes

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 37: Introduction to Programming Using Matlab

minus1 It is also possible to get an error message which is returned as the second optional output argumentIt is a good habit to test the file identifier each time when you open a file especially for reading Below theexample is given when the user provides a string until it is a name of a readable filefid = 0while fid lt 1fname = input (rsquoOpen file rsquo rsquosrsquo)[fid message] = fopen (fname rsquorrsquo)if (fid == -1)disp (message)endendExercise 57Create a script with the code given above and check its behavior when you give a name of a non-existing file(eg nonametxt) and a readable file (eg one of your functions) _When you finish working on a file use fclose to close it up Matlab automatically closes all open files whenyou exit it However you should close your file when you finished using itfid = fopen (rsquoresultstxtrsquo rsquowrsquo)fclose(fid)41111 Text filesThe fprintf command converts data to character strings and displays it on screen or writes it to a file Thegeneral syntax isfprintf (fidformata)For more detailed description see section 72 Consider the following examplegtgt x = 0011gtgt y = [x exp(x)]gtgt fid = fopen (rsquoexptabtxtrsquorsquowrsquo)gtgt fprintf(fid rsquoExponential functionnrsquo)gtgt fprintf(fid rsquo62f 128fnrsquoy)gtgt fclose(fid)Exercise 58Prepare a script that creates the sintabtxt file containing a short table of the sinus function _The fscanf command is used to read a formatted text file The general function definition is[Acount] = fscanf (fid format size)This function reads text from a file specified by file identifier fid converts it according to the given format(the same rules apply as in case of the fprintf command) and returns it in a matrix A count is an optionaloutput argument standing for the number of elements successfully read The optional argument size says howmany elements should be read from the file If it is not given then the entire file is considered The followingspecifications can be usedbull n - read at most n elements into a column vectorbull inf - read at most to the end of the filebull [m n] - read at most m n elements filling at least an m-by-n matrix in column order n can be infHere is an examplegtgt a = fscanf (fid rsquo5drsquo 25) read 25 integers into a vector agtgt A = fscanf (fid rsquo5drsquo [5 5]) read 25 integers into a 5 x 5 matrix AMatlab can also read lines from a formatted text and store it in strings Two functions can be used fgetsand fgetl The only difference is that fgetl copies the newline character while fgets does notExercise 59Create the following script and try to understand how it works (use the help command to learn more on thefeof function)fid = fopen (rsquoexptabtxtrsquorsquorrsquo)title = fgetl (fid)k = 0while ~feof(fid) as long as end-of-file is not reached do k = k+1line = fgetl (fid) get a line from the exponential tabletab(k) = str2num (line) convert the line into a vector from tab matrixendfclose(fid)Look at the matrix tab How does it differ from the originally created matrix _Reading lines from a formatted text file may be especially useful when you want to modify an existing fileThen you may read a specified number of lines of a file and add something at the found spotExercise 60Create a script that reads the exptabtxt file and at the end of the file adds new exponential values say for

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 38: Introduction to Programming Using Matlab

x = 11 01 3 Note that you should open the exptabtxt file both for reading and writing _42optionalExercise 61Write the function countlet that opens a file specified by a name reads this file line by line and counts thenumber of appearance of the specified letter (so there are two input arguments the name and the letter)Remember to return an error message when there is a problem with opening the file Create a text filetesttxt with some text eg by writing random words or retyping a few sentences of a book Test yourfunction by callinggtgt c = countlet (rsquotesttxtrsquo rsquodrsquo)gtgt c = countlet (rsquocountletmrsquo rsquoarsquo) YES you can do this_end optional

112 Binary filesThere are two important variables to write and read from a binary file fread and fwrite The definition ofthe function fwrite is given belowcount = fwrite (fid A precision)This command writes the elements of matrix A to the provided file while converting values to the specifiedprecision The data is written in column order count is the number of successfully written elementsThe definition of the function fread is given below[A count] = fread (fid size precision)This reads binary data from the specified file and writes it into matrix A count is an optional parameterwhich returns the number of elements successfully read The size argument is optional and its specification isthe same as in case of the fscanf function (see section 111) The precision argument controls the numberof bits read for each value and their interpretation as character integer or floating-point values eg rsquoucharrsquorsquoint16rsquo or rsquosinglersquo (learn more from help) By default numeric values are returned in double precisionoptionalExercise 62Exercise with the following scripts Write the 5-by-5 magic square into binary fileM = magic(5) creates a magic squarefid1 = fopen (rsquomagic5binrsquorsquowrsquo)count = fwrite (fid1 M rsquoint16rsquo) count should be 25fclose(fid1)Note that a 50-byte binary file should appear (25 integer numbers each stored in 2 bytes) Read the 5-by-5 magic square into binary filefid2 = fopen (rsquomagic5binrsquorsquorbrsquo)[A count] = fread (fid2 [55] rsquoint16rsquo) count should be 25fclose(fid2)Check what will happen if you skip the specification of either size or type eg[B count] = fread (fid2)or[B count] = fread (fid2 [55])43Note that each time you should open and close the magic5bin file _A particular location within a file is specified by a file position indicator This indicator is used to determinewhere in the file the next read or write operation will begin The Matlab functions operating on the fileposition indicator are summarized belowFunction Purposefeof determines if file position indicator reached the end-of-filefseek sets file position indicator to the specified byte with respect to the given originftell returns the location of file position indicatorfrewind resets file position indicator to beginning of fileTo understand how fseek and ftell work consider this script (you can use on-line help to learn more aboutthese functionrsquos specifications)a = 15fid = fopen (rsquofivebinrsquorsquowrsquo)count = fwrite (fid a rsquosinglersquo)fclose(fid)Five integers are written to the file fivebin with a single precision so each number uses 4 bytes Try tounderstand what is happening heregtgt fid = fopen (rsquofivebinrsquorsquorrsquo) open for readinggtgt status = fseek (fid 12 rsquobofrsquo) move the file position indicator forward 12 bytesgtgt from the beginning of file rsquobofrsquo status is 0 whengtgt the operation was successful

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 39: Introduction to Programming Using Matlab

gtgt four = fread (fid 1 rsquosinglersquo) read one element at the current position startinggtgt from byte 13 so it should be the number 4gtgt pos = ftell (fid) check the position the number 4 is read so itgtgt should be 16 nowgtgt status = fseek (fid -8 rsquocofrsquo) move the file position indicator backward 8 bytesgtgt from the current position rsquocofrsquogtgt pos = ftell (fid) check the position it should be 8gtgt three = fread (fid 1 rsquosinglersquo) read one element so it should be 3gtgt fclose(fid)end optional

12 Writing and debugging Matlab programsThe recommendations in this section are general for programming in any language Learning them now willturn out to be beneficial in the future or while learning real programming languages like C where structuredprogramming is indispensable121 Structural programmingNever write all code at once program in small steps and make sure that each of these small steps works asexpected before proceeding to the next one Each step should be devoted to only one task Do not solve toomany tasks in one module because you may easily make a mess This is called a structured or modular way ofprogramming Formally modularity is the hierarchical organization of a system or a task into self-containedsubtasks and subsystems each having a prescribed input-output communication It is an essential feature ofa well designed program The benefit of structural programming are easier error detection and correctionmodifiability extensibility and portabilityBelow the general approach to a program development is presented1 SpecificationRead and understand the problem The computer cannot do anything itself you have to tell it howto operate Before using the computer some level of preparation and thought is required Some basicquestions to be asked are44- What are the parametersinputs for this problem- What are the resultsoutputs for this problem- What form should the inputsoutputs be provided in- What sort of algorithms is needed to find the outputs from the inputs2 DesignSplit your problem into a number of smaller and easier tasks Decide how to implement them Start witha schematic implementation to solve your problem eg create function headers or script descriptions(decide about the input and output arguments) To do this you may use for example a top-downapproach You start at the most general level where your first functions are defined Each function maybe again composed of a number of functions (subfunctions) While rsquogoing downrsquo your functions becomemore precise and more detailedAs an example imagine that you have to compare the results of the given problem for two differentdatasets stored in the files data1dat and data2dat Schematically such a top-down approach couldbe designed as_ This is the top (the most general) level A script solve it is created[d1 d2] = read_data (rsquodata1datrsquo rsquodata2datrsquo)[res1 err1] = solve_problem (d1)[res2 err2] = solve_problem (d2)compare_results (res1 res2 err1 err2)_ This is the second level The following functions read data solve problem and compare resultsbelong here Each of them has to be defined in a separate filebull function [d1 d2] = read_data (fname1 fname2) Here should be some descriptionfid1 = fopen (fname1rsquowrsquo) check whether the file fname1 existsfclose(fid1)fid2 = fopen (fname2rsquowrsquo) check whether the file fname2 existsfclose(fid2)d1 = d2 = returnbull function [res err] = solve_problem (d) Here should be some (possibly detailed) description

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 40: Introduction to Programming Using Matlab

res = the data d is used to compute reserr = compute_error (res)returnbull function compare_results (res1 res2 err1 err2) Some descriptiontol = 1e-6if abs (err1 - err2) gt tolfprintf (rsquoThe difference is significantrsquo)elsefprintf (rsquoThe difference is NOT significantrsquo)endreturn_ In this example this is the last level The function solve problem uses the function compute errorwhich has to be definedfunction err = compute_error (res) Here should be some (possibly detailed) description45err = the variable res is used to compute errreturn3 CodingImplement the algorithms sequentially (one by one) Turning your algorithm into an efficient code isnot a one-shot process You will have to try make errors correct them and even modify the algorithmSo be patient While implementing make sure that all your outputs are computed at some pointRemember about the comments and the style requirements (see section 123)4 Running and debugging (see also section 122)Bugs will often exist in a newly written program Never ever believe or assume that the code you justcreated works Always check the correctness of each function or script Twice You may addsome extra lines to your code which will present the intermediate results (screen displays plots writesto files) to help you controlling what is going on Those lines can be removed later5 Testing and VerificationAfter the debugging process the testing stage starts Prepare a number of tests to verify whether yourprogram does what it is expected to do Remember that good tests are those for which the answersare known Your program should produce correct results for normal test conditions as well as boundaryconditions6 MaintenanceIn solving your task new ideas or problems may appear Some can be interesting and creative and somecan help you to understand the original problem better you may see an extent to your problem or a wayto incorporate new things If you have a well-designed problem you will be able to easily modify it aftersome time Take a responsibility to improve your solutions or correct your errors when found later122 DebuggingDebugging is the process by which you isolate and fix any problem with your code Two kinds of errorsmay occur syntax error and runtime error Syntax errors can usually be easily corrected by Matlab errormessages Runtime errors are algorithmic in nature and they occur when eg you perform a calculationincorrectly They are usually difficult to track down but they are apparent when you notice unexpectedresultsDebugging is an inevitable process The best way to reduce the possibility of making a runtime error isdefensive programming- Do not assume that input is correct simply check- Where reasonable and possible provide a default option or value- Provide diagnostic error messages- Optionally print intermediate results to check the correctness of your codeDefensive programming is a part of the early debugging process Another important part is modularitybreaking large task into small subtasks which allows for developing tests for each of them more easily Youshould always remember to run the tests again after the changes have been made To make this easy provideextra print statements that can be turned on or offMatlab version 5x provides an interactive debugger It allows you to set and clear breakpoints specific linesin an m-file at which the execution halts It also allows you to change the workspace and execute the lines inan m-file one by one The Matlab m-file editor also has a debugger The debugging process can be also donefrom the command line The following command should be of use dbstop dbclear dbclear all dbstep

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447

Page 41: Introduction to Programming Using Matlab

dbstep in dbcont and dbquit When needed use help to learn more123 Recommended programming styleProgramming style is a set of conventions that programmers follow to standardize their code to some degreeand to make the overall program easier to read and to debug This will also allow you to quickly understand46what you did in your program when you look at it weeks or months from now The style conventions are forthe reader only but you will become that reader one dayBelow some style requirements and style guidelines are presented These are recommendations and somepersonal variations in style are acceptable but you should not ignore them It is important to organize yourprograms properly since it will improve the readability make the debugging task easier and save time of thepotential readers1 You should always comment difficult parts of the program But do not explain the obvious2 Comments describing tricky parts of the code assumptions or design decisions are suggested to be placedabove the part of the code you are attempting to document Try to avoid big blocks of comments exceptfor the description of the m-file header3 Indent a few spaces (preferably 2 or 3) before lines of the code and comments inside the control flowstructures The layout should reflect the program rsquoflowrsquo Here is an examplex = 001500for i=1length(x)if x(i) gt 0s(i) = sqrt(x(i))elses(i) = 0endend4 Avoid the use of magic numbers use a constant variable instead When you need to change the numberyou will have to do it only once rather than searching all over your code An example A BAD code that uses This is the way it SHOULD be magic numbers n = 50 number of pointsr = rand(150) r = rand(1n)for i = 150 for i = 1ndata(i) = i r(i) data(i) = i r(i)end endy = sum(data)50 avr = sum(data)ndisp([rsquoNumber of points is 50rsquo]) disp([rsquoNumber of points is rsquoint2str(n)])5 Avoid the use of more than one code statement per line in your script or function m-files6 No line of code should exceed 80 characters (it is a rare case when this is not possible)7 Avoid declaring global variables You will hardly ever encounter a circumstance under which you willreally need them Global variables can get you into trouble without your noticing it8 Variables should have meaningful names You may also use the standard notation eg x y are realvaluedi j k are indices or n is an integer This will reduce the number of comments and make yourcode easier to read However here are some pitfalls when choosing variable names- A meaningful variable name is good but when it gets longer than 15 characters it tends to obscurerather than improve the code readability- Be careful with names since there might be a conflict with Matlabrsquos built-in functions or reservednames like mean end sum etc (check in index or ask which ltnamegt in Matlab - if you get theresponse ltnamegt not found it means that you can safely use it)417-429 - Avoid names that look similar or differ only slightly from each other9 Use white spaces both horizontally and vertically since it will greatly improve the readability of yourprogram Blank lines should separate larger blocks of the code10 Test your program before submitting it Do not just assume it works

Referencesbull DC Lay Linear algebra and its applications Addison-Wesley 199447