0% found this document useful (0 votes)
8 views58 pages

CHE 306 Lesson Note 3

Uploaded by

Sysavane Usman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views58 pages

CHE 306 Lesson Note 3

Uploaded by

Sysavane Usman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 58

• The primary

objective of this
LESSON 3: section is to
learn how to
MATLAB write M-file
programs to
PROGRAMMING implement
numerical
methods.
M-files
Input-Output
Structured Programming
CONTENTS Nesting and Indentation
Passing Functions to M-
files
Case Study: Bungee
Jumper Velocity
 The most common way to operate
MATLAB is by entering commands
one at a time in the command
window.
 M-files provide an alternative way
of performing operations that
M-FILES greatly expand MATLAB’s
problem-solving capabilities.
 An M-file consists of a series of
statements that can be run all at
once. Note that the nomenclature
“M-file” comes from the fact that
such files are stored with a .m
A script file is merely a series of
MATLAB commands that are
saved on a file.
They are useful for retaining a
M-FILES
series of commands that you
want to execute on more than
(A) SCRIPT one occasion.
FILES The script can be executed by
typing the file name in the
command window or by invoking
the menu selections in the edit
window: Debug, Run.
Example 3.1: Develop a script
file to compute the velocity of the
free-falling bungee jumper for the
case where the initial velocity is
zero.
M-FILES
Solution: Open the editor with
the menu selection: File, New, M-
(A) SCRIPT file. Type in the following
FILES statements to compute the
velocity of the free-falling bungee
jumper at a specific time [recall
Eq. (1.9)]:
g = 9.81; m = 68.1; t = 12; cd = 0.25;
v = sqrt(g * m / cd) * tanh(sqrt(g * cd / m)
>>scriptdemo
The result will be displayed as
v =
50.6175
M-FILES Thus, the script executes just as
if you had typed each of its lines
(A) SCRIPT in the command window.
FILES As a final step, determine the
value of g by typing
>> g
g =
9.8100
So you can see that even though
g was defined within the script, it
retains its value back in the
command workspace.
M-FILES As we will see in the following
section, this is an important
(A) SCRIPT distinction between scripts and
functions.
FILES
Function files are M-files that
start with the word function.
In contrast to script files, they
can accept input arguments and
M-FILES return outputs.
Hence, they are analogous to
(B) FUNCTION user-defined functions in
FILES programming languages such as
Fortran, Visual Basic or C.
The syntax for the function file
can be represented generally as
function outvar = funcname(arglist)
% helpcomments
statements
outvar = value;

where outvar = the name of the output


M-FILES variable, funcname = the function’s
name, arglist = the function’s argument
list (i.e., comma-delimited values that
(B) FUNCTION are passed into the function), help
FILES comments = text that provides the user
with information regarding the
function (these can be invoked by
typing Help funcname in the command
window), and statements = MATLAB
statements that compute the value that
is assigned to outvar.
Beyond its role in describing the
function, the first line of the help
comments, called the H1 line, is
the line that is searched by the
M-FILES lookfor command.
Thus, you should include key
(B) FUNCTION descriptive words related to the
file on this line.
FILES
The M-file should be saved as
funcname.m.
The function can then be run by
typing funcname in the
command window as illustrated
Note that even though MATLAB is
case-sensitive, your computer’s
operating system may not be.
M-FILES Whereas MATLAB would treat
function names like freefall and
(B) FUNCTION FreeFall as two different
variables, your operating system
FILES
might not.
Example 3.2: As in Example
3.1, compute the velocity of the
free-falling bungee jumper but
now use a function file for the
Solution. Type the following
statements in the file editor:
function v = freefall(t, m, cd)
% freefall: bungee velocity with
second-order drag
M-FILES % v=freefall(t,m,cd) computes the free-
fall velocity

(B) FUNCTION % t = time (s)


% m = mass (kg)
FILES % cd = second-order drag coefficient
(kg/m)
% 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 freefall.m. To
invoke the function, return to the
command window and type in
>> freefall(12,68.1,0.25)

The result will be displayed as


M-FILES ans =
50.6175

(B) FUNCTION One advantage of a function M-


FILES file is that it can be invoked
repeatedly for different argument
values. Suppose that you wanted
to compute the velocity of a 100-
kg jumper after 8 s:
>> freefall(8,100,0.25)
To invoke the help comments type
>> help freefall

which results in the comments


being displayed
freefall: bungee velocity with second-order drag
M-FILES v=freefall(t,m,cd) computes the free-fall velocity
of an object with second-order drag
input:
t = time (s)
(B) FUNCTION m = mass (kg)
cd = second-order drag coefficient (kg/m)
FILES output:
v = downward velocity (m/s)

If later, you forgot the name of


this function, but remembered
that it involved bungee jumping,
you could enter
and the following information
would be displayed
Freefall.m - bungee velocity with second-order drag.

Note that, at the end of the


previous example, if we had typed
M-FILES >> g

 the following message would


(B) FUNCTION have been displayed:
FILES ??? 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 2, this is an important
distinction between functions and
scripts.
The variables within a function
M-FILES
are said to be local and are erased
after the function is executed. In
(B) FUNCTION contrast, the variables in a script
FILES retain their existence after the
script is executed.
Function M-files can return more
than one result. In such cases, the
variables containing the results
For example, the following
function, stats.m, computes the
mean and the standard deviation
of a vector:
function [mean, stdev] = stats(x)
M-FILES n = length(x);
mean = sum(x)/n;
stdev = sqrt(sum((x-mean).^2/(n-1)));
(B) FUNCTION
FILES  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 =
Functions can call other functions.
Although such functions can exist
as separate M-files, they may also
be contained in a single M-file.
M-FILES For example, the M-file in Example
3.2 (without comments) could
(C) have been split into two functions
SUBFUNCTION and saved as a single M-file.
S function v
v = vel(t,
= freefallsubfunc(t, m, cd)
m, cd);
end
function v = vel(t, m, cd)
g = 9.81;
v = sqrt(g * m / cd)*tanh(sqrt(g * cd / m) *
t);
end
 This M-file would be saved as
freefallsubfunc.m.
 In such cases, the first function is
called the main or primary function.
M-FILES  It is the only function that is
accessible to the command window
(C) and other functions and scripts.
SUBFUNCTION  All the other functions (in this case,
S vel) are referred to as
subfunctions.
 A subfunction is only accessible to
the main function and other
subfunctions within the M-file in
>> freefallsubfunc(12,68.1,0.25)
ans =
50.6175
However, if we attempt to run the
subfunction vel, an error message
M-FILES
occurs:
>> vel(12,68.1,.25)
(C) ??? Undefined function or method
SUBFUNCTION 'vel’
'double’.
for input arguments of type

S
As in the previous Section,
information is passed into the
function via the argument list and
is output via the function’s name.
Two other functions provide ways
3.2 to enter and display information
directly using the command
INPUT-OUTPUT
window.
The input Function
 This function allows you to prompt
the user for values directly from the
command window. Its syntax is:
n = input('promptstring')
The function displays the
promptstring, waits for keyboard
input, and then returns the value
from the keyboard.
For example,
m = input('Mass (kg): ')
3.2
When this line is executed, the
INPUT-OUTPUT
user is prompted with the
message
Mass (kg):

If the user enters a value, it


would then be assigned to the
To do this, an 's' is appended to
the function’s argument list. For
example,
name = input('Enter your name:
','s’)

3.2 The disp Function


INPUT-OUTPUT This function provides a handy way
to display a value. Its syntax is
disp(value)

where value = the value you


would like to display. It can be a
numeric constant or variable, or a
Example 3.3: An Interactive M-
File Function
As in Example 3.2, compute the
velocity of the free-falling bungee
jumper, but now use the input
3.2 and disp functions for
input/output.
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): ');
3.2 t = input('Time (s): ');
disp(' ')
INPUT-OUTPUT 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

The fprintf Function


3.2 This function provides additional
INPUT-OUTPUT control over the display of
information.
A simple representation of its
syntax is
fprintf('format', x, ...)

where format is a string


 A simple example would be
to display a value along with a
message. For instance, suppose
that the variable velocity has a
value of 50.6175.
To display the value using eight
3.2
digits with four digits to the right
INPUT-OUTPUT
of the decimal point along with a
message, the statement along
with the resulting output would
be:
>> fprintf('The velocity is %8.4f m/s\n', velocity)
The velocity is 50.6175 m/s
3.2
INPUT-OUTPUT
 MATLAB starts at the left end
of the string and displays the
labels until it detects one of the
symbols: % or \.
In our example, it first encounters
3.2 a % and recognizes that the
following text is a format code.
INPUT-OUTPUT
As in Table 3.1, the format codes
allow you to specify whether
numeric values are displayed in
integer, decimal, or scientific
format.
After displaying the value of
units: m/s) until it detects the
symbol \.
This tells MATLAB that the
following text is a control code.
As in Table 3.1, the control codes
3.2 provide a means to perform
actions such as skipping to the
INPUT-OUTPUT
next line.
If we had omitted the code \n in
the previous example, the
command prompt would appear
at the end of the label m/s rather
than on the next line as would
 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
3.2
INPUT-OUTPUT It can also be used to display
vectors and matrices.
Here is an M-file that enters two
sets of values as vectors.
These vectors are then combined
into a matrix, which is then
 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);

3.2 The result of running this M-file is


INPUT-OUTPUT  >> fprintfdemo
x y
1 20.400
2 12.600
3 17.800
4 88.700
5 120.400
The simplest of all M-files perform
instructions sequentially. That is,
the program statements are
executed line by line starting at
the top of the function and
3.3 moving down to the end.
STRUCTURED Because a strict sequence is
PROGRAMMING highly limiting, all computer
languages include statements
allowing programs to take
nonsequential paths. These can
be classified as:
 Decisions (or Selection). The
The if Structure.
 This structure allows you to execute
a set of statements if a logical
condition is true. Its general syntax
is:
3.3.1 if condition
statements
DECISIONS end
where condition is a logical
expression that is either true or
false.
For example, here is a simple M-
file to evaluate whether a grade
function grader(grade)
% grader(grade):
% determines whether grade is passing
% input:
% grade = numerical value of grade (0-
100)
% output:
% displayed message
3.3.1 if grade >= 60
DECISIONS disp('passing grade')
end

The following illustrates the result


>> grader(95.6)
passing grade
For cases where only one
statement is executed, it is often
convenient to implement the if
structure as a single line,
if grade > 60, disp('passing grade'),
end
3.3.1 This structure is called a single-
DECISIONS line if.
For cases where more than one
statement is implemented, the
multiline if structure is usually
preferable because it is easier to
read.
TABLE 3.2: Summary of relational
operators in MATLAB.

3.3.1
DECISIONS
The if...else Structure.
This structure allows you to
execute a set of statements if a
logical condition is true and to
3.3.1 execute a second set if the
condition is false.
DECISIONS
Its general syntax is
if condition
statements1
else
statements2
end
The if...elseif Structure.
It often happens that the false
option of an if...else structure is
another decision.
3.3.1 This type of structure often
DECISIONS occurs when we have more than
two options for a particular
problem setting.
For such cases, a special form of
decision structure, the if...elseif
has been developed.

if condition1
statements1
elseif condition2
statements2
elseif condition3
3.3.1 statements3
DECISIONS . . .
else
statements
else
end
The switch Structure.
The switch structure is similar in
spirit to the if...elseif structure.
However, rather than testing
individual conditions, the
3.3.1 branching is based on the value
DECISIONS 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 the prescribed
switch testexpression
case value1
statements1
case value2
statements2
. . .
3.3.1 otherwise
statements
DECISIONS otherwise
end

As an example, here is function


that displays a message
depending on the value of the
string variable, grade.
Variable Argument List.
MATLAB allows a variable
number of arguments to be
passed to a function.
This feature can come in handy
3.3.1 for incorporating default values
DECISIONS 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.
As an example, recall in earlier
v = freefall(t,m,cd)
Although a user would obviously
need to specify the time and
mass, they might not have a
good idea of an appropriate drag
coefficient.
3.3.1
Therefore, it would be nice to
DECISIONS
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
constructs to incorporate default
values as well as error messages
your functions.
The following code illustrates
how this can be done for freefall:
3.3.1 function v = freefall2(t, m, cd)
% freefall2: bungee velocity with
DECISIONS second-order drag
% v=freefall2(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)
% 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;
3.3.1 end
DECISIONS g = 9.81; % acceleration of gravity
v = sqrt(g * m / cd)*tanh(sqrt(g * cd /
m) * t);

 Notice how we have used a switch


structure to either display error
messages or set the default,
depending on the number of
 Here is a command window session
showing the results:
>> freefall2(12,68.1,0.25)
ans =
50.6175
>> freefall2(12,68.1)
ans =
3.3.1 48.8747
DECISIONS >> freefall2(12)
??? Error using ==> freefall2 at 15
Must enter mass
>> freefall2()
??? Error using ==> freefall2 at 13
Must enter time and mass
 Here is a command window session
showing the results:
>> freefall2(12,68.1,0.25)
ans =
50.6175
>> freefall2(12,68.1)
ans =
3.3.1 48.8747
DECISIONS >> freefall2(12)
??? Error using ==> freefall2 at 15
Must enter mass
>> freefall2()
??? Error using ==> freefall2 at 13
Must enter time and mass
 As the name implies, loops perform
operations repetitively.
 There are two types of loops,
depending on how the repetitions are
terminated.
3.3.2  A for loop ends after a specified
number of repetitions.
 A while loop ends on the basis of a
LOOPS logical condition.

The for...end Structure.


 A for loop repeats statements a
specific number of times. Its
general syntax is
 The for loop operates as follows. The
index is a variable that is set at an
initial value, start.
 The program then compares the index
with a desired final value, finish. If the
3.3.2 index is less than or equal to the
finish, the program executes the
statements.
LOOPS  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
Note that if an increment of 1 is
desired (as is often the case), the
step can be dropped. For
example,

3.3.2 for i = 1:5


disp(i)
end

LOOPS When this executes, MATLAB


would display in succession, 1, 2,
3, 4, 5. In other words, the
default step is 1.
The size of the step can be
changed from the default of 1 to
For example, step sizes of 0.2, –
1, or –5, are all acceptable.

EXAMPLE 3.5: Using a for Loop to


Compute the Factorial.
3.3.2
 Develop an M-file to compute the
factorial.
LOOPS

 Solution. A simple function to


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;
3.3.2 end
fout = x;
end
LOOPS
which can be run as

>> 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 1 × 2 × 3 × 4 × 5 =
3.3.2 120).
Notice what happens if n = 0.
LOOPS For this case, the for loop would
not execute, and we would get
the desired result, 0! = 1.
Vectorization.
 The for loop is easy to implement
and understand.
 However, for MATLAB, it is not
necessarily the most efficient means
3.3.2 to repeat statements a specific
number of times.
LOOPS  Because of MATLAB’s ability to
operate directly on arrays,
vectorization provides a much more
efficient option.
 For example, the following for loop
structure:
i = 0;
for t = 0:0.02:50
i = i + 1;
y(i) = cos(t);
end

can be represented in vectorized


3.3.2
form as
t = 0:0.02:50;
LOOPS y = cos(t);

It should be noted that for more


complex code, it may not be
obvious how to vectorize the
code.
The while Structure
 A while loop repeats as long as a
logical condition is true. Its general
syntax is

3.3.2 while condition


statements
end
LOOPS  The statements between the while
and the end are repeated as long as
the condition is true. A simple
example is
x = 8
while x > 0
When this code is run, the result
is
x =
8
5
3.3.2
2
-1
LOOPS
Those are glimpses to
programming in MATLAB.
If you want to know more, try to
get hold of some texts and

You might also like