Sei sulla pagina 1di 25

4/1/2019

CSCI-1190
Beginning Programming for Engineers
 Today’s class
 Quiz 2
• At the beginning of the class, about 15 minutes
• Covers lectures 2 and 3, online multiple choices
o Lecture 4
 Lecture assignment: due before the next lecture on Monday
1. HW 4 in Grader
2. zyBook Participation Activity 4, Listed on LMS and zyBook
 Lab 4 on Thursday

CSCI-1190 Dr. Liu

Lecture 4
1. Program flow control: Iteration
o for loop
o while loop
o break loop statement
2. Program speed: tic and toc commands to time a program
3. Vectorization vs. iteration
4. More on drawings: subplot, plot3, polar, …
CSCI-1190 BP Liu 4

1
4/1/2019

for Loop: Repeat for Specified Number of Times


 Syntax: for var=firstn:step:lastn
for variable = values statements
statements end
end
 The variable is a variable name and takes each value of values during the
iteration process. (It is called the control variable, the loop variable, or
the index variable.)
 The values can take one of the following forms:
o A range expression – initialValue : endValue
o A range expression – initialValue : increment : endValue
o An array
o An expression or a function which results in an array
http://www.mathworks.com/help/matlab/ref/for.html

How Does the for Loop Run?

for variable = values


statements
end

o The number of iteration is defined by values


o In each iteration, the variable takes a successive column
of the values
o The variable is normally used in the statements

2
4/1/2019

for Loop Example


% variable n takes each value of the values 1:10

clear, clc
format compact
for n = 1:10
n
end

% Question: what is n value after the loop?

for Loop Examples


%% Use a “for” loop to create a row vector y = [ 1 2 3 4 5 6 7 8 9 10 ]

for n = 1:10
y(n) = n;
end
y

%% Vectorization of the above for loop


y=1:10

3
4/1/2019

for Loop Example


% Variable v takes each value of the row vector [1:2:12]

clear, clc
for v = 1:2:12
disp(v)
end

for Loop Example


% The control variable c is assigned to each column of b

clear, clc
b=[1:5; 21:25; 31:35]
for c = b
c
end

4
4/1/2019

for Loop Example


%% The "for" loop’s values can be the result of an expression

format compact
clear, clc
for e = eye(4,3)
e
end

for Loop Examples


%% Create a vector with each element to be the square of its
index

for idx = 1:5


vec(idx) = idx^2
end

%% Vectorization of the above for loop


vec =[1:5].^2

5
4/1/2019

for Loop Example


% Create a geometric series with a constant ratio r
format rat % display in fraction format
r = 1/2; x(1)=1;
for n=2:10 % The loop starts from index 2
x(n) = x(n-1) * r;
end
x

for Loop Example: Compute a Running Sum

total=0; % initialization
for x = 1:5
total = total + x
end

6
4/1/2019

for Loop Example: Compute Factorial N!

N=10; f = 1; % initialization
for i = 1:N
f=f*i
end

fprintf('%d! = %d\n', N, f); % 10! = 3628800

for Loop Example: Use a for Loop in a Function to Compute N!


function [f] = fact(N)
%% fact computes N!
f = 1; %initialization is necessary
for i = 1:N
f = f * i;
end
end

% Call the function


>> y = fact(10) % y = 3628800

7
4/1/2019

Example: Use for Loop to Create a Reciprocal Vector


% Algorithm 1 % Algorithm 2
vec = [ 2 3 5 1 9 ]; vec = [ 2 3 5 1 9 ];
rv = []; % rv = [];
for v = vec
for i = 1:length(vec)
rv = [rv , 1/v]
rv(i) = 1/vec(i);
end
end
rv
rv
% Algorithm 3: vectorization
vec = [ 2 3 5 1 9 ];
rv = 1 ./vec

For Loop Can Have Non-integer Range Values

% good example
for n = -1.5:1.5:3
disp(n^2);
end

Note: Can not use non-integer values as indices


% Error example Why is this wrong?


for n=1.5:2.5:10 A matrix must use
x(n)=n^2 integers as its indices
end

8
4/1/2019

for Loop’s Control Variable is Owned/Controlled by the Loop


 The for loop automatically assigns the control variable
to its next value for each iteration. Any value change on
the control variable inside the loop will be ignored.
% Example: The loop overrides any changes to the cvar in the loop
clear, clc
for cvar = 1:5
cvar % The cvar takes values 1,2,3,4,5
cvar=-100; % Try to change the cvar in the loop
cvar % temporarily changed cvar to be -100.
end

break
o The break statement terminates the execution of a loop before
the loop finishes (in for or while loop).

o Statements in the loop after the break statement do not execute.

o In nested loops, break exit the loop in which it occurs. Process


flow control passes to the statement that follows the end of that
loop.

9
4/1/2019

Example: break statement


% The following for loop only executes
% The following for loop executes
% 10 times when it exits the loops
% 100 times without break
y=0;
for n = 1:100
y=0;
y=y+n;
for n = 1:100
if (n == 10)
y=y+n;
break;
end
end
y % y = 5050
end
y % y = 55

Nesting the “for” Loop


 It starts from the outer loop, finish the inner loop, then
continue the outer loop.

for i = 1:3
for j = 4:6
disp ( [ i, j ] );
end
end

10
4/1/2019

break Nested for Loops


for i = 1:3
for j = 4:6 i j
disp( [ i, j ] );
break;
end
end

for i = 1:3
for j = 4:6
disp( [ i, j ] );
end
break;
end

Example: for, if, and break


% A modified Hi-Lo Game. Try at most C times.
clear, clc, M = 100; C = 10; myNum = floor(1+M*rand());
fprintf('Please enter a number between 1 and %d. You can guess up to %d times.\n', M, C);
for i = 1:C
yourNum = input('Enter your guess: ');
if yourNum < myNum
disp('Too low!')
elseif yourNum > myNum
disp('Too high!')
else
disp('Correct!')
break; % Exit the loop if guessed right before 10 times
end
end

11
4/1/2019

continue
% The continue command skips the statement after it in a “for” or “ while”
loop, and continues to the next iteration.

for n = 1:10
if mod(n,3) % remainder after n/3
continue % continue is executed when n is not a multiple of 3
disp(n); % This disp command is never executed here.
end
disp(['Divisible by 3: ' , ‘n is ‘ , num2str(n)]);
end
% The above disp is executed only when n is a multiple of 3 because mod(n,3) is 0 (false)
% when the continue command is not executed.
https://www.mathworks.com/help/matlab/ref/mod.html

Summary on the Tips Using the “for” Loop


 Use the for loop when you know the number of iteration or loop
over a predefined matrix
 Avoid changing the control variable inside the loop statement.
The for loop structure overrides any changes made to the control
variable within the loop
 Use the break command to programmatically exit the loop
 Use the continue command to skip the rest of the instruction in a
loop and continue to the next iteration

12
4/1/2019

while loop
Syntax: while condition
while expression action(s)
end
statements
end
 The expression is evaluated; if the evaluation results in a true, the
statements inside the while loop are executed and the while loop
continues; if the evaluation results in a false, the while loop stops.
 The statements inside the while loop normally contain commands
that change the expression result to stop the loop.
https://www.mathworks.com/help/matlab/ref/while.html

while Loop Example

% Example
c = 0;
while c <= 10
c = c + 1 % changes the expression result
end

• The variable c is used as a counter here


• In this case, the variable c must be defined before the while loop,
and its value is updated inside the while loop.
• Question: what is the ending value of c?
• The loop stops when c has value 11.

13
4/1/2019

“for” vs. “while” Loops: Syntax Comparison


for var = rangeValues
statements
end

% Variables used in the expression must be defined before the while loop
while relational/logical expression % normally the loop contains the
statements commands which lead to the
change of the relational/logical
end
expression’s result to stop the
loop or uses the break command

Example: “for” vs. “while” Loops


c = 0; % initialize c
for c = 0:10 while c <= 10
c=c+1 c = c + 1; % command updates the c
end end

o In a for loop, the ‘=‘ operator o In a while loop, its relational or


creates and updates the logic expression is evaluated
control variable c. o The while loop stops if the
o The range values determine expression result is a ‘false’ value.
the iteration and when to stop. o The statement in a while loop
o The loop is controlled by the normally contains commands to
‘for’ syntax. changes the expression result

14
4/1/2019

Example: while Loop vs. for loop : Compute Running Sum

%% while loop for a running sum %% for loop for a


total=0; running sum
x= 1; total=0;
while x <= 5 for x = 1:5
total = total + x total = total + x
x = x +1; end
end

32

while Loop Example: Calculate the Total Dots in a Triangle


function [total] = triangle(n)
% Computes triangle numbers.
i = 1;
total = 0;
while i <= n % i:0,1,2,3,4, … n
total = total + i;
i = i+1;
end
end

●The variable total is a running sum (or running total).


●The variable i is a counter

15
4/1/2019

Example: Build Fibonacci Sequence

Compute a Fibonacci Number Using a while Loop (Multiple Running Sums)


function [f] = fib(n)
%% fib computes Fibonacci sequence
f = 1; f1 = 0; f2 = 1; i = 2;
while i <= n
f = f1 + f2;
f1 = f2;
f2 = f;
i = i+1;
end
end
(The function returns the nth number in the Fibonacci sequence. Each
iteration updates f, f1, f2, and the counter i.)

16
4/1/2019

2. Build Fibonacci Sequence Table Using a while Loop


function [ft] = fib_table(c)
% fib_table creates Fibonacci series
ft = []; i = 1;
while i <= c;
ft(end+1) = fib(i); % Append to fib(i) to ft(end+1)
i = i+1;
end
end

2. Build Fibonacci Sequence Table Using a while Loop

function [ft] = fib_table(c)


% fib_table creates Fibonacci series
i = 1;
while i <= c;
ft(i) = fib(i);
i = i+1;
end
end

17
4/1/2019

while loop Example: A Better hi-lo Game


%% Use while loop until guessing correctly.
M = 100; myNum = floor( 1+M*rand() ); % create myNum
% Prompt the guess range
fprintf('Enter an integer guess between 1 and %i. \n', M);

yourNum = input('Enter your guess: '); % Player’s input


while(yourNum ~= myNum) % Repeat until guess correctly.
if (yourNum < myNum)
disp('Too low!')
else
disp('Too high!')
end
yourNum = input(‘Enter your next guess: ');
end
38
disp('You
CSCI-1190 Liugot it!') % Finish up

while Loop Example: Use break in the Loop


%% Computer guesses your number between 1 and 100
clear; clc; lo = 1; high = 100; % Initialize
while true % Guessing loop (guess until reaching the right number)
guess = floor((lo+high)/2), w = input('Enter 1-low, 2-high, 3-correct: ');
if w == 1
disp('low'); lo = guess+1;
elseif w == 2
disp('high'); high = guess-1;
elseif w == 3
disp('correct! ‘, ‘ Ha, you got it!'); break;
else
disp('you entered an invalid number');
end
end

18
4/1/2019

Questions: How many iterations does each of the following loops runs?
i = 1;
while 1
while 1
disp('looping ...') disp('looping ...')
end i = i+1
end

i = 1; num1 = 5; num2 = 10;


while i < 10 while (num1 ~= num2)
disp('looping ...') num2 = input(‘input a number: ’ );
end num2= round(num2)
end
40

Enter the “ctrl-c” Keys to Stop a Running Program

 If a while loop program enters an infinite loop, it might because


the condition for stopping the while loop never met.

 To force a stop, type the ctrl-c keys in the Command Window

19
4/1/2019

Summary: for loop vs. while loop


 A counted loop
• “for”
• Used when you know ahead of time how many times the statements will
be repeated
• Repeat n-times
 A conditional loop
• “while”
• Used when you do not know ahead of time how many times some action
will be repeated
• Repeat until some relational or logical statement becomes false
 Most “for” loops can also be written as while loops
42

Timing algorithms
>> help tic
“tic Start a stopwatch timer.
tic and toc functions work together to measure elapsed time.
tic, by itself, saves the current time that toc uses later to
measure the time elapsed between the two.

tic
statements
time_spent = toc

20
4/1/2019

Vectorization vs iteration

%Iteration %Vectorization
tic tic
for n = 1:1000 x = [1:1000].^2; % faster
x(n) = n^2; toc
end
toc

Vectorization vs iteration
%% iteration
tic
for i = 1:100000
sind(i);
end
toc

% vectorization
tic;
sind(1:100000);
toc

21
4/1/2019

Effective and Ineffective Algorithms (zyBooks 9.5 Loops and Arrays)


clear, clc %% time algorithm 3: vectorization
%% time algorithm 1, create array by looping
tic
tic
a=round(rand(1, 1e6)*65); a=round(rand(1, 1e6)*65);
for k = 1:length(a) a1 = a* 60 * 60 *(1/1000);
a1(k) = a(k) * 60 * 60 *(1/1000); t3 = toc
end % time ratios of the algorithms
t1 = toc t1_t2 = t1/t2
%% time algorithm 2:
t2_t3 = t2/t3
tic
a = round(rand(1, 1e6) * 65);
% Allocate mem chunk
a1 = zeros(1, length(a));
for k = 1: length(a)
a1(k) = a(k) * 60 * 60 *(1/1000);
end
t2 = toc 46

subplot
 Plots can be divided into subplots.
% number of rows and columns, and where to plot
subplot(1,2,1);
plot(cosd(1:360),sind(1:360), ‘g');
title('Circle');

subplot(1,2,2);
plot(1:10, 1:10, 'r');
title('Line');
% each plot must follow each subplot

22
4/1/2019

plot3() in 3 dimensions
 3-dimensional line plots with plot3()function

theta = (pi/180)*(1:720);
x = theta.*cos(theta);
y = theta.*sin(theta);
z = theta;
plot3(x, y, z, 'r:')
grid on

polar()
 Can plot using polar coordinates, logarithmic coordinates, etc.

polar(sin(1:.01:3*pi),cos(1:0.01:3*pi))

Syntax:

polar(theta, rho)
polar(theta, rho, LineSpec)

23
4/1/2019

Polygon Operations
The fill() function creates and fills a polygon.
>> fill([1 2 3], [0 3 2], 'r');

The polyarea() computes the area of a polygon


>> polyarea([1 2 3], [0 3 2]) % ans = 2
The inpolygon() function tests if a point is in a polygon or not.
>> inpolygon(3,3, [1 2 3], [0 3 2]) % logical 0

subplot() function’s rows and columns

subplot(2,2,1) subplot(2,2,2)

subplot(2,2,3) subplot(2,2,4)

24
4/1/2019

subplot() Example: a 2-by-2 grid of graph


subplot(2, 2, 1); plot(1:10, 1:10, 'r'); title('Line');

subplot(2, 2, 2);
polar(sin(1:.01:3*pi),cos(1:0.01:3*pi))

subplot(2, 2, 3);
fill([1 2 3], [0 3 2], 'r');

theta = (pi/180)*(1:720);
x = theta.*cos(theta);
y = theta.*sin(theta);
z = theta;
subplot(2, 2, 4);
plot3(x, y, z, 'r:')
grid on

25

Potrebbero piacerti anche