MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 www.clarkson.edu/class/honorsmatlab.

Slides:



Advertisements
Similar presentations
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Advertisements

Introduction to Computing Science and Programming I
Chapter Chapter 4. Think back to any very difficult quantitative problem that you had to solve in some science class How long did it take? How many times.
Flow Charts, Loop Structures
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Computer Science 1620 Loops.
CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 3, Lecture 2.
1 Parts of a Loop (reminder) Every loop will always contain three main elements: –Priming: initialize your variables. –Testing: test against some known.
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Branches and Loops Selim Aksoy Bilkent University Department of Computer Engineering
Precedence Parentheses Arithemetic ^ * / + - (exception logical not ~ ) Relational > =
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Week 7 - Programming I Relational Operators A > B Logical Operators A | B For Loops for n = 1:10 –commands end.
Lecture 12 Another loop for repetition The while loop construct © 2007 Daniel Valentine. All rights reserved. Published by Elsevier.
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.
EGR 106 – Project Intro / While Loop Project description Project schedule Background information / terminology A simple example Examples of similar programs.
Week 7 - Programming II Today – more features: – Loop control – Extending if/else – Nesting of loops Debugging tools Textbook chapter 7, pages
Loops are MATLAB constructs that permit us to execute a sequence of statements more than once. There are two basic forms of loop constructs: i. while.
MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES HP 101 – MATLAB Wednesday, 9/24/2014
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
For Loops 2 ENGR 1181 MATLAB 9. For Loops and Looped Programming in Real Life As first introduced last lecture, looping within programs has long been.
08/10/ Iteration Loops For … To … Next. 208/10/2015 Learning Objectives Define a program loop. State when a loop will end. State when the For.
CPS120 Introduction to Computer Science Iteration (Looping)
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.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Review for Exam2 Key Ideas 1. Key Ideas: Boolean Operators (2 > 3) || (3 < 29.3) A.True B.False C.Impossible to determine (22 > 3) && (3 > 29.3) A.True.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
PROBLEM SOLVING WITH LOOPS Chapter 7. Concept of Repetition Structure Logic It is a computer task, that is used for Repeating a series of instructions.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
read and learn from example loop programs develop modular program
Introduction to Loops For Loops. Motivation for Using Loops So far, everything we’ve done in MATLAB, you could probably do by hand: Mathematical operations.
1 Loops II. 2 Recall the while Loop int sum = 0; int i = 1;... /* Sum the integers 1 to 10 */ while ( i
Chapter 5: Control Structures: Iteration Visual Basic.NET Programming: From Problem Analysis to Program Design.
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.
A simple classification problem Extract attributes Pattern Pattern recognition decision x C1 C2.
Matlab Programming for Engineers
CPS120 Introduction to Computer Science Iteration (Looping)
Repetition Statements (Loops) The do while Loop The last iteration structure in C++ is the do while loop. A do while loop repeats a statement or.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
Iterations (aka Loops). 2 Loops Loops (iterations) are segments of code that may be executed several times. Fixed-count (definite) loops repeat a fixed.
For…Next and Do...While Loops! Happy St. Patrick’s Day!
Intro to Loops 1.General Knowledge 2.Two Types of Loops 3.The WHILE loop 1.
Fortran: Control Structures Session Three ICoCSIS.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Iterations (aka Loops). 2 Loops Loops (iterations) are segments of code (loop body) that may be executed several times. Fixed-count (definite) loops repeat.
Why Repetition? Read 8 real numbers and compute their average REAL X1, X2, X3, X4, X5, X6, X7, X8 REAL SUM, AVG READ *, X1, X2, X3, X4, X5, X6, X7, X8.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CSE123 - Lecture 4 Structured Programming- Loops.
Chapter 5: Looping. Using the while Loop Loop – A structure that allows repeated execution of a block of statements Loop body – A block of statements.
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.
26/06/ Iteration Loops For … To … Next. 226/06/2016 Learning Objectives Define a program loop. State when a loop will end. State when the For.
Chapter 4 MATLAB Programming
Think What will be the output?
Scripts & Functions Scripts and functions are contained in .m-files
JavaScript: Control Statements.
Week 8 - Programming II Today – more features: Loop control
Lecture 4 MATLAB programming (2)
Loop Statements & Vectorizing Code
Loop Statements & Vectorizing Code
REPETITION Why Repetition?
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014

Quote and Video…  “Check Blackboard for the new homework. I know none of you will, but it makes me feel better.”  Sumona Mundal  Statistics  Video: 

Introduction to Loops  Loops: Simply a way for a program to execute certain values for a function  In other words, repeat a section of code  Can be a pattern or sporadic  Used when vectorization is not possible or impractical  We will learn for and while loops

Loops  MATLAB construct which allows multiple executions of the same block of code multiple times.  The while loop is repeated an indefinite number of times until a logical expression (like we learned a week ago) is satisfied  The for loop is repeated a predefined number of times  Visualize: While Loop For Loop Statement = true Repeat 3 times

For Loops – Basic Vocab  For construction:  Always contains for and end command  Code is between the for and end for variable = parameters Code line 1; Code line 2;...“Loop Index” end

Sporadic For Loops  For a preset vector of variables for x = [1,3,13,90] value = 2*x^2; disp(value); end  Output:

Simple Vector Loops  When your variables are in a pattern: factorial = 1; for ii = 1:5 factorial = factorial * ii; fprintf(‘%5.0f \n’, factorial); end  Output:

But……..  What if you want to store some values in an array to access later in the program after the loop is complete?

Loops – Defining an Array  You must index your array for ii = 1:5 a(ii) = 4*ii; disp(a); end  a is redefined each time (“iteration”) through the loop  Output  When your loop is done you have:  a = [ ]

Nested logicals in For Loops  You can have logical statements in loops count = 0; for ii = [ ]; grade = ii./60.*100; if grade >= 90 count = count + 1; end disp([‘In this group, ’ num2str(count) ‘ students got an A on the first physics exam!’]);  Output In this group, 2 students got an A on the first physics exam

Incremental For Loops  You can have loops in increments for a = start:incr:end Expression 1 Expression 2... Expression n end  Just be careful with your vectors. MATLAB will automatically fill empty slots in your vector with zeros

For Loops with Arrays  You can execute arrays in loops MatLab uses each column for each iteration format bank for ii = [1 2 3; 4 5 6; 7 8 9]; transpose = ii’; disp(transpose); end  Output

Nesting Loops  You can put one loop inside of another!  Make sure you use different loop indexes  ExampleMeaning: disp('# *# =#'); for ii = 1:3 1 * 1 = 1 for jj = 1:3 1 * 2 = 2 product = ii * jj; 1 * 3 = 3 disp([num2str([ii jj product])]); 2 * 1 = 2 end 2 * 2 = 4 end 2 * 3 = 6 Ends the inner most loop3 * 1 = 1 Ends the outer loop3 * 2 = 6 3 * 3 = 9  Remember: The end’s will close the innermost loop first and work out Any “ break ” or “ continue ” will also refer to the innermost loop which contains it – we’ll discuss this more later.

While Loops - Basic  While construction:  Always contains while and end command  Code is between the while and end while logical_expression Code line 1; Code line 2;... end  Logical Examples (Two weeks ago): x >= 5, x 5, x==1 || x==10

While Loops  Concept similar to for loops m = 0; while (m < 5) m = m + 1; disp(m); end  Output

Indexed Arrays  Like for loops, can store value as an indexed array m = 0; while(m < 4) m = m + 1; array(m) = m^2; end disp(array);  Output Useful when you don’t know how many iterations (“cycles”) you will need to complete

The Physics Example – Again!  While Construct: scores = [ ];student = 0;count = 0; while count < length(scores); count = count + 1; grade = scores(count) / 60 * 100; if grade >= 90 student = student + 1; end fprintf(‘In this group, %1.0f students got an A on the first physics exam \n’, student);  Output In this group, 2 students got an A on the first physics exam.

Break and Continue  Break: Can be used to stop a loop % This program accepts 10 positive input values n = 0; while n < 10; n = n + 1; a = input(‘Enter a positive number ’); if a < 0 disp(‘Has to be positive. You broke it! ’); break end disp(n) end  Output: Program displays all positive numbers until a negative number was entered.

Another Example  Guess Joe’s favorite number in 5 guesses guess = 0; while guess < 5; guess = guess + 1; fprintf(‘\nThis is guess number %1.0f \n’,guess); a = input(‘Make a guess! ’); if a == 8 disp(‘You guessed it! ’); break else disp(‘Nope. Try again.’); continue end

Good Programming Practice:  Indent the bodies of loops Not necessary but you should always do it. To make your code pretty, highlight all code, right click, smart indent  Never modify your loop index within the loop. You will produce errors that you will never find!  Preallocate all arrays before using them in a loop. Your code will run much faster! Do this: square = zeros(1,100); for ii = 1:100 square(ii) = ii^2; end Rather than this: for ii = 1:100 square(ii) = ii^2; end

The for Loop - Vecotorization (cont.)  Good Programming Practice:  Vectorize your code when you can. To perform the same calculations a vectorized code can perform 15 times faster than code using loops. Ex: Using a Loop Vecotrized for ii = 1:100 ii = 1:100; square(ii) = ii^2; square = ii.^2 square_root(ii) = ii^(1/2); square_root(ii)= ii.^(1/2); cube_root(ii) = ii^(1/3); cube_root(ii) = ii.^(1/3) end

Questions and Homework: Questions?  Homework: 8.9, 8.23, 8.24, 8.25 (with plot) Due next Wednesday at 5 (like normal). Get started early!