Thanks to visit codestin.com
Credit goes to www.scribd.com

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

CHE 306 Lesson Note 3

The document discusses MATLAB programming using M-files. It explains that M-files allow running a series of commands all at once and come in two flavors: script files and function files. Script files are a series of commands saved in a file, while function files can accept inputs and return outputs like user-defined functions in other languages. The document provides examples of both script and function M-files.

Uploaded by

odubade opeyemi
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)
65 views58 pages

CHE 306 Lesson Note 3

The document discusses MATLAB programming using M-files. It explains that M-files allow running a series of commands all at once and come in two flavors: script files and function files. Script files are a series of commands saved in a file, while function files can accept inputs and return outputs like user-defined functions in other languages. The document provides examples of both script and function M-files.

Uploaded by

odubade opeyemi
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

LESSON 3: objective of this


section is to learn
MATLAB how to 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 greatly expand
MATLAB’s problem-solving capabilities.
M-FILES  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
extension.
 M-files come in two flavors: script files
and function files.
A script file is merely a series of
MATLAB commands that are saved on a
file.
They are useful for retaining a series of
M-FILES commands that you want to execute on
more than one occasion.
(A) SCRIPT 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.
Solution: Open the editor with the menu
M-FILES selection: File, New, M-file. Type in the
following statements to compute the
(A) SCRIPT FILES 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)
* t)

 Save the file as scriptdemo.m. 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
M-FILES
had typed each of its lines in the
command window.
(A) SCRIPT 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.
As we will see in the following section,
this is an important distinction between
M-FILES scripts and functions.

(A) SCRIPT FILES


Function files are M-files that start with
the word function.
In contrast to script files, they can accept
input arguments and return outputs.
M-FILES Hence, they are analogous to user-
defined functions in programming
(B) FUNCTION languages such as Fortran, Visual Basic
FILES 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 lookfor command.
M-FILES Thus, you should include key descriptive
words related to the file on this line.
(B) FUNCTION The M-file should be saved as
FILES funcname.m.
The function can then be run by typing
funcname in the command window as
illustrated in the following example.
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 FreeFall as two
(B) FUNCTION different variables, your operating system
might not.
FILES
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 task.
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-file is that


FILES 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)
ans =
53.1878
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
>> lookfor bungee
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 have been


(B) FUNCTION 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 are said to
M-FILES be local and are erased after the function is
executed. In contrast, the variables in a
script retain their existence after the script
(B) FUNCTION is executed.
FILES
Function M-files can return more than one
result. In such cases, the variables
containing the results are comma-delimited
and enclosed in brackets.
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);
M-FILES mean = sum(x)/n;
stdev = sqrt(sum((x-mean).^2/(n-1)));

(B) FUNCTION  Here is an example of how it can be applied:


FILES >> y = [8 5 10 12 6 7.5 4];
>> [m,s] = stats(y)
m =
7.5000
s =
2.8137
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
M-FILES
(without comments) could have been split
into two functions and saved as a single M-
(C) file.
SUBFUNCTIONS 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
 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
M-FILES
command window and other functions and
scripts.
(C)  All the other functions (in this case, vel) are
SUBFUNCTIONS referred to as subfunctions.
 A subfunction is only accessible to the main
function and other subfunctions within the M-
file in which it resides. If we run
freefallsubfunc from the command window,
>> freefallsubfunc(12,68.1,0.25)
ans =
50.6175
However, if we attempt to run the
subfunction vel, an error message occurs:
M-FILES >> vel(12,68.1,.25)
??? Undefined function or method 'vel’
for input arguments of type 'double’.
(C)
SUBFUNCTIONS
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 to enter
and display information directly using the
3.2 command window.
INPUT-OUTPUT 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): ')
When this line is executed, the user is
3.2
INPUT-OUTPUT prompted with the message
Mass (kg):

If the user enters a value, it would then be


assigned to the variable m.
The input function can also return user
input as a string.
To do this, an 's' is appended to the
function’s argument list. For example,
name = input('Enter your name: ','s’)

The disp Function

3.2 This function provides a handy way to


display a value. Its syntax is
INPUT-OUTPUT
disp(value)

where value = the value you would like to


display. It can be a numeric constant or
variable, or a string message enclosed in
hyphens.
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 and disp functions for
3.2 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 control
INPUT-OUTPUT over the display of information.
A simple representation of its syntax is
fprintf('format', x, ...)

where format is a string specifying how


you want the value of the variable x to be
displayed.
 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 digits
3.2 with four digits to the right of the decimal
point along with a message, the statement
INPUT-OUTPUT
along with the resulting output would be:
>> fprintf('The velocity is %8.4f m/s\n', velocity)
The velocity is 50.6175 m/s

This example should make it clear how


the format string works.
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 a % and
recognizes that the following text is a
3.2 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 velocity,
MATLAB continues displaying the
character information (in our case the
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 provide a means to perform
actions such as skipping to the next line.
3.2 If we had omitted the code \n in the
INPUT-OUTPUT previous example, the command prompt
would appear at the end of the label m/s
rather than on the next line as would
typically be desired.
 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 It can also be used to display vectors and


INPUT-OUTPUT 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 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);

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
moving down to the end.
Because a strict sequence is highly
3.3 STRUCTURED
limiting, all computer languages include
PROGRAMMING
statements allowing programs to take
nonsequential paths. These can be
classified as:
 Decisions (or Selection). The branching of
flow based on a decision.
 Loops (or Repetition). The looping of flow
The if Structure.
 This structure allows you to execute a set of
statements if a logical condition is true. Its
general syntax is:
if condition
statements
3.3.1 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 is passing:
function grader(grade)
% grader(grade):
% determines whether grade is passing
% input:
% grade = numerical value of grade (0-
100)
% output:
% displayed message
3.3.1 DECISIONS if grade >= 60
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
This structure is called a single-line if.
3.3.1 DECISIONS 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 execute a second set if the
condition is false.
3.3.1 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.
This type of structure often occurs when
we have more than two options for a
3.3.1 DECISIONS particular problem setting.
For such cases, a special form of decision
structure, the if...elseif has been
developed.
It has the general syntax
if condition1
statements1
elseif condition2
statements2
elseif condition3
statements3
3.3.1 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 branching is based on the
3.3.1 DECISIONS 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 the prescribed values.
It has the general syntax
switch testexpression
case value1
statements1
case value2
statements2
. . .
otherwise
3.3.1 DECISIONS statements
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 for
incorporating default values into your
functions.
3.3.1 DECISIONS
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 section,
we developed a function freefall, which
had three arguments:
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.
Therefore, it would be nice to have the
3.3.1 DECISIONS 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
constructs to incorporate default values as
well as error messages your functions.
The following code illustrates how this
can be done for freefall:
function v = freefall2(t, m, cd)
% freefall2: bungee velocity with
3.3.1 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)
% 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;
3.3.1 DECISIONS end
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
arguments passed by the user.
 Here is a command window session showing
the results:
>> freefall2(12,68.1,0.25)
ans =
50.6175
>> freefall2(12,68.1)
ans =
48.8747
3.3.1 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 =
48.8747
3.3.1 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.
 A for loop ends after a specified number of
3.3.2 repetitions.
 A while loop ends on the basis of a logical
condition.
LOOPS
The for...end Structure.
 A for loop repeats statements a specific
number of times. Its general syntax is
for index = start:step:finish
statements
end
 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 index is less
than or equal to the finish, the program executes
3.3.2 the statements.
 When it reaches the end line that marks the end
of the loop, the index variable is increased by
LOOPS 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.
Note that if an increment of 1 is desired
(as is often the case), the step can be
dropped. For example,
for i = 1:5
disp(i)
3.3.2 end

When this executes, MATLAB would


LOOPS 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 any other numeric
value. It does not have to be an integer,
nor does it have to be positive.
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 implement


this calculation can be developed as
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 = 120).
3.3.2
Notice what happens if n = 0.
For this case, the for loop would not
LOOPS
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 to repeat statements
3.3.2 a specific number of times.
 Because of MATLAB’s ability to operate
LOOPS 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 form as


3.3.2
t = 0:0.02:50;
y = cos(t);
LOOPS
It should be noted that for more complex
code, it may not be obvious how to
vectorize the code.
That said, wherever possible, vectorization
is recommended.
The while Structure
 A while loop repeats as long as a logical
condition is true. Its general syntax is

while condition
3.3.2 statements
end

 The statements between the while and the end


LOOPS are repeated as long as the condition is true. A
simple example is
x=8
while x > 0
x = x - 3;
disp(x)
end
When this code is run, the result is

x =
8
5
2
3.3.2
-1

LOOPS Those are glimpses to programming in


MATLAB.
If you want to know more, try to get hold
of some texts and manual on MATLAB as
Engineering packages.

You might also like