79
CHAPTER 3 PART II PROGRAMMING WITH MATLAB

CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

CHAPTER 3

PART II

PROGRAMMING WITH

MATLAB

Page 2: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

Chapter 3 (Part II) : TOPIC COVERS

(PROGRAMMING with MATLAB)

• Structured Programming

• Passing Functions to M-Files

Page 3: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

LEARNING OUTCOMES

INTRODUCTION

It is expected that students will be able to:

• Write script and function files

• Create well-documented M-files by employing structured

programming

Page 4: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• Learning how to create well-documented M-files in the edit window and invoke/raise them from the command window.

• Understanding how script and function files differ.

• Understanding how to incorporate help comments in functions.

• Knowing how to set up M-files so that they interactively prompt users for information and display results in the command window.

• Understanding the role of subfunctions and how they are accessed.

• Knowing how to create and retrieve/get back data files.

Chapter Objectives

Page 5: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• Learning how to write clear and well-documented M-files by employing structured programming constructs to implement logic and repetition.

• Recognizing the difference between if...elseif and switchconstructs.

• Recognizing the difference between for...end and whilestructures.

• Understanding what is meant by vectorization and why it is beneficial.

• Knowing how to animate/living MATLAB plots.

• Understanding how anonymous/unnamed functions can be employed to pass function to function function M-files.

Objectives (cont)

Page 6: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

3.8 M-files

• While commands can be entered directly to the command window,

MATLAB also allows you to put commands in text files called M-files.

• M-files are so named because the files are stored with a “.m” extension.

• There are two main kinds of M-file

Script files

Function files

Page 7: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

3.8.1 Script Files• A script file is merely a set of MATLAB commands that are saved on a

file - when MATLAB runs a script file, it is as if you typed the characters stored in the file on the command window.

• Scripts can be executed either by typing their name (without the .m) in the command window, by selecting the Debug, Run (or Save and Run) command in the editing window, or by hitting the F5 key while in the editing window.

• Note that the two options will save any edits you have made, while the former will run the file as it exists on the drive.

Page 8: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

Example 3.1: Script File

• Problem Statement

Develop a script file to compute the velocity of the free-falling bungee jumper ?

• Solution

Open the editor with the menu selection: File, New, M-file or new script.

Then, type the following statements to compute the velocity (at a specific time).

g = 9.81; m = 68.1; t = 12; cd = 0.25;

v = sqrt (g * m / cd) * tanh (sqrt (g * cd / m) * t)

Save the file as scriptdemo.m (or other name that can be accepted)

Page 9: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

Return to the command window and type :

>> scriptdemo

The result will be displayed as :

v = 50.6175

Thus, the script executes just as if you had typed each of its lines in the

command window.

As a final step, determine the value of g by typing :

>> g

g =

9.8100

Page 10: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

So, you can see that even though ”g“ was defined within the script, it

remains its value back in the command workspace.

As discuss in the following section, this is an important

distinction/difference between scripts and functions file.

Page 11: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

3.8.2 Function files

• Function files are M-files that start with the word function.

• Function files serve an entirely different purpose from script files.

• Function files can accept input arguments and return outputs to the

command window, but variables created and manipulated within the

function do not impact/influence the command window.

Page 12: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

3.8.2.1 Function File Syntax (language rules)

• The general syntax for a function is:

function outvar = funcname(arglist)% helpcommentsstatementsoutvar = value;

whereoutvar: output variable name

funcname: function’s name

arglist: input argument list; comma-delimited list of what the

function calls values passed to it

helpcomments: text to show with information regarding function name; can be reaches by type: help funcname

statements: MATLAB statement for the computevalue that is assigned to outvar.

Page 13: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

Example 3.2 : Function Files

• Problem Statement

As in previous Example 3.1, compute the velocity of the free-falling bungee jumper, but now use a function file for the task ?

• Solution

type the following statements in the file editor.

function v = freefallvel (t, m, cd)

% freefallvel : bungee velocity with second-order drag

% v = freefallvel (t, m, cd) computes the free-fall velocity

% of an object with second-order drag

% input :

% t = time (s)

% m = mass (kg)

% cd = second-order drag coefficient (kg/m)

Page 14: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

Example : Function Files …cont.

% output :

% v = downward velocity (m/s)

g = 9.81; % acceleration of gravity

v = sqrt (g * m / cd) * tanh (sqrt (g * cd / m) * t) ;

Save the file as “freefallvel.m”

To invoke/call up the function, return to the command window and

type :

>> freefallvel (12, 68.1, 0.25)

The result will be displayed as :

ans =

50.6175

Page 15: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

One advantage of a function M-file is that it can be invoked/raise

repeatedly for different argument values. For example, compute the

velocity of a100 kg jumper after 8 s :

>> freefallvel (8, 100, 0.25)

ans =

53.1878

To invoke/recall the help comments type :

>> help freefallvel

which results in the comments being displayed as :

Page 16: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

freefallvel : bungee velocity with second-order drag

v = freefallvel (t, m, cd) computes the free-fall velocity

of an object with second-order drag

Input :

t = time (s)

m = mass (kg)

cd = second-order drag coefficient (kg/m)

output :

v = downward velocity (m/s)

If you forgot the name of this function, but remembered that it

involved bungee jumping, you could enter :

>> look for bungee

and the following information would be displayed :

freefall.m : % freefall : bungee velocity with second-order drag

Page 17: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

Note that, at the end of Example 3.2, if we had typed :

>> g

The following message would have been displayed :

??? Undefined function or variable ‘g’.

So even though “g” had a value of 9.81 within the M-file, it would not

have a value in the command workspace.

As noted previously at the end of Example 3.1(script file), this is an

important distinction between functions file and scripts file.

The variables within a function are said to be local and are erased after

the function is executed (not understand in command window).

In contrast, the variables in a script retain their existence after the

script is executed.

Page 18: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

Function M-files can return more than one result.

In this case, the variables containing the results are comma-delimited

and enclosed in brackets (such as: [m, s] = stats (y) which is writes in command window).

For example, the following function, stats.m : computes the mean and

the standard deviation of a vector :

function [mean, stdev] = stats (x)

n = length (x) ;

mean = sum (x)/n ;

stdev = sqrt (sum ((x-mean).^2/(n-1))) ;

Here is an example of how it can be applied :

>> y = [ 8 5 10 12 6 7.5 4 ]

>> [m, s] = stats (y)

m = 7.5000

s = 2.8137

Page 19: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

NOTE:

Because script M-files have limited utility, function M-files will be our

primary programming tool for the remainder of this book.

Thus, we will often refer to function M-files as simply M-files.

Page 20: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

3.8.3 Subfunctions• A function file can contain a single function, but it can also contain a

main/primary function and one or more subfunctions.

• The primary function is whatever function is listed first in the M-file - its function name should be the same as the file name.

• Subfunctions are listed below the primary function.

• Subfunctions are only accessible by the main function and subfunctions within the same M-file.

• Subfunctions are not accessible by the command window or any otherfunctions or scripts.

Page 21: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• Functions can call other functions. Although such functions can exist as separate M-files, they may also be contained in a single M-file.

• For example : the M-file in Example 3.2 could have been split into two functions and saved as a single M-file.

• (without comments)

function v = freefallsubfunc (t, m, cd)

v = vel (t, m, cd) ;

end

function v = vel (t, m, cd)

g = 9.81 ;

v = sqrt (g * m / cd) * tanh (sqrt (g * cd / m) * t) ;

end

Note : “end” statements are optional to highlight the boundaries

between the main function and the subfunction.

Main/Primary functions

subfunctions

Page 22: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• Then, this M-file would be saved as “freefallsubfunc.m”.

• In such cases, the first function is called the main or primary function. It is the only function that is accessible to the command window and other functions and scripts.

• All the other function (in this case, vel) are referred to as subfunctions. A subfunction is only accessible to the main function and other subfunctions within the M-file in which it resides/exist in.

• If we run “freefallsubfunc” from the command window, the result is exactly same to Example 3.2 :

>> freefallsubfunc ( 12, 68.1, 0.25 )

Ans =

50.6175

Page 23: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• However, if we attempt to run the subfunction vel, an error message occurs as :

>> vel ( 12, 68.1, 0.25 )

??? Underfined command / function ‘vel’.

Page 24: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

3.9.1 Input functions

• This function allows us to prompt the values directly from the command window.

• Its syntax is:

n = input('promptstring')

MATLAB will display the characters promptstring, waits for keyboard input, and then returns the value from the keyboard.

• For example:

m = input ( ' Mass (kg) : ' )

when this line is executed, the user is prompted with the message:

Mass (kg) :

• If the user enters a value, it would then be assigned to the variable "m".

Page 25: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• the input function can also return user input as a string/series.

• To do this, an ‘s’ is appended to the function’s argument list.

• For example:

name = input(‘Enter your name: ','s')

Page 26: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

3.9.2 Output functions

• The easiest way to display the value of a matrix is to type its name, but that will not work in function or script files.

• Instead, use the disp command to display value as :

disp(value)

will show the value= the value you would like to display on the screen.

value can be a numeric constant or variable or a string/series message enclosed in hyphens (' ').

Page 27: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

Example 3.3 : Example for Input-output functions

• Problem statement

As in Example 3.2, compute the velocity of the free-falling bungee jumper,

but now use the “input” and “disp” functions for input/output ?

• Solution

Type the following statements in the file editor :

function freefalli

% freefalli : interactive bungee velocity

% freefalli interactive computation of the

% free-fall velocity of an object

% with second-order drag.

g = 9.81 ; % acceleration of gravity

m = input (‘mass (kg) : ’ ) ;

cd = input (‘Drag coefficient (kg/m) : ’ ) ;

Page 28: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

t = input (‘Time (s) : ’ ) ;

disp ( ‘ ’ )

disp (‘Velocity (m/s) : ’ )

disp ( sqrt ( g * m / cd ) * tanh ( sqrt ( g * cd / m ) * t ) )

Save the file as ” freefalli.m.”

To invoke the function, return to the command window and type :

>> freefalli

Mass (kg) : 68.1

Drag coefficient (kg/m) : 0.25

Time (s) : 12

Velocity (m/s) :

50.6175

Page 29: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

3.9.3 Formatted output

• For formatted output, or for output generated by combining variable values with literal text, use the” fprintf ”command. Try to type this syntax :

fprintf ('format', x, y,...)

where format is a string/series specifying how you want the value of the variables x, y, and more to be displayed - including literal text to be printed along with the values.

• The values in the variables are formatted based on format codes.

• For example : Give value of variable velocity of 50.6175. To display the value using eight digits with four digits to the right of the decimal point along with a message, the statement along with the resulting output would be :

>> velocity = 50.617

>> fprintf ( ‘ The velocity is %8.4f m / s \ n ’ , velocity )

The velocity is 50.6175 m/s

Page 30: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• This example should make it clear how the format sequence works.

• MATLAB starts at the left end of the string and displays the labels until it detects one of the symbols : % or \ .

• In this example, it first encounter a % and recognizes that the following text is a format code (which allow you to specify whether numeric values are displayed in integer, decimal, or scientific format – see Table 3.1).

Table 3.1 : Format and Control Codes

• The following format codes define how a numerical value is displayed.%d - integer format%e - scientific format with lowercase e%E - scientific format with uppercase E%f - decimal format%g - the more compact of %e or %f

• The following control codes produce special results within the format string/series.\n - start a new line\t - tab\\ - print the \ character

• To print a ' put a pair of ' in the format string

Page 31: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• After displaying the value of velocity, MATLAB continues displaying the character information (in our case the unit : “m/s”) until it detects the symbol “ \ ” . This tells MATLAB that the following text is a control code (which provide a means to perform actions such as skipping to the next line – see Table 3.1).

• If we had omitted the code “ \ n ” in the previous example, the command prompt/rapid (>>) would appear at the end of the label “m/s” rather than one the next line as would typically be desired.

• You can try to omit the code “ \ n ” .

• The “ fprintf ” function can also be used to display several values per line with different formats.

• For example :

>> fprintf ( ‘ %5d %10.3f %8.5e\n ’ , 100, 2*pi,pi ) ;

100 6.283 3.14159e+000

Page 32: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• The “ fprintf ” function is used to display vectors and matrices.

• For example : use M-file to enter two sets of values as vector. These vectors are then combined into a matrix, which is then displayed as a table with headings.

function fprintfdemo

x = [ 1 2 3 4 5 ] ;

y = [ 20.4 12.6 17.8 88.7 120.4 ] ;

z = [ x ; y ] ;

fprintf ( ‘ x y \n ’ ) ;

fprintf ( ‘ %5d %10.3f \ n ’ , z ) ;

The result of running this M-file is :

>> fprintfdemo

x y

1 20.400

2 12.600

3 17.800

4 88.700

5 120.400

Page 33: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

3.9.4 Creating and Accessing Files

• MATLAB has a built-in file format that may be used to save and load where the values in variables can be created and accessed.

• The save command can be used to generate a MAT-file holding either the entire worksapce or a few selected variables. This is a simplest approach involves a special type of binary file (called a MAT-file).

• For example :

save filename var1 var2 . . . varn

• Thus, this command creates a MAT-file named “filename.mat” that hold the variables “var1” through “varn”.

If the variables are omitted, all the workspace variables are saved.

• Note - these are not text files!

Page 34: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• The “load” command can be used to retrieve/regain the file. For example :

load filename var1 var2 . . . varn

• Which regain/recover the variables var1 through varn from filename.mat.

• As was the case with save, if the variables are omitted, all the variables are retrieved.

• For example : Use equation of falling bungee equation (1.9) to generate velocities for a set of drag coefficients.

>> g = 9.81 ; m = 80 ; t = 5 ;

>> cd = [ .25 .267 .28 .273 ] ’ ;

>> v = sqrt ( g * m . / cd ) . * tanh ( sqrt ( g * cd / m ) * t ) ;

• You can create a file holding the values of drag coefficient and the velocities with command :

>> save veldrag v cd

Page 35: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• To illustrated how the values can be retrieved at a later time, remove all variables from the workspace with the “clear” command as :

>> clear

• At this point, if you tried to display the velocities you would get the result as :

>> v

??? Underfined function or variable ‘ v ’ .

• However, you can recover them by entering :

>> load veldrag

• Now, the velocities are available as can be verified by typing :

>> who

Your variables are :

cd v

Page 36: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

3.9.5 ASCII Files

• Although MAT-files are quite useful when working exclusively within the MATLAB environment, a somewhat different approach is required wheninterfacing MATLAB with other programs.

• In such case, a simple approach is to create text files written in the widely accessible ASCII format.

• ASCII files can be generated in MATLAB by appending “ -ascii ” to the “save” command.

• While to save MAT-files (entire workspace), you would save a single rectangular matrix of values.

• For example:

>> A = [ 5 7 9 2 ; 3 6 3 9 ] ;

>> save simpmatrix.txt –ascii

In this case, the “save” command stores the values in “A” in 8-digit ASCII

form.

Page 37: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• If you want to store the number in double precision, just append

“-ascii -double”.

• For both cases, the file can be assessed by other programs such as spreadsheets or word processors. For example if you open this file with a text editor, you will see :

5.0000000e + 000 7.0000000e + 000 9.0000000e + 000 2.0000000e + 000

3.0000000e + 000 6.0000000e + 000 3.0000000e + 000 9.0000000e + 000

• Alternatively, you can read the values back into MATLAB with the “load” command as:

>> load simpmatrix.txt

• Because ”load simpmatrix.txt“ is not a MAT-file, MATLAB creates a double precision array named after the “filename” :

>> simpmatrix

simpmatrix =

5 7 9 2

3 6 3 9

Page 38: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• Alternatively, you could use “load” command as a function and assign its values to a variable as :

>> A = load (simpmatrix.txt)

Page 39: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

3.10 Structured Programming

• We have learn the simplest of M-files that perform instructions sequentially which the program statements are executed line by line (starting at the top of the function and moving down to the end)

• However, there are 2 type of computer language which allow for non-sequential paths.

• They are :

a. Decision (or selection) : the branching of flow based on a decision

b. Loops (or Repetition) : the looping of flow to allow statements to be repeated.

Page 40: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

3.10.1 Decisions

a. The “if” Structure : allows to execute a set of statements if a logical

condition is true. The general syntax/language rule is :

if condition

statements

end

• Where “condition” is a logical expression that is either true or false.

• For example : to evaluate whether a grade is passing (using simple M-file)

function grader (grade)

% grader (grade)

% determine whether grade is passing

% input :

% grade = numerical value or grade (0-100)

% output :

% displayed message

if grade >=60

disp ( ‘ passing grade ’ )

end

Page 41: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

Then, let we want to know whether grade of 95.6 is pass or not?

>> grader (95.6)

Passing grade

• For cases where only one statement is executed, thus more convenience is to implement/use the “if” structure as a single line.

• For example :

if grade > 60, disp (‘passing grade’), end

• This structure is called a ”single-line if”.

• For the cases more than one statement is implemented, the multiline“ if ” structure is preferable because it is easier to read.

Page 42: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

b. Error Function : The syntax for error function:

error (msg)

• Error function has come with “msg” and cause the M-file to terminate and return to the command window.

• For example : terminate M-file to avoid a division by zero;

function f = errortest (x)

if x == 0 , error ( ‘ zero value encountered ’ ) , end

f = 1/x ;

• Thus, if a non-zero argument is used, the division would be implemented successfully, for example :

>> errortest (10)

ans =

0.1000

Page 43: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• However, for a zero argument, the function would terminate prior to the division and the error message would be displayed as :

>> errortest (0)

??? Error using ==> erroetest

zero value encountered

Page 44: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

c. Logical Conditions : is used to compares two values. The syntax can

be typed as :

value1 relation value2

• where the “values” can be constants, variables, or expressions and the “relation” is one of the relational operators listed in Table 3.2.

Page 45: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

Table 3.2: Summary of relational operators in MATLAB:

Example Operator Relationship

x == 0 == Equal

unit ~= ‘m’ ~= Not equal

a < 0 < Less than

s > t > Greater than

3.9 <= a/3 <= Less than or equal to

r >= 0 >= Greater than or equal to

Page 46: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• If you want to test with more than one condition you can use the logical operators command such as

Logical Operator Commands

• The “if…..else” structure : this structure allows to execute a set of statements if a logical condition is true and to execute a second set if the condition is false.

• For example :

if condition

statements1

else

stetement2end

~x (Not): true if x is false (or zero); false if x is true (or non-zero)

x & y (And): true if both x and y are true (or non-zero)

x | y (Or): true if either x or y are true (or non-zero)

Page 47: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• The “ if…..elseif ” structure : it often happens that the false option of an ” if…..else ” structure is another decision.

• This type of structure (“ if…..elseif ”) often occurs when we have more than two options for a particular problem setting.

• To execute this syntax as :

if condition

statements1

elseif condition2

stetement2elseif condition3

stetement3.

.

.

else

stetementelse

end

Note : Try at home Example 3.4 (page 61) for the “if” structure….

Page 48: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• The “switch” structure :

• The ”switch” structure is similar in spirit to the “if…..elseif” structure.

• However, rather than testing individual conditions, the branching is based on the value of a single test expression.

• Depending on its value, different blocks of code are implemented. In addition, an optional block is implemented if the expression takes on none of prescribed values.

• The structure can be execute as :

switch testexpression

case value1

stetement1case value2

stetement2.

.

.

otherwise

stetementotherwise

end

Page 49: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• For example to display a message depending on the value of the string/series variable “grade” :

grade = ‘B’ ;

switch grade

case ‘A’

disp (‘Excellent’)

case ‘B’

disp (‘Good’)

case ‘C’

disp (‘Mediocre’)

case ‘D’

disp (‘Whoop’)

case ‘F’

disp (‘Would like fries with your order?’)

otherwise

disp (‘Huh!’)

end

When this code was executed, the message “Good” would be displayed

Page 50: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

d. Variable argument list : MATLAB allows a variable number of

arguments to be passed to a function (with a function called “nargin” ).

• This feature can come in handy for incorporating “default values” into your functions.

• A “default value” is a number that is automatically assigned in the event that the user does not pass it to a function.

• For example, recall that earlier in this chapter, we developed a function “freefallvel”, which had three arguments :

v = freefallvel (t, m, cd)

Page 51: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• Although a user obviously need a specify the time and mass, they might not have a good idea of an appropriate drag coefficient.

• Therefore, it would be nice to have the program supply a value if they omitted it from the argument list.

• MATLAB has a function called “nargin” that provides the number of input arguments supplied to a function by a user.

• It can be used in conjunction with decision structures like the “if ” or “switch” constructs to incorporate default values as well as error message into functions.

• The following code shows how this can be done for “freefallvel” :

Page 52: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

function v = freefall2 (t, m, cd)

% freefall2 : bungee velocity with second-order drag

% v = freefallvel (t, m, cd) computes the free-fall velocity

% of an object with second-order drag.

% input :

% t = time (s)

% m = mass (kg)

% cd = drag coefficient (default = 0.27 kg/m)

% output :

% v = downward velocity (m/s)

switch nargin

case 0

error (‘ Must enter time and mass ’)

case 1

error (‘ Must enter mass ’)

case 2

cd = 0.27 ;

end

g = 9.81 ; % acceleration of gravity

v = sqrt (g * m / cd) * tanh (sqrt (g * cd / m) * t ) ;

Page 53: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• Notice that the use of a switch structure to either display error message or set the default, depending on the number of arguments passed by the user.

• This is the result shows in the command window :

>> freefallvel (12, 68.1, 0.25)

ans =

50.6175

>> freefallvel (12, 68.1)

ans =

48.8747

>> freefallvel (12)

??? Error using ==> freefallvel

Must enter mass

>> freefallvel ()

??? Error using ==> freefallvel

Must enter time and mass

default value for Cd = 0.27 kg/m

Page 54: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• Notice that if a word of “nargin” is type in command window it behaves a little differently, it returns the number of arguments in the function. For example :

>> nargin (‘ freefallvel ’)

ans =

3

Page 55: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

3.10.2 Loops (or Repetition)-(circles/rounds)• As the name implies, loops perform operations repetitively.

• Another programming structure involves loops, where the same lines of

code are run several times.

• There are two types of loop depending on how the repetitions are

terminated :

A “for” loop ends after a specified number of repetitions (“for” loop

command).

A “while” loop ends on the basis of a logical condition (“while” loop

command)

Page 56: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

a. The “for. . . end“ structure :

• A “ for “ loop repeat statements a specific number of times. The

command can be given as :

for index = start : step : finish

statements

end

• The above command can be explained as :

The “index” is a variable that is set at an initial value of “start”

The program then compares the “index” with a desired final value of “finish”

If the “index” is less than or equal to the “finish”, the program executes the “

statement”.

When it reaches the “end” line that marks the end of the loop, the “index”

variable is increased by the “step” and the program loops back up to the “for”

statement.

The process continues until the “index” becomes greater than the “finish” value.

At this point, the loop terminates as the program skips down to the line

immediately following the “ end” statement.

Page 57: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• For example :[Note : if an increment of “1” is desired ( as most of the case as a default value), the “step”

can be dropped]

for i = 1 : 5

disp (i)

end

• When this command is executes, MATLAB would display in

succession/series, 1, 2, 3, 4, 5. (where the default “step” is “1”)

• The size of the “step” can be changed from the default of 1 to any other

numeric value, includes an integer value and negative magnitude. For

example, step size of 0.2, -1 or -5 are all accepted.

• If a negative “step” is used, the loop will countdown in reverse, where the

logic is reversed as well, Thus, the “finish” is less than the “start” and the

loop terminates when the “index” is less than the “finish”.

• For example:

Page 58: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• For example :

for j = 10 : -1 : 1

disp (j)

end

• When this executes, MATLAB would display the classic countdown

sequence : in succession/series,

10, 9, 8, 7, 6, 5, 4, 3, 2, 1.

Page 59: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

Example 3.5 : Using a “ for ” loop to compute the factorial.

Problem Statement : Develop an M-file to compute the factorial.

(Note : MATLAB has a built-in function “ factorial” as well)

O ! = 1

1 ! = 1

2 ! = 1x2 = 2

3 ! = 1x2x3 = 6

4 ! = 1x2x3x4 = 24

5 ! = 1x2x3x4x5 = 120.

.

.

.

Solution : A simple function to implement this calculation can be

developed as :

Page 60: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

function fout = factor (n)

% factor (n) :

% Computes the product of all the integers from 1 to n.

x = 1 ;

for i = 1 : n

x = x * i ;

end

fout = x ;

end

The result will be (in command window):

>> factor (5)

ans =

120

This loop will execute 5 times (from 1 to 5). At the end of the process, x

will hold a value of 5 ! (meaning 5 factorial or 1x2x3x4x5 = 120).

Notice what happens if n = 0. For this case, the “for” loop would not

execute, and we would get the desired result, 0 ! = 1.

Page 61: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

b. Vectorization

• Sometimes, it is more efficient to have MATLAB perform calculations on

an entire array rather than processing an array element by element

(repeat statement of “for” loop).

• This can be done through vectorization (operate directly on arrays).

• The examples of MATLAB operate statement of “for” loop and

vectorization command window are in table below:

“for” loop Vectorization

i = 0;

for t = 0:0.02:50

i = i + 1;

y(i) = cos(t);

end

t = 0:0.02:50;

y = cos(t);

Page 62: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

c. “while” Loops

• A “while” loop repeats as long as logical condition is true.

• A “while” loop is fundamentally different from a “for” loop since “while” loops can run an indeterminate/ uncertain number of times.

• The general syntax is :

while conditionstatements

end

• The statements between the while and the end are repeated as long as the condition is true.

• For example :

x = 8

while x > 0

x = x – 3 ;

disp (x)

end

Page 63: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

The result is :

x =

8

5

2

-1

Page 64: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

c. “while . . . break” Loop

• “while” structure is extremely useful when it always exist at the beginning of the structure on a “false result” is constraining/limiting.

• For this reason, language programs such as Fortran 90 and Visual Basic have special structure that allow “termination on a true condition anywhere in the loop”.

• Although such structure are currently not available in MATLAB, their functionality can be mimicked/imitated by a special version of the “while”loop; which called a “while. . . break” structure.

Page 65: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• The general syntax is :while (1)

statementsif condition, break, end

statements

end

• “break” terminates execution/effecting/implementation of the loop.

• “if” is used to exit the loop if the condition tests are true.

• “break” can be placed in the middle of the loop (where the statements are put before and after the “break” ), this can be called as a midtest loop.

• We could also place the “break” at the very beginning to create a “pretest loop”.

• For example :

while (1)

if x < 0, break , end

x = x – 5 ;

end

• Notice how “5” is subtracted from “x” on each iteration, until it will eventually terminates. Otherwise it would become a so-called “infinite loop” that would never stop.

Page 66: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• Alternatively, we could also place the “if. . . break” statement at the very end and create a posttest loop:

• For this the syntax is :

while (1)x = x – 5 ;

if x < 0, break , end

end

Example for posttest loop (The explanation in next slide) :

x = 24

while (1)

x = x – 5

if x < 0, break, end

end

• This will produce “x” values of 24, 19, 14, 9, 4, and -1, then stop.

Page 67: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• Notice how ”5” is subtracted from “x” on each iteration.

• This represents a mechanism so that the loop eventually terminates.

• Every decision loop must have such mechanism (terminate mechanisms), otherwise it would become a so-called “infinite loop” that would never stop.

Page 68: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

d. “pause” command

• This command is used to temporarily “halt/pause” the program.

• The command “pause” causes a procedure to stop and wait until any key is hit.

• A good example involves creating a sequence of plots that user might want to leisurely/easy/check before moving on to the next.

• For example :

for n = 3 : 10

mesh (magic (n) )

pause

end

• The “pause” can also be formulated as “pause (n)” in which case the procedure will halt/ pause for ‘n’ seconds.

• This procedure can be applied in conjunction with several other useful MATLAB functions.

• For example the “beep” command cause the computer to emit/release a beep sound.

Page 69: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• While, functions of “tic” and “toc”, work together to measure elapsed/pass time.

• The “tic” command saves the current time that “toc” later employs to display the pass time.

• The example to execute such commands are :

tic

beep

pause (5)

beep

toc

• When this code is run the computer will beep, five second later it will beep again and display the following message :

Elapsed time is 5.006306 second

Page 70: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

3.11.5 Animation (alive/decorate MATLAB plots)• Two ways to animate plots in MATLAB:

Using looping with simple plotting functions

This approach merely replots the graph over and over again.

Important to use the “axis” command so that the plots scales are fixed.

Using special function: “getframe” and “movie”

This allows you to capture a sequence of plots (“getframe”) and then play them back (“movie”).

Page 71: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

Case Study for Animation – Example 3.6 (page 70)

• The (x, y) coordinates of a projectile/rocket can be generated as a function of time, t, with the following parametric equations:

x = v0 cos(0 t)

y = v0 sin(0 t) - 0.5 gt2

Where v0 = initial velocity (m/s)

0 = initial angle (radians)

g = gravitational constant (= 9.81 m/s2)

Page 72: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

Answers : write the Script to generate animation

• The following code illustrates both approaches:clc,clf,clear

g=9.81; theta0=45*pi/180; v0=5;

t(1)=0;x=0;y=0;

plot(x,y,'o','MarkerFaceColor','b','MarkerSize',8)

axis([0 3 0 0.8])

M(1)=getframe;

dt=1/128;

for j = 2:1000

t(j)=t(j-1)+dt;

x=v0*cos(theta0)*t(j);

y=v0*sin(theta0)*t(j)-0.5*g*t(j)^2;

plot(x,y,'o','MarkerFaceColor','b','MarkerSize',8)

axis([0 3 0 0.8])

M(j)=getframe;

if y<=0, break, end

end

pause

movie(M,1)

Page 73: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

Result

Page 74: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

3.12 Nesting/layer and Indentation/hollow• Nesting is “Structures can be placed within other structures”.

• For example, the “statements” portion of a “for” loop can be comprised of an “if...elseif...else” structure.

• For clarity of reading, the “statements” of a structure are generally indented/hollowed to show which lines of controlled are under the control of which structure.

Note : Example 3.7 (page 71) for the “if. . . elseif. . . else” structure.

Page 75: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

3.13.1 Anonymous Functions (unnammed function) & Inline Functions

• Anonymous functions are simple one-line functions created without the need for M-file.

• It can be defined within the command window with syntax:fhandle = @(arg1, arg2, ...) expression

where fhandle = function handle you can use to invoke/raise the function.

arg1, arg2, . . . = a comma separated list of input arguments to be passed

to the function.

expression = any single valid MATLAB expression

• For example:

>> f1 = @ (x, y) x^2 + y^2 ;

• Once these function are defined in the command window, they can be used just as other function, for example:

>> f1 (3, 4)

ans =

25

Page 76: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• Aside from the variables in its argument list, an anonymous function can include variables that exist in workspace where it is created.

• For example : f(x) = 4x2 that can be written as:

>> a = 4

>> b = 2 ;

>> f2 = @ (x) a*x^b ;

>> f2 (3)

ans = 36

• Note that if subsequently we enter new values for “a” and “b”, the anonymous function does not change:

>> a = 3 ;

>> f2 (3)

ans = 36

Page 77: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

• Thus, the function handle holds a snapshot of the function at the time it was created. If we want the variables to take on values, we must recreate the function.

• For example, having changed “a” to “3”:

>> f2 = @ (x) a*x^b ;

with the result

>> f2 (3)

ans = 27

• Inline functions are essentially the same as anonymous functions, but with a different syntax:fhandle = inline('expression', 'arg1', 'arg2',...)

• Anonymous functions can access the values of variables in the workspace upon creation, while inlines cannot.

• Example for inline function:

>> f1 = inline (‘x^2 + y^2’ , ‘x’ , ‘y’) ;

Page 78: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

3.13.2 Function Functions • Function functions are functions that operate on other functions which are

passed to it as input arguments.

• The input argument may be the handle of an anonymous function or inline function, the name of a built-in function, or the name of a M-file function.

• Using function functions will allow for more dynamic programming.

Page 79: CHAPTER 3 PART II - Universiti Teknologi Malaysia€¦ · 3.8.1 Script Files • A script file is merely a set of MATLAB commands that are saved on a file - when MATLAB runs a script

END

OF

CHAPTER 3

(Part II)