0% found this document useful (0 votes)
47 views13 pages

MATLAB Selection Structures Overview

This document discusses logical functions and control structures in computer programs including MATLAB. It covers sequence, selection, and repetition structures. Logical operators allow comparisons to return true or false results. Selection structures like if/else and switch/case allow for conditional execution. Repetition structures like for loops repeat a block of code a specified number of times. Examples are provided to illustrate logical operators, selection structures, and for loops.

Uploaded by

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

MATLAB Selection Structures Overview

This document discusses logical functions and control structures in computer programs including MATLAB. It covers sequence, selection, and repetition structures. Logical operators allow comparisons to return true or false results. Selection structures like if/else and switch/case allow for conditional execution. Repetition structures like for loops repeat a block of code a specified number of times. Examples are provided to illustrate logical operators, selection structures, and for loops.

Uploaded by

Hassan Azouz
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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

Common questions

Powered by AI

Indentation is crucial when using nested control structures in MATLAB to improve code readability and comprehension. Proper indentation visually distinguishes between different levels of control structures, such as nested loops or if/elseif/else statements, allowing programmers to easily follow the logic flow and understand how different blocks of code are related. This practice reduces errors and aids in debugging by making it obvious which statements belong to which control structures, thus leading to more maintainable and clear code .

The switch/case structure in MATLAB offers advantages over the if/elseif/else structure mainly in terms of readability and maintainability. It is best utilized when dealing with multiple distinct, potentially discrete values. Whereas if/elseif/else can become cumbersome and unwieldy with many conditions, switch/case provides a clear and structured approach, allowing for easier understanding and management of the code. Each 'case' represents a potential value of a variable, and the structure allows straightforward execution of different statements for each 'case,' leading to cleaner and more organized code .

Nested loops and selection statements significantly increase the complexity of MATLAB programming due to interplay between multiple control structures. When loops are nested, each inner loop must complete its iterations before the outer loop progresses, which requires careful consideration of the order of execution and potential interactions between loops. Similarly, nested if/elseif/else statements can lead to complex logical pathways, making it challenging to track code execution and state. In practical terms, such as managing variables across nested structures, programmers need to be mindful of scope and ensure that logic is sound to prevent errors, inefficient performance, or unintended behavior .

MATLAB handles infinite series approximation by summing terms iteratively until convergence criteria are met, typically involving tolerances to determine sufficient accuracy. Implementing such approximations necessitates addressing precision and performance considerations. For example, approximating the sine function using its Taylor series requires alternating term signs and factorial coefficients. Programmers must implement logic to truncate the series based on specified tolerance, iterating only as long as new terms significantly contribute to summation. This requires carefully handling potential overflow in factorial calculations and ensuring that series convergence is adequately parameterized with tolerances .

An efficient way to create animations in MATLAB involves using a loop to iteratively update object properties, and using the pause and delete functions to manage frame-by-frame progression. This process begins by setting up the graphical environment and creating initial plot objects. Within the loop, objects are redrawn with updated data to reflect motion, tagged for identification, and then deleted before the next iteration, ensuring that memory usage remains efficient. The pause function regulates update speed for smooth visual flow. This method allows for dynamic real-time animation across multiple frames, such as updating the position of points within a bounded plot area .

Yes, the find command can be more efficient than traditional selection structures in MATLAB for tasks that involve identifying elements in a matrix that meet specific criteria. For instance, instead of using a loop to iterate through the elements of a matrix to find positions that satisfy a condition, the find command can directly return indices of elements that match the condition in a single operation. For example, given a matrix of applicant heights and ages, the command pass = find (applicants(:,1) >= 66 & applicants(:,2) >=18 & applicants(:,2) < 35) efficiently identifies suitable applicants based on height and age conditions without individually checking each element .

MATLAB interprets logical comparisons of matrices by performing element-wise comparisons, and the results depend on whether each individual comparison is true or false. These comparisons leverage relational operators, and MATLAB returns a matrix of the same dimensions containing binary values: 1 for true and 0 for false. For example, given vectors x = [1:5] and y = [-2 0 2 4 6], the expression x<y returns a result of [0 0 0 0 1], indicating that only the last element comparison yields a true value. This approach allows for comprehensive checks across matrix elements without the need for loops .

A while loop is more suitable than a for loop in scenarios where the number of iterations cannot be predetermined and is instead based on a condition that must be continually checked. This is particularly useful for processes that run until a specific condition is met, rather than for a fixed number of iterations. For instance, when iterating through a list until finding an element that meets a certain criterion or repeating calculations until a convergence threshold is reached, a while loop ensures that the loop exits when the condition changes to false, providing flexibility in termination criteria .

The break and continue commands are significant for controlling flow within MATLAB loops. The break command prematurely exits a loop when a particular condition is met while avoiding executing the remainder of the loop's body, which is essential for stopping loops early based on dynamic criteria. Conversely, the continue command skips the current iteration and proceeds to the next cycle of the loop. This is useful for bypassing specific iterations that meet certain conditions without terminating the loop, allowing selective processing of elements within iterative structures. These commands offer finer control over loop execution .

Logical operators in MATLAB, such as & (and), ~ (not), and | (or), enhance the functionality of selection and repetition structures by allowing for complex conditions to be evaluated. These operators are used to combine multiple relational operator conditions. For example, the expression x<y & x<z evaluates to zero (false) as a whole if any single comparison is false. This capability is crucial in control structures, like if/else statements or loops, to determine which code path to execute based on multiple criteria. By using logical operators, code can be more concise and expressive, addressing multiple conditions simultaneously .

You might also like