chapter5 – for loops - v2.pptx

24
Chapter5 – part3 For Loops (Section 5.3)

Upload: louis-reynolds

Post on 17-Nov-2015

228 views

Category:

Documents


2 download

TRANSCRIPT

PowerPoint Presentation

Chapter5 part3For Loops (Section 5.3)

for loops vs. while loopsIn while we ask MATLAB to execute a block of code while a certain condition is trueIn for loops we ask MATLAB to execute a block of code for all values in a certain vectorUsually used to execute a block of code for a certain number of times

1-3The template for a for loop is:for = end

Here is how it works:For each value in , assign the value to and execute the

for loop syntax

3

Simple for loop example>> SimpleForLoop

SimpleForLoopWorkspaceindex 1

Simple for loop example>> SimpleForLoop1

SimpleForLoopWorkspaceindex 1

Simple for loop example>> SimpleForLoop1

SimpleForLoopWorkspaceindex 2

Simple for loop example>> SimpleForLoop12

SimpleForLoopWorkspaceindex 2

Simple for loop example>> SimpleForLoop12

SimpleForLoopWorkspaceindex 3

Simple for loop example>> SimpleForLoop123

SimpleForLoopWorkspaceindex 3

Simple for loop example>> SimpleForLoop123

SimpleForLoopWorkspaceindex 4

Simple for loop example>> SimpleForLoop1234

SimpleForLoopWorkspaceindex 4

11

A for loop can be any of the followingfor 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)endreal number incrementValues of k: 2 2.5 3

Implied increment of 1Values of k : 1 2 3 4

Negative incrementValues of k: 0 -2 -4 -6

k takes on the values one by one

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 the phrase Welcome Huskies n times

k is not used in the loop body!n = input(Enter the number of lines);% prints a greeting n timesfor k= 1:n % print the greeting disp('Welcome Huskies')end

Example 3Calculate the average of 4 numbers given by the userear% Average 4 numbers from user inputn= 4; % number of data valuestotal = 0;;for k= 1:n % read and process input value num= input('Enter a number: '); total= total + num;end

avrg = total/n; % average of n numbersfprintf('Average is %f\n', avrg)15Initialize your variables in which the total will be accumilated

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 used to read the values

16% Average 4 numbers from user inputn= 4; % initialize the number of data valuesnumbers = [];for k= 1:n % read and save input value num= input('Enter a number: '); numbers = [numbers num]endavrg = mean(numbers);% average of n numbersfprintf('Average is %f\n', avrg)

16

A solution without a loopRead all values at once as a vector. The user would have to enclose the numbers between [ ].

17% read and save input values as a vectornum= input('Enter a list of numbers between [ ]: ');avrg = mean(numbers);% average of n numbersfprintf('Average is %f\n', avrg)

17

Back to the examplesExamples: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.

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

12104 190.237990 5204.311410 25.134412 7.741319 799.428671 6.025443 940.9 GenesGenesIDs GeneExp

Demo on MATLAB

Loops and fprintfGiven 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)

First attemptGiven 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 attemptUse fprintf for better number formattingGiven a vector A of numbers, print a two column table with the numbers in column 1 and their square roots in the second column

A

sqrtABig Mess!!

Third attemptGiven a vector A of numbers, print a two column table with the numbers in column 1 and their square roots in the second column

Use fprintf inside a for loop for better controlof 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 loopA = 1:10; % generate the numberssqrtA = sqrt(A); % get the sqrt% combine the two vectors verticallyA_sqrtA = [A; sqrtA];Disp(A sqrt(A));fprintf(%d \t %5.2f \n, A_sqrtA)