0% found this document useful (0 votes)
5 views

Lecture_7_Boolean_Logic_and_Logical_Operations_cont

The document outlines the content of a class on Logic Flow Control in MATLAB, including upcoming assignments and exercises related to Boolean logic, for loops, while loops, and their applications. It provides specific examples of MATLAB scripts for user input, running sums, and factorial calculations. Additionally, it discusses the differences between for and while loops, as well as the efficiency of MATLAB's vector operations.

Uploaded by

bobpinnicle10
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lecture_7_Boolean_Logic_and_Logical_Operations_cont

The document outlines the content of a class on Logic Flow Control in MATLAB, including upcoming assignments and exercises related to Boolean logic, for loops, while loops, and their applications. It provides specific examples of MATLAB scripts for user input, running sums, and factorial calculations. Additionally, it discusses the differences between for and while loops, as well as the efficiency of MATLAB's vector operations.

Uploaded by

bobpinnicle10
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Logic Flow Control (cont.

)
(Chapter 4—Riggs)

Upcoming assignments:
 Assignment 5 (Boolean Logic & Logical Operations): due February 6, 11:59 PM
 EXAM 1 (February 18)

For today’s class:


 Create a new sub-folder, named Lecture7, in your ME2543 folder.
 Open MATLAB and change the path to the Lecture7 folder.
 Be sure to save all exercises done in class (we will be using .m files).
Review: In-Class Exercise

Problem 1. Write a script file (y_value.m) that does the following:

Ask the user to input a number x, then compute the appropriate value of y. If x < 0, display
an error message to the screen.

Data input command: x = input(‘Enter a value for x \n’)


Note: MATLAB will wait for you to enter a value at the command prompt.
\n tells MATLAB to begin a new line.

Error display command: disp(‘The value of x < 0’) (disp(‘Error’) also OK)
Review: In-Class Exercise, Cont’d.

This is one example of solution for Problem 1 (other solutions may also be
correct).

x = input(‘Enter a value for x \n’)

if (x < 0)
disp(‘The value of x < 0’)
elseif (x < 5)
y = sqrt(x)
else
y = ln(x)
end
for Loops

 Repeat executable statements a fixed number of times.

Basic Form:
Note: index tracks which iteration of
for index = n_initial : n_increment : n_final
the loop is being run.
executable code
It often directly affects the executable
end
code.
Where: n_initial = initial value of index (real or integer)
n_final = final value of index (real or integer)
n_increment = increment used between n_initial and n_final
for Loops

 Create new script file: Lecture7_Ex1.m

Single for loop:


Example: for i = 1 : 3 Hello world
disp(‘Hello world’); Hello world
Hello world
end >>

Nested for loops:


Hello world
1
Example: for i = 2 : 2 : 6 2
disp(‘Hello world’); Hello world
for j = 1 : 2 1
2
disp(j); Hello world
end 1
end 2
>>
for Loops

for index = n_initial : n_increment : n_final


executable code
end

 The index variable takes on the first value in the range, then MATLAB runs all the commands
between the for and end lines.

 Then, the index variable takes on the next value in the range, and MATLAB runs the
commands again.

 Once the loop has finished the last iteration, the program continues from after the end line.
In-class exercise

 Create new script file: Lecture7_Ex2.m

Given: c = [1 0 2 1]

Using a for loop, create a script that loops through vector c and adds 6 to each
element.
How to Compute a “Running” Sum

 Create new script file: Lecture7_Ex3.m

Given:

Compute:

Need to numerically perform a running sum using for loop.

V = [5.6 7.2 4.9 8.3 9.2];


sumv = 0; Must initialize running sum to zero!
N = length(V);
for i = 1:N
sumv = sumv + V(i)*V(i); V_rms = 7.2214
end
V_rms = sqrt(sumv/N)
Computing a “Running” Sum

In MATLAB, can also solve in other ways:

V_rms = sqrt(sum(V.*V)/N)
V_rms =
7.2214

or

V_rms = sqrt(dot(V,V)/N)
V_rms =
7.2214

Loop structures are generally not computationally efficient compared to matrix operations
Nested for loops

Loops may be nested (a loop within a loop).

Example: Create a script file (Lecture7_Ex4.m) that executes a nested loop.

for iodd = 1:2:5


disp(‘Starting inner loop.’)
Outer for ieven = 2:2:6
Loop Inner disp( [iodd ieven] )
Loop end
end

Inspect the results that are printed in the command window.


while Loops

 Repetitively applies the execution of a set of statements until a logic state IS NOT
satisfied.

Basic Form:

while ‘logic statement’ (Executed until logic is NOT TRUE.)


executable code
end

Often used with iterative methods until convergence criterion is satisfied.

Example (Lecture7_Ex5.m) : Print integers from 1 to 3. For each integer, print its
squared value.
1
i = 1; 1
while i <= 3 2
disp(i); 4
disp(i^2); 3
i = i + 1; 9
end >>
A Simple Example

 Create new script file: Lecture7_Ex6.m

In this script, using a while loop and the rand function, you will write a
program to generate a random number greater than 0.5.

% Generate a random number greater than 0.5


clear;
clc;

xmin = 0.5; %Minimum desired value of x


A Simple Example

 Create new script file: Lecture7_Ex6.m

In this script, using a while loop and the rand function, you will write a
program to generate a random number greater than 0.5.

% Generate a random number greater than 0.5


clear;
clc;

xmin = 0.5; % Minimum desired value of x


x = 0; % Initialize value of x to start the while loop
while (x < xmin) % If x is too small, keep trying
x = rand;
disp(x)
end

disp('Final value reached.')


While Loops vs. For Loops

For Loop While Loop


 Runs a pre-determined number of times.  Runs until a condition is met. The number
of iterations is not necessarily known
beforehand. May also be an infinite loop.

 Has an index variable which automatically  Does not have an automatic index variable.
changes value at each iteration. If you want one, it must be added manually.
An Infinite Loop

 Create new script file: Lecture7_Ex7.m

Infinite loop occurs if the logical expression in a WHILE loop never becomes
false.

x = 5;
while (x > 0)
disp(x)
end

• Run script, then;


• In the Command Window, press Ctrl-C to stop the current program.
Implied Loops

 MATLAB is designed for high-speed vector computations.

 You can often save lines of code by using MATLAB commands instead of loops.

For example:

x = [0 : 5 : 100]; for k = 1 : 21
y = cos( x ); x = (k – 1)*5;
y(k) = cos(x);
end

Equivalent Statements
A Simple Example

 Create new script file: Lecture7_Ex8.m

Develop a MATLAB code that computes n!


• Define the value of n manually in the script.
• Because n is prescribed, it makes sense to use a for loop.

n = 5;
Factorial_Product = 1;
for i = 2:n
Factorial_Product = Factorial_Product*i; A “Running” Product!
end

Answer:

Factorial_Product = 120
An Example, Cont’d.

May also use a while loop:

n = 5; Note: Must initialize the value of i


i = 1; (or will go into infinite loop….must
Factorial_Product = 1; manually terminate!).
while i <= n
Factorial_Product = Factorial_Product*i;
i = i + 1;
end

Or, using intrinsic MATLAB function:

n = 5;
factorial(n)
ans =
120
Some examples: function and for loop

 Create new script file: Lecture7_Ex9.m


Compute cos x using a Maclaurin Series Expansion function, where x is an
input value prescribed by the user.
 Within the Script, type:

x = 0.6;
Cos_x = fct_cosx(x);
Ans = Note: this series can be used
0.8253 to approximate a function or
compute an otherwise incomputable
 The function file (fct_cosx.m) consists of: sum. Will be revisited later
function [Cos_x] = fct_cosx(x) (numerical methods).
sum = 0;
for n = 0:10
sum = sum + (-1)^n * x^(2*n)/factorial(2*n);
end
Cos_x = sum;
end

You might also like