Presentation is loading. Please wait.

Presentation is loading. Please wait.

Flow control. Conditionals if condition do this stuff end if condition do this stuff else do this stuff end if condition do this stuff elseif condition.

Similar presentations


Presentation on theme: "Flow control. Conditionals if condition do this stuff end if condition do this stuff else do this stuff end if condition do this stuff elseif condition."— Presentation transcript:

1 Flow control

2 Conditionals

3 if condition do this stuff end if condition do this stuff else do this stuff end if condition do this stuff elseif condition do this stuff else do this stuff end

4 Conditionals if condition do this stuff end condition should evaluate to logical true or false. examples: x > 5 y == 5 x =7 strcmp(subject,’S01’)

5 Flow Control (IF statement) d=10; if d<5 'less than 5' else 'not less than 5' end output? d=10 True?no Skip to here end

6 The if statement evaluates a logical expression and executes a group of statements when the expression is TRUE. The optional elseif and else keywords provide for the execution of alternate groups of statements. An end keyword, terminates the last group of statements Example: for different values of A If (A > B) % Test for condition A > B disp('A is greater than B'); % disp writes string argument to screen elseif (A < B) % Test for condition A < B disp('A is less than B'); elseif (A == B) % Note that == means test for equality disp('A and B are equal'); else disp('Rather unexpected situation.... ') end Flow Control (IF statement) The if statement evaluates a logical expression and executes a group of statements when the expression is TRUE. The optional elseif and else keywords provide for the execution of alternate groups of statements. An end keyword, terminates the last group of statements Example: for different values of A If (A > B) % Test for condition A > B disp('A is greater than B'); % disp writes string argument to screen elseif (A < B) % Test for condition A < B disp('A is less than B'); elseif (A == B) % Note that == means test for equality disp('A and B are equal'); else disp('Rather unexpected situation.... ') end

7 function isItBigger(x,y) % will decide if x is bigger than y if x > y fprintf('Yes, x is bigger than y.\n'); else fprintf('No, x is not bigger than y.\n'); end >> isItBigger(3,4) No, x is not bigger than y. >> isItBigger(8,4) Yes, x is bigger than y. function isItNine(x) % will decide if x is equal to 9 if x = 9 fprintf(’It is nine!\n'); else fprintf('No, its not nine.\n'); end function isItNine(x) % will decide if x is equal to 9 if x == 9 fprintf(’It is nine!\n'); else fprintf('No, its not nine.\n'); end

8 function fruit = pickAFruit(color,size) % choose a fruit based on color and size % color is a string, and size is a double representing weight in grams if strcmp(color,’red’) if size < 10 fruit = ‘apple’; else fruit = ‘watermelon’; end elseif strcmp(color,’yellow’) fruit = ‘banana’; else fruit = ‘unknown’; end Nested conditionals

9 Switch and Case Statements The switch statement executes one of a group of case statements, based on whether the value of a variable (logicals included) is the same in both. Only the first match is executed. If no match is found, otherwise is executed. % In this example, need first to specify a positive integer value for n switch (rem(n,2)) % use help “rem” case 0 disp('n is even'); case 1 disp('n is odd') otherwise error('This seems hard to believe') end

10 Code repetition

11 For Loop The for loop repeats a group of statements a fixed, predetermined number of times. A matching end delineates the statements Example : for n = 1:30 % for loop start t(n) = n*0.5; % t elements will be allocated “on the fly” r(n) = sin(t(n)); % r elements will be allocated on the fly end; % for loop end plot(t,r); % Usual plot command It is a good idea to indent the loops for readability, especially when they are nested.

12 For Loop for i = 1:3 i end How many loops?3 i=1 i=2 i=3 output? What are the values of i in each loop?

13 For Loop for i = 1:2:5 i end How many loops?3 i=1 i=3 i=5 output? What are the values of i in each loop?

14 For Loop k=20:20:100; for i = 1:2:5 k(i) end How many loops?3 i=1 i=3 i=5 output? What are the values of i in each loop? What is in the original k vector? k=[20,40,60,80,100];

15 For Loop Vec=[12:-3:0]; for idx=1:length(Vec) disp( Vec(idx) ) end % create an rxc matrix for r=1:4 for c=1:4 M(r,c)=r*c; end for i =2:2:8 % the construct can be any vector array disp(i) end for i = ‘Kostas’ % the construct can be a character array disp(i) end

16 For loops function doLoop() %do a loop for i = 1:10 j = sqrt(i); fprintf(‘The square root of %d is: %.2f\n’,i,j); end >> doLoop() The square root of 1 is 1.00 The square root of 2 is 1.41 The square root of 3 is 1.73 The square root of 4 is 2.00 The square root of 5 is 2.24 The square root of 6 is 2.45 The square root of 7 is 2.65 The square root of 8 is 2.83 The square root of 9 is 3.00 The square root of 10 is 3.16 counter variable range of values for counter to take on code to be repeated

17 For loops function doLoop() %do a loop listOfPeople = {‘Fred’,’Mary’,’Laura’}; for i = 1:length(listOfPeople) name = listOfPeople{i}; fprintf(‘Person number %d is %s\n’,i,name); end return >> doLoop() Person number 1 is Fred Person number 2 is Mary Person number 3 is Laura

18 Vectorisation and Preallocation One way to make your MATLAB programs run faster is to vectorise the algorithms you use in constructing the programs, for example: x =.01; for k = 1:1000 y(k) = log10(x); % array y will be allocated dynamically x = x +.01; % x gets incremented here.... end A vectorized version is x =.01:.01:10; y = log10(x); % Compare with previous example If it is not possible to vectorise a piece of code, then a for loop can be made to execute faster by pre-allocating any vectors or arrays in which output results are stored such as: r = zeros(32,1); % 0 matrix (rows,cols) t = zeros(32,1); % 0 matrix for n = 1:32 t(n) = 0.1*n; r(n) = sin(t(n)); end

19 While Loop The while loop repeats a group of statements an indefinite number of times under control of a logical condition. A matching end delineates the main loop. while condition do this stuff end

20 While Loop a=1; b=5; while a<b b b=b-1; end How many loops?4 output? It continues until false but in this case, 4 loops

21 While Loop The while loop repeats a group of statements an indefinite number of times under control of a logical condition. A matching end delineates the main loop. Example: count = 10; % Initialise loop variable while count > 0 % Start of while loop disp(['Counter is: ',num2str(count)]); % use help num2str ! count = count-1; % Decrement the counter end % End of while loop

22 While loops function doLoop() %do a loop x = 0; while x < 10 y = x^2; fprintf(‘%d squared is %d\n’,x,y); x = x + 1; end >> doLoop() 0 squared is 0 1 squared is 1 2 squared is 4 3 squared is 9 4 squared is 16 5 squared is 25 6 squared is 36 7 squared is 49 8 squared is 64 9 squared is 81

23 While loops function doLoop() %do a loop x = 0; while 1 x = x + 1; fprintf(‘x is %d\n’,x); end Infinite loops

24 While loops function doLoop() %do a loop x = 0; while 1 x = x + 1; fprintf(‘x is %d\n’,x); if sqrt(x) == 5 break; end Breaking loops end the loop, regardless of whether condition is still true

25 While loops Continuing within a loop: sometimes you may want to stay within a for or while loop but pass control to the next iteration of the loop, skipping over any remaining statements in the body of the loop. This can be achieved with a continue statement. For example: for r=1:4 for c=1:4 if r*c>10 continue end N(r,c)=r*c; end >> N

26 Exercises Define V = round(rand(10000,1)*100+0.5); Describe what variable V consists of. How many numbers? What sort of numbers? What range of numbers? Using the for... end syntax write a program to step through each of the elements in the array V one value at a time and to print out each value Using the if... else... end syntax, now amend the above program so that it only prints out the value in the array if the value is greater than 99 Amend the program again to use a counter and then count how many times V exceeds 99 (Hint: this number should be about 100) Now try rewriting this program to use the while … end syntax rather than the for … end syntax

27 Exercises Suppose we have this data from 8 participants in an experiment, where column 1 is mean reaction time in ms and column 2 is proportion correct responses: data = [ 390 0.45; 347 0.32; 866 0.98; 549 0.67; 589 0.72; 641 0.50; 777 0.77; 702 0.68 ]; Using for … end and if … end syntax write a program to identify the participants who had mean RTs greater than 500ms and proportions correct greater than 0.65. Save these values in 2 matrices: ID (idx no of each participant that meets the criteria) and scores (2 col matrix, col 1 = RT and col 2 = proportion correct)


Download ppt "Flow control. Conditionals if condition do this stuff end if condition do this stuff else do this stuff end if condition do this stuff elseif condition."

Similar presentations


Ads by Google