0% found this document useful (0 votes)
38 views24 pages

Chapter5 - For Loops - v2

For loops allow code to be executed repeatedly for each value in a vector. The syntax uses a variable like i or k to iterate through each element of the vector. For example, a for loop could print the phrase "Welcome Huskies" n times based on a user-input value of n. For loops are commonly used to process each element of a vector or array individually, such as calculating the average of user-input numbers by adding them to a running total variable inside the for loop.

Uploaded by

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

Chapter5 - For Loops - v2

For loops allow code to be executed repeatedly for each value in a vector. The syntax uses a variable like i or k to iterate through each element of the vector. For example, a for loop could print the phrase "Welcome Huskies" n times based on a user-input value of n. For loops are commonly used to process each element of a vector or array individually, such as calculating the average of user-input numbers by adding them to a running total variable inside the for loop.

Uploaded by

Louis Reynolds
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Chapter5 part3

For Loops (Section 5.3)

for loops vs. while loops


In while
we ask MATLAB to execute a block of
code while a certain condition is true

In for loops
we ask MATLAB to execute a block of
code for all values in a certain vector
Usually used to execute a block of code
for a certain number of times

for loop syntax


The template for a for loop is:
for<variable>=<vector>
<codeblock>
end

Here is how it works:


For each value in <vector>, assign the
value to <variable> and execute the
<code block>
1-3

Simple for loop example

impleForLoop

>> SimpleForLoop

Workspace
index
1

Simple for loop example

impleForLoop

>> SimpleForLoop
1

Workspace
index
1

Simple for loop example

impleForLoop

>> SimpleForLoop
1

Workspace
index
2

Simple for loop example

impleForLoop

>> SimpleForLoop
1
2

Workspace
index
2

Simple for loop example

impleForLoop

>> SimpleForLoop
1
2

Workspace
index
3

Simple for loop example

impleForLoop

>> SimpleForLoop
1
2
3

Workspace
index
3

Simple for loop example

impleForLoop

>> SimpleForLoop
1
2
3

Workspace
index
4

Simple for loop example

impleForLoop

>> SimpleForLoop
1
2
3
4

Workspace
index
4

A for loop can be any of the following


for k= [1,3,7,8,9,11]
disp(k)
end
for k = 1:4
disp(k)
end
for k = 2:0.5:3
disp(k)
end
for k = 0:-2:-7
disp(k)
end

k takes on the values one by one

Implied increment of 1
Values of k : 1 2 3 4
real number increment
Values of k: 2 2.5 3

Negative increment
Values of k: 0 -2 -4 -6

Do we have to use the loop index


inside the loop?
No sometimes it just serves as a
counter
Example 2: A function used in printing
flyers. The function accepts a number
n as a parameter and prints the phrase
Welcome Huskies n times

Example 2: A program used in printing


flyers that reads a number n and prints
phrase Welcome
Huskies
n times
n the
= input(Enter
the number
of lines);
% prints a greeting n times

for k= 1:n
% print the greeting

disp('Welcome Huskies')
end

k is not used in the loop body!

Example 3
Calculate the average of 4 numbers given by the user

ear
% Average 4 numbers from user input
n= 4; % number of data values

total = 0;;
for k= 1:n

Initialize your variables in


which the total will be
accumilated

% read and process input value

num= input('Enter a number: ');


total= total + num;
end
avrg = total/n; % average of n numbers
fprintf('Average is %f\n', avrg)
15

Another way !
Save the values entered by the user in a
vector of values then use the built in
function mean() !
The loop
is usedfrom
to read
values
%
Average
4 numbers
user the
input
n= 4; % initialize the number of data values
numbers = [];
for k= 1:n
% read and save input value

num= input('Enter a number: ');


numbers = [numbers num]
end
avrg = mean(numbers);% average of n numbers
fprintf('Average is %f\n', avrg) 16

A solution without a loop


Read all values at once as a vector. The
user would have to enclose the numbers
between [ ].
% read and save input values as a vector
num= input('Enter a list of numbers between [ ]: ');
avrg = mean(numbers);% average of n numbers
fprintf('Average is %f\n', avrg)

17

Back to the examples


Examples:
Given a set of genes and their expressions, get
all genes with expression higher than a specific
level.
In a pass fail course, give all students with total
grade >= 60 a letter grade P and students
with total grade < 60 a letter grade of F.
Schedule payday for employees based on the
first letter of their last names.
Set the room A/C temperature based on the
time of the day.

Genes
Find genes with expression
level
>= 10 and output their
IDs

12104
37990
11410
34412
41319
28671
25443

GenesIDs

Demo on MATLAB

190.2
5204.3
25.1
7.7
799.4
6.0
940.9

GeneExp

Loops and fprintf


Given a vector A of numbers, print a
two column table with the numbers
in column 1 and their square roots in
the second column (similar to
homework assignment 1)

Given a vector A of numbers, print a


two column table with the numbers
in column 1 and their square roots in
second column
Firstthe
attempt

Given a vector A of numbers, print a


two column table with the numbers
in column 1 and their square roots in
the second
column
Second
attempt
Use fprintf for better number formatting

A
sqrtA

Big Mess!!

Given a vector A of numbers, print a


two column table with the numbers
in column 1 and their square roots in
theattempt
second column
Third
Use fprintf inside a for loop for better
control
of the order in which elements are
printed
returns the number of
elements in A
Send the values 2 at a time

A solution without a loop


A = 1:10; % generate the numbers
sqrtA = sqrt(A); % get the sqrt
% combine the two vectors vertically
A_sqrtA = [A; sqrtA];
Disp(A
sqrt(A));
fprintf(%d \t %5.2f \n, A_sqrtA)

You might also like