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.

Slides:



Advertisements
Similar presentations
While loops.
Advertisements

Computer programming Lecture 3. Lecture 3: Outline Program Looping [Kochan – chap.5] –The for Statement –Relational Operators –Nested for Loops –Increment.
Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Branches and Loops Selim Aksoy Bilkent University Department of Computer Engineering
Loops – While, Do, For Repetition Statements Introduction to Arrays
Precedence Parentheses Arithemetic ^ * / + - (exception logical not ~ ) Relational > =
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Fundamentals of Python: From First Programs Through Data Structures
INTRO TO PROGRAMMING Chapter 2. M-files While commands can be entered directly to the command window, MATLAB also allows you to put commands in text files.
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
Fundamentals of Python: First Programs
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
Slide deck by Dr. Greg Reese Miami University MATLAB An Introduction With Applications, 5 th Edition Dr. Amos Gilat The Ohio State University Chapter 6.
Selection Programming EE 100. Outline introduction Relational and Logical Operators Flow Control Loops Update Processes.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
Loops CS 103 February 19, 2007 Presented by Nate.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
MATLAB for Engineers 4E, by Holly Moore. © 2014 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected by Copyright.
1 Flow of control Sequential Executing instructions one by one, in exact order given Selection Choosing to execute a particular set of statements depending.
Programming in Java Unit 4. Learning outcome:  LO2: Be able to design Java solutions  LO3: Be able to implement Java solutions Assessment criteria:
1 Computer Programming (ECGD2102 ) Using MATLAB Instructor: Eng. Eman Al.Swaity Lecture (4): Control Flow (Chapter 2)
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Saeed Ghanbartehrani Summer 2015 Lecture Notes #5: Programming Structures IE 212: Computational Methods for Industrial Engineering.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 ‏ Control Structures.
CMP-MX21: Lecture 5 Repetitions Steve Hordley. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition.
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
JavaScript, Fourth Edition
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
Matlab tutorial course Lesson 4: Writing your own functions: programming constructs
1 ECE 1331 MATLAB: Iteration loops and implied loops.
Matlab Programming for Engineers
Digital Image Processing Introduction to M-function Programming.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
General Computer Science for Engineers CISC 106 Lecture 13 - Midterm Review James Atlas Computer and Information Sciences 10/02/2009.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
A L I MAM M OHAMMAD B IN S AUD I SLAMIC U NIVERSITY C OLLEGE OF S CIENCES D EPARTMENT OF M ATHEMATICS MATLAB 251 : MATH SOFTWARE Introduction to MATLAB.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Conditional Statements A conditional statement lets us choose which statement will be executed next Conditional statements give us the power to make basic.
PH2150 Scientific Computing Skills Control Structures in Python In general, statements are executed sequentially, top to bottom. There are many instances.
Lecture 4b Repeating With Loops
EEE 161 Applied Electromagnetics
REPETITION CONTROL STRUCTURE
Repetition Structures Chapter 9
Loop Structures.
Ch 7: JavaScript Control Statements I.
JavaScript: Control Statements.
ITM 352 Flow-Control: Loops
Looping.
Arrays, For loop While loop Do while loop
Outline Altering flow of control Boolean expressions
Structured Program Development in C
Matlab tutorial course
3 Control Statements:.
Logical Operations In Matlab.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Matlab Basics.
Chap 7. Advanced Control Statements in Java
Presentation transcript:

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 do this stuff else do this stuff end

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’)

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

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

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

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

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

Code repetition

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.

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?

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?

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];

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

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

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

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

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

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

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

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

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

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

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

Exercises Define V = round(rand(10000,1)* ); 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

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 = [ ; ; ; ; ; ; ; ]; 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 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)