Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Section 6:

Logical Functions and Control Structures

Computer programs (not just MATLAB) can be categorized into one of three
structures: sequences, selection structures, and repetition structures (see Fig 6.1).
Up to this point, all commands have been written in sequences.

Sequence Selection Repetition

Figure 6.1 Programming structures in MATLAB

Logical Operators
Selection and repetition structures used in MATLAB depend on relational
operators, used to compare two matrices of equal size. Comparisons are either
true or false. MATLAB (along with most other computer programs) use the
number 1 for true and 0 for false. Consider the expressions
>> x = 5;
>> y = 1;
>> x<y returns ans = 0 meaning false

Of course, variables with MATLAB represent matrices. Logical operators perform


an element by element comparison. Consider the expressions
>> x = 1:5;
>> y = [-2 0 2 4 6];
>> x<y returns ans = 0 0 0 0 1
That is, only the last comparison is true.

6-1
The six relational operators within MATLAB include:
Operator Interpretation
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
~= not equal to

MATLAB also allows for the combination of comparisons wityh the logical
operators:
Operator Interpretation
& and
~ not
| or

As an example,
>> x = 5;
>> y = 1;
>> z = 7;
>> x<y & x<z returns ans = 0 meaning false
>> x<y | x<z returns ans = 1 meaning true

Selection Structures
A simple if statement has the following form:
if comparison
statements
end
If the comparison is true, the statements between the if statement and end
statement are executed. It is good practice to indent the statements within the if
structure for readability.

6-2
Practice Problem 6.1
Create a function accepts 𝑎, 𝑏, 𝑐, and calculates the real roots of a quadratic
equation
𝑎𝑥 2 + 𝑏𝑥 + 𝑐 = 0
Recall that the roots are
−𝑏 ± √𝑏 2 − 4𝑎𝑐
𝑥1 , 𝑥2 =
2𝑎
2
Use the function for 𝑥 − 6𝑥 + 8 = 0, where we all can factor to get 𝑥 = 2 and
𝑥 = 4 as solutions

While the simple if statement executes a series of statements if a condition is


true, the else clause executes another set if the comparison is false.
if comparison
statements
else
other statements
end

The elseif statement allows for execution based on multiple criteria to be


checked.
if comparison 1
statements
elseif comparison 2
statements 2
else
other statements
end

The if/else structure is best confined to scalars.

6-3
Practice Problem 6.2
Create a function that accepts a test score and determines a letter grade:

Grade Score
A ≥ 90
B ≥80 and <90
C ≥70 and <80
D ≥60 and <70
F <60

The if/elseif/else structure can be nested to provide increased versatility.


if comparison 1
if comparison 1A
statements 1A
elseif comparison 1B
statements 1B
else
other statements 1
end
elseif comparison 2
if comparison 2A
statements 2A
elseif comparison 2B
statements 2B
else
other statements 2
end
else
still other statements
end

6-4
Practice Problem 6.3
Create script that quires the user for coordinates of a point
(x1, y1) and determines the quadrant (1, 2, 3, or 4) of a line
extending from the origin to that point.

The switch/case structure is similar to the if/elseif/else structure for distinct


values. While they can be used interchangeably, the switch/case structure is
easier to read and interpret.
switch variable
case option 1
statements 1
case option 2
statements 2
case option 3
statements 3
otherwise
other statements
end

Practice Problem 6.4


The number of credits required for engineering undergraduate degrees are:
1. Civil Engineering 131
2. Chemical Engineering 133
3. Electrical Engineering 129
4. Mechanical Engineering 132
Write a script that uses the input command to accept a number associated with
an engineering program. Use the switch/case structure to send the minimum
number of credits required for graduation to the command window.

6-5
Practice Problem 6.5
Modify the previous example to use the menu command.

Find Command
The find command searches a matrix and identifies which elements in that matrix
meet a given criteria. The find command can often be used more efficiently in
place of traditional selection structures. Consider the following matrix containing
the heights of applicants for a Military Academy,
height = [63, 67, 65, 72, 69, 78, 75]
The find command will identify the index number of the matrix that meets the
specified criteria. Since applicants are required to be at least 5’6” (66”),
acceptable applicants are
accept = find (height >= 66)
which returns
accept = 2 4 5 6 7
Further,
height(accept)
returns
accept = 67 72 69 78 75
Consider a larger matrix, where each row contains the applicant height and age.
applicants = [63, 18; 67, 19; 65, 18; 72, 20; 69, 36; 78, 43; 75, 12]
Since applicants are required to be at least 5’6” (66”), acceptable applicants are
pass = find (applicants(: ,1) >= 66 && applicants(: ,2)>=18 …
&& applicants(: ,2)< 35)
which returns
pass = 2
4
5

6-6
Practice Problem 6.6
The height ℎ of a rocket (in meters) as a function of time 𝑡 (in seconds) can be
represented by the following equation:
ℎ = 2.13𝑡 2 − 0.0013𝑡 4 + 0.000034𝑡 4.751
Create a vector of time from 0 to 70 at 0.5-second intervals. Use the find function
to determine when the rocket hits the ground to within 0.5 seconds.

Repetition Structures: For Loops


Loops are used to repeat a set of instruction multiple times.
A for loop is the easiest choice when the number of repetitions is known. It has
the following form:
for index = [matrix]
statements to be executed
end
The loop is executed one for each element of the index matric identified in the
first line. For example,
for k = [1, 3, 7]
k
end
This code returns
k=1
k=3
k=7
The index matrix can be defined with the colon operator as well
for k = 1:3
a = 5^k
end
This code returns
a=5
a = 25
a = 125

6-7
Practice Problem 6.7
Although it would be better to use MATLAB’s vector capability, use a for loop to
create a degrees-to-radians table.

Practice Problem 6.8


Use a for loop to sum the elements in the following vector:
𝑥 = [1, 23, 43, 72, 87, 56, 98, 33]
Check your answer with the sum function.

Practice Problem 6.9


A Fibonacci sequence is composed of elements created by adding the previous
two elements. The simplest Fibonacci sequence starts with 1,1 and proceeds as
follows:
1, 1, 2, 3, 5, 8, 13, etc.
Prompt the user for any two starting numbers. Then use a for loop to create a 15-
value Fibonacci.

It is common to nest loops and selection statements


for index = [matrix]
statements to be executed
if comparison 1
statements
elseif comparison 2
statements 2
else
other statements
end
end
In order to follow the code, indenting becomes nearly essential.

6-8
Practice Problem 6.10
A cantilever beam is shown below. Beam width, w
x General Location Force, F

Force Location, a Beam height, h

Length, L

The deflection of a general location on the beam is given as


2𝐹𝑥 2
𝛿= (𝑥 − 3𝑎) if 𝑥≤𝑎
𝐸𝑤ℎ3
2𝐹𝑎2
𝛿= (𝑎 − 3𝑥) if 𝑥>𝑎
𝐸𝑤ℎ3
Plot the deflected shape of a steel (𝐸 = 30×106 psi) cantilever beam with 𝐹 = 5 lbs,
𝑎 = 10 in, 𝐿 = 18 in, ℎ = 0.375 in, and 𝑤 = 0.75 in.

Repetition Structures: While Loops


A while loop is similar to for loop, except that MATLAB decides how many times
to repeat the loop based on some criterion. The format for the while loop is
while criterion
statements to be executed
end
For example
k = 0;
while k < 3
k=k+1
end
which returns
k=1
k=2
k=3

6-9
Note that the variable used to control the while loop must be updated every time
through the loop. If not, an endless loop results. To manually exit a calculation,
type ctrl-c.
Consider another example
scores = [76, 92, 45, 86, 90, 82, 98, 97];
count = 0;
k = 0;
while k < length(scores)
k = k + 1;
if scores(k)>90
count = count + 1;
end
end
disp(count)

Practice Problem 6.11


Write MATLAB script to determine how many of the first integers would have to
be multiplied together to exceed a product of 1500.

Practice Problem 6.12


Write a MATLAB function my_factorial(n) that calculates the product of all
positive integers less than or equal to n.

Practice Problem 6.13


The sine of a number 𝑥 can be approximated with an infinite series:

(−1)𝑛 2𝑛+1
sin(𝑥) = ∑ 𝑥
(2𝑛 + 1)!
𝑛=0
Write a MATLAB function my_sin(x,tol) that uses the infinite series. Allow the
convergence tolerance argument to be optional. Use a default of tol of 0.01 and
do not use the factorial function.

6-10
Break and Continue
The break command can be used to terminate a loop prematurely, while the
comparison criterion is still true. Here’s an example
n = 0;
while n < 10
n = n + 1;
a = input(‘Enter a value greater than 0: ’)
if a < 0
disp(‘You should’ve entered a positive number ’)
disp(‘This program will not terminate ’)
break
end
disp(‘The natural log of that number is ’)
disp(log(a))
end

The continue command is similar to break, however instead of terminating the


loop, the code just skips to the next pass. Consider a more polite script
n = 0;
while n < 10
n = n + 1;
a = input(‘Enter a value greater than 0: ’)
if a < 0
disp(‘You should’ve entered a positive number ’)
disp(‘Try again ’)
continue
end
disp(‘The natural log of that number is ’)
disp(log(a))
end
If loops are nested, the continue command applies to the loop in which the
statement was executed.

6-11
Animations
MATLAB can be used to create animated graphics by continually erasing and then
redrawing objects on the screen, making incremental changes with each redraw.
Here’s an example:
close all; clear all; clc
n = 20;
s = .02;
x = rand(n,1)-0.5;
y = rand(n,1)-0.5;
figure
axis([-1 1 -1 1])
axis square
grid off
hold on
while min(abs([x;y]))<1
x = x+s*rand(n,1);
y = y+s*rand(n,1);
plot(x,y,'.','MarkerSize', 15, 'tag', 'update') %tags objects as “update”
pause(.05)
delete(findobj('tag', 'update')) %erases all objects tagged as “update”
end

Practice Problem 6.14


Write a MATLAB script to animation of a fully rotating crank of length 𝑅

The coordinates of the endpoint as a function of crank angle 𝜃 are


𝑥𝐵 = 𝑥𝐴 + 𝑅𝑐𝑜𝑠𝜃 and 𝑦𝐵 = 𝑦𝐴 + 𝑅𝑐𝑜𝑠𝜃

6-12
6-13

You might also like