You are on page 1of 45

Week 04:

1 – Structured Programming – Decisions


2 – Structured Programming – Loops
3 – MATLAB Functions & Programs
Applied Numerical Methods and
Programming in Engineering
00 - Introduction
› In the previously studied scripts and functions files, the
statements are executed in Sequence( the program
statements are executed line by line starting at the top of the
function and moving down to the end).
› This is not always desirable, and on many occasions, we need
to make choices or take decisions.
› Therefore, all computer languages include statements allowing
programs to take nonsequential paths (Structured
programing). These can be classified as
– Decisions (or Selection): The branching of flow based on a decision.
– Loops (or Repetition): The looping of flow to allow statements to be
repeated.

DR. MOHAMAD A. ALKHALIDI 2


00 - Introduction

DR. MOHAMAD A. ALKHALIDI 3


01 - Structured Programming – Decisions
› Decisions and Selections:
– Structured programming in MATLAB allows us to make decisions or selections
based on conditions of the program.
– Decisions in MATLAB are based on the result of logical and relational
operations and are implemented with "if", "if…else", and "if…elseif" structures.
– Selections in MATLAB are based on comparisons with a test expression and
are implemented with "switch" structures.
– When we need to make choices as such as whether statements are executed
or not, and/or how to choose between or among statements, the statements
that accomplish this are called selection or branching statements.
› MATLAB has two basic statements that allow us to make choices:
– the if statement:
› The if statement has optional else and elseif clauses for branching.
› The if statement uses expressions that are logically true or false. These expressions use
relational and logical operators.
– the switch statement.
– MATLAB also has "is" functions that test whether an attribute is true or not; these can be used
with the selection statements.

DR. MOHAMAD A. ALKHALIDI 4


01 - Structured Programming – Decisions
› if statement:
– The if statement chooses whether another statement, or group of
statements, is executed or not. The general form of the if statement
is:
========================
if condition
statement/action
end
=====================
– The condition is a relational (logical) expression that is conceptually,
or logically, true or false.
– The statement/action is a statement, or a group of statements, that
will be executed if the condition is true. When the if statement is
executed, first the condition is evaluated.
› If the value of the condition is true, the action will be executed;
› if not, the action will not be executed.

DR. MOHAMAD A. ALKHALIDI 5


01 - Structured Programming – Decisions
› if statement:
– The action can be any number of statements until the reserved
word end; the action is naturally bracketed by the reserved
words if and end.
› Note that this is different from the "end" that is used as an index into a
vector or matrix. The action is usually indented to make it easier to see.
– Logical Conditions: The simplest form of the condition is a single
relational expression that compares two values as in value1
relation value2

DR. MOHAMAD A. ALKHALIDI 6


01 - Structured Programming – Decisions
› if statement:
› The values can be constants, variables, or expressions and the relation is
one of the relational operators listed below
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

DR. MOHAMAD A. ALKHALIDI 7


01 - Structured Programming – Decisions
Example 1:

x = input('What is the value of x?, x = ');


if x < 0
x = 0 Example 3:
end
Prompt the user for a number and print its sqrt, and If the user entered a negative number, tell

the user and change it

1. Prompt the user for a number:


xample 2:
num = input ( 'Please enter a number : ' ) ;
1. Prompt the user for a number and print its sqrt
2. If the user entered a negative number, tell the user and change it
num = input ( ' Please enter a number : ' ) ;
if num < 0
2. If condition: the user entered a negative number, change it
disp ( ' OK, we''ll use the absolute value')
if num < 0 end
num = 0; OK, we'll use the absolute value
end

num = abs (num) ;


3. Display the results fprintf ( 'The sqrt of %.1f is% .1f\n', num, sqrt (num))
The sqrt of 25.0 is 5.0
fprintf('The sqrt of % .1f is % .1f\n ', num, sqrt (num))

DR. MOHAMAD A. ALKHALIDI 8


01 - Structured Programming – Decisions
› if statement:
– Representing Logical True and False:
› In MATLAB, the concept of false is represented by the value of 0, and the
concept of true is represented by any nonzero value.
› This can lead to some strange logical expressions. For example:

DR. MOHAMAD A. ALKHALIDI 9


01 - Structured Programming – Decisions
› if statement:
– Error Function:
› We can use the error function, which has the syntax; error(msg), to display
a message that indicate error.
› When this function is encountered, it displays the text message msg,
indicates where the error occurred, and causes the M-file to terminate and
return to the command window.
› An example of its use would be where we might want to terminate an M-file
to avoid a division by zero. The following M-file illustrates how this could be
done:

› If a nonzero argument is used, the division would be implemented successfully


as in
– errortest(10)
– ans =
– 0.1000

DR. MOHAMAD A. ALKHALIDI 10


01 - Structured Programming – Decisions
› Logical Operator:
– ~x (Not): Used to perform logical negation on an expression
› If the expression is true, the result is false.
› If the expression is false, the result is true.
– x & y (And): Used to perform a logical conjunction on two
expressions: expression1 & expression2
› If both expressions evaluate to true, the result is true.
› If either or both expressions evaluates to false, the result is false.
– x || y (Or): Used to perform a logical disjunction on two
expressions: expression1 || expression2
› If either or both expressions evaluate to true, the result is true.

DR. MOHAMAD A. ALKHALIDI 11


01 - Structured Programming – Decisions
› Logical Operator:
– The table below summarizes all possible outcomes for each of
these operators.
› Just as for arithmetic operations, there is a priority order for evaluating
logical operations.
› These are from highest to lowest: ~, &, and ||.
› In choosing between operators of equal priority, MATLAB evaluates them
from left to right.
› As with arithmetic operators, parentheses can be used to override the
priority order.

DR. MOHAMAD A. ALKHALIDI 12


01 - Structured Programming – Decisions
Example: If a = -1, b = 2, x = 1, and y = 'b', evaluate whether the following is true or false

a * b > 0 & b == 2 & x > 7 | ~(y > 'd')

○ Substitute the values for the variables: −1 * 2 > 0 & 2 = = 2 & 1 > 7 || ~('b' > 'd')

○ The first thing that MATLAB does is to evaluate any mathematical expressions. In
this example, there is only one: −1 * 2: −2 > 0 & 2 == 2 & 1 > 7 || ~('b' > 'd')

○ Next, evaluate all the relational expressions

−2 > 0 & 2 == 2 & 1 > 7 || ~('b' > 'd')


F & T & F || ~ F

○ At this point, the logical operators are evaluated in priority order. Since the ~ has
highest priority, the last expression (~F) is evaluated first to give: F & T & F || T

○ The & operator is evaluated next. Since there are two, the left-to-right rule is
applied and the first expression (F & T) is evaluated: F & F || T

○ The & again has highest priority: F || T

○ Finally, the || is evaluated as true.

DR. MOHAMAD A. ALKHALIDI 13


01 - STRUCTURED
PROGRAMMING –
DECISIONS
The if...else Structure:
if condition
This structure allows
you to execute a set of
statements if a logical
statements1
condition is true and
to execute a second
set if the condition is
else
false.
Its general syntax is statements2
end

DR. MOHAMAD A. ALKHALIDI 14


01 - STRUCTURED if condition1
PROGRAMMING – statements1
DECISIONS elseif condition2
The if...elseif Structure:
It often happens that
statements2
the false option of an elseif condition3
if...else structure is
another decision. This statements3
type of structure often
occurs when we have ·
more than two options
for a particular problem ·
setting.
·
For such cases, a
special form of decision else
structure, the if...elseif
has been developed. statementselse
Its general syntax is end
DR. MOHAMAD A. ALKHALIDI 15
01 - Structured Programming – Decisions
› Decisions are made in MATLAB using "if" structures, which
may also include several "elseif" branches and possibly a
catch-all else branch.
› Deciding which branch runs is based on the result of
conditions which are either true or false.
› If an if tree hits a true condition, that branch (and that branch
only) runs, then the tree terminates.
› If an if tree gets to an else statement without running any
prior branch, that branch will run.
› Note - if the condition is a matrix, it is considered true if and
only if all entries are true (or non-zero).

DR. MOHAMAD A. ALKHALIDI 16


01 - Structured Programming – Decisions
› Example: For a scalar, the built-in MATLAB sign function
returns the sign of its argument (−1, 0, 1). Here’s a
MATLAB session that illustrates how it works:
>> sign(25.6)
ans =
1
>> sign(−0.776)
ans =
−1
>> sign(0)
ans =
0

DR. MOHAMAD A. ALKHALIDI 17


01 - Structured Programming – Selections
› Selections:
– Selections are made in MATLAB using "switch structures", which
may also include a catch-all otherwise choice.
– Deciding which branch runs is based on comparing the value in
some test expression with values attached to different cases.
– If the test expression matches the value attached to a case, that
case’s branch will run.
– If no cases match and there is an otherwise statement, that
branch will run.
› switch, case, otherwise: Execute one of several groups of statements

DR. MOHAMAD A. ALKHALIDI 18


01 - Structured Programming – Selections

Syntax:
switch switch_expression
case case_expression
statements
case case_expression
statements
...
otherwise
statements
end

DR. MOHAMAD A. ALKHALIDI 19


01 - Structured Programming – Selections

DR. MOHAMAD A. ALKHALIDI 20


01 - Structured Programming – Selections
› 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.
– A default value is a number that is automatically assigned if the
user does not pass it to a function.
– As an example, recall that earlier in this chapter, we developed a
function freefall, which had three arguments:
v = freefall(t,m,cd)

DR. MOHAMAD A. ALKHALIDI 21


01 - Structured Programming – Selections
› Variable Argument List
› 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 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 messages into your
functions.
– The following code illustrates how this can be done for freefall:

DR. MOHAMAD A. ALKHALIDI 22


01 - Structured Programming – Selections

DR. MOHAMAD A. ALKHALIDI 23


02 - Structured Programming – Loops
› Loops:
– Another programming structure involves loops, where the same
lines of code are run several times. There are two types of loop:
› A for loop ends after a specified number of repetitions established by the
number of columns given to an index variable.
› A while loop ends on the basis of a logical condition.
– One common way to use a for…end structure is:
for index = start:step:finish
statements
end

› where the index variable takes on successive values in the vector created
using the ":" operator.

DR. MOHAMAD A. ALKHALIDI 24


02 - Structured Programming – Loops
› 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 the statements.
– 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.

DR. MOHAMAD A. ALKHALIDI 25


02 - Structured Programming – Loops
› Example: Develop an M-file
to compute the factorial
– 0! = 1
– 1! = 1
– 2! = 1 × 2 = 2
– 3! = 1 × 2 × 3=6
– 4! = 1 × 2 × 3 × 4 = 24
– 5! = 1 × 2 × 3× 4× 5=
120

DR. MOHAMAD A. ALKHALIDI 26


02 - Structured Programming – Loops
› Vectorization:
– Sometimes, it is more
efficient to have MATLAB
for loop
perform calculations on an Vectorization

entire array rather than i = 0; t =


0:0.02:50;
for t =
processing an array element 0:0.02:50 y =
by element. i = i + 1; cos(t);
– This can be done through y(i) =
"vectorization": cos(t);
end

DR. MOHAMAD A. ALKHALIDI 27


02 - Structured Programming – Loops
› Pre-allocation of Memory:
– MATLAB automatically increases the size of arrays every time
you add a new element.
– This can become time consuming when you perform actions
such as adding new values one at a time within a loop.
– For example, here is some code that sets value of elements of y
depending on whether or not values of t are greater than one:
t = 0:.01:5;
for i = 1:length(t)
if t(i)>1
y(i) = 1/t(i);
else
y(i) = 1;
end
end
DR. MOHAMAD A. ALKHALIDI 28
02 - Structured Programming – Loops
› Pre-allocation of Memory:
– For this case, MATLAB must resize y every time a new value is
determined.
– The following code pre-allocates the proper amount of memory
by using a vectorized statement to assign ones to y prior to
entering the loop:

› Thus, the array is only sized once.


› In addition, pre-allocation helps reduce memory fragmentation, which also
enhances efficiency.

DR. MOHAMAD A. ALKHALIDI 29


02 - Structured Programming – Loops
› The while Structure:
– A while loop repeats as long as a logical condition is true.
– Its general syntax is
while condition
statements
end
– 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
x = x − 3;
disp(x)
End

DR. MOHAMAD A. ALKHALIDI 30


02 - Structured Programming – Loops
› The while...break Structure
– Although the while structure is extremely
useful, the fact that it always exits at the
beginning of the structure on a false result is
somewhat constraining.
– For this reason, languages such as Fortran 90
and Visual Basic have special structures that
allow loop termination on a true condition
anywhere in the loop.
– Although such structures are currently not
available in MATLAB, their functionality can be
mimicked by a special version of the while while (1)
loop. statements
– The syntax of this version, called a if condition, break, end
while...break structure, can be written as statements
end
DR. MOHAMAD A. ALKHALIDI 31
02 - Structured Programming – Loops
› The while...break Structure
– where break terminates execution of the loop. Thus, a single line
if is used to exit the loop if the condition tests true.
– Note that as shown, the break can be placed in the middle of the
loop (i.e., with statements before and after it).
– Such a structure is called a midtest loop.
– If the problem required it, we could place the break at the very
beginning to create a pretest loop.
while (1)
If x < 0, break, end
x = x − 5;
end

DR. MOHAMAD A. ALKHALIDI 32


02 - Structured Programming – Loops
› The while...break Structure
– 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 a mechanism.
› Otherwise, it would become a so-called infinite loop that would never
stop.
› Alternatively, we could also place the if...break statement at the very end
and create a posttest loop,
while (1)

x = x − 5;
if x < 0, break, end
end

DR. MOHAMAD A. ALKHALIDI 33


02 - Structured Programming – Loops
› The while...break Structure
– It should be clear that, in fact, all three structures are really the
same.
– That is, depending on where we put the exit (beginning, middle,
or end) dictates whether we have a pre-, mid- or posttest.
› The pause Command
– There are often times when you might want a program to
temporarily halt.
– The command pause causes a procedure to stop and wait until
any key is hit.

DR. MOHAMAD A. ALKHALIDI 34


02 - Structured Programming – Loops
› The pause Command
– The pause can also be formulated as pause(n), in which case the
procedure will halt for n seconds.

DR. MOHAMAD A. ALKHALIDI 35


03 - MATLAB Functions & Programs
› NESTING AND INDENTATION:
– The roots of a quadratic equation
› f(x) = ax2 + bx + c
› can be determined with the quadratic formula
−𝑏𝑏± 𝑏𝑏2 −4𝑎𝑎𝑎𝑎
– 𝑥𝑥 =
2𝑎𝑎
– Develop a function to implement this formula given values of the
coefficients.
› Top-down design provides a nice approach for designing an algorithm to
compute the roots.
› This involves developing the general structure without details and then refining
the algorithm.
› To start, we first recognize that depending on whether the parameter a is zero,
we will either have "special" cases (e.g., single roots or trivial values) or
conventional cases using the quadratic formula.
› This "big-picture' version can be programmed as

DR. MOHAMAD A. ALKHALIDI 36


03 - MATLAB Functions & Programs
– Next, we develop refined
code to handle the "special"
cases: %special
if b ~= 0
cases

%single root
r1 = -c / b
else
%trivial solution
disp('Trivial solution. Try again')
end

DR. MOHAMAD A. ALKHALIDI 37


03 - MATLAB Functions & Programs
– And we can develop refined code to handle the quadratic
formula cases: %quadratic formula
d = b ^ 2 - 4 * a * c;
if d >= 0
%real roots
r1 = (-b + sqrt(d)) / (2 * a)
r2 = (-b - sqrt(d)) / (2 * a)
else
%complex roots
r1 = -b / (2 * a)
i1 = sqrt(abs(d)) / (2 * a)
r2 = r1
i2 = -i1
end

DR. MOHAMAD A. ALKHALIDI 38


03 - MATLAB Functions & Programs
– We can then merely
substitute these blocks
back into the simple
'big-picture' framework
to give the final result:

DR. MOHAMAD A. ALKHALIDI 39


03 - MATLAB Functions & Programs
› PASSING FUNCTIONS TO M-FILES: Anonymous Functions
– Anonymous functions allow us to create a simple function
without creating an M-file.
– They can be defined within the command window with the
following syntax:
=================================
fhandle = @(arglist) expression
=================================
› fhandle = the function handle you can use to invoke the function,
› arglist = a comma separated list of input arguments to be passed to the
function, and
› expression = any single valid MATLAB expression
– f1=@(x,y) x^2 + y^2;

DR. MOHAMAD A. ALKHALIDI 40


03 - MATLAB Functions & Programs
› PASSING FUNCTIONS TO M-FILES: Anonymous Functions
– Aside from the variables in its argument list, an anonymous
function can include variables that exist in the workspace where
it is created.
› For example, we could create an anonymous function f (x)
= 4x2 as
>> a = 4;
>> b = 2;
>> f2=@(x) a*x^b;
>> f2(3)
ans = 36

DR. MOHAMAD A. ALKHALIDI 41


03 - MATLAB Functions & Programs
› PASSING FUNCTIONS TO M-FILES: Anonymous Functions
– Note that if subsequently we enter new values for a and b, the
anonymous function does not change:
› >> a = 3;
› >> f2(3)
› ans = 36
– 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.

DR. MOHAMAD A. ALKHALIDI 42


03 - MATLAB Functions & Programs
› PASSING FUNCTIONS TO M-FILES: Function Functions
– Function functions are functions that operate on other functions
which are passed to it as input arguments.
– The function that is passed to the function “function“ is referred to as
the passed function.
– A simple example is the built-in function fplot, which plots the graphs
of functions.
› A simple representation of its syntax is fplot(func,lims)
– func is the function being plotted between the x-axis limits specified by lims = [xmin
xmax].
– For this case, func is the passed function.
– This function is "smart" in that it automatically analyzes the function
and decides how many values to use so that the plot will exhibit all the
function's features.

DR. MOHAMAD A. ALKHALIDI 43


03 - MATLAB Functions & Programs
› PASSING FUNCTIONS TO
M-FILES: Function
Functions
– Here is an example of how
fplot can be used to plot the
velocity of the free-falling
bungee jumper.
› The function can be created
with an anonymous function:
– >> vel=@(t)
sqrt(9.81*68.1/0.25)*tanh(sqrt(
9.81*0.25/68.1)*t);
› We can then generate a plot
from t = 0 to 12 as
– >> fplot(vel,[0 12])

DR. MOHAMAD A. ALKHALIDI 44


03 - MATLAB Functions & Programs
› PASSING FUNCTIONS TO M-FILES: Passing Parameters
– If we want the parameters to take on new values, MATLAB offers
adding the term varargin as the function function's last input
argument.
– In addition, every time the passed function is invoked within the
function “function", the term varargin{:} should be added to the
end of its argument list (note the curly brackets).
– Here is how both modifications can be implemented for funcavg
(omitting comments for conciseness):
function favg = funcavg(f,a,b,n,varargin)
x = linspace(a,b,n);
y = f(x,varargin{:});
favg = mean(y);

DR. MOHAMAD A. ALKHALIDI 45

You might also like