“Clumsy mixture of ingredients…”

Slides:



Advertisements
Similar presentations
Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Advertisements

Introduction to Computing Science and Programming I
CS0004: Introduction to Programming Repetition – Do Loops.
Repeating Actions While and For Loops
Computer Science 1620 Loops.
Chapter 5: Loops and Files.
Loops – While, Do, For Repetition Statements Introduction to Arrays
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
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.
1 Flow of control Sequential Executing instructions one by one, in exact order given Selection Choosing to execute a particular set of statements depending.
CS112 Scientific Computation Department of Computer Science Wellesley College Hodgepodge “Clumsy mixture of ingredients…”
27/05/ Iteration Loops Nested Loops & The Step Parameter.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
CS112 Scientific Computation Department of Computer Science Wellesley College Building your own Functions.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
CMP-MX21: Lecture 5 Repetitions Steve Hordley. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition.
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.
CS112 Scientific Computation Department of Computer Science Wellesley College Loops Iteration with for loops.
Loops and Files. 5.1 The Increment and Decrement Operators.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
CS112 Scientific Computation Department of Computer Science Wellesley College Building your own Functions.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
Some Assignments  Write a program which prints the following information about at least 5 persons: NAME MAIL-ID EMPLOYEE-CODE PHONE Eg. Umesh
ESC101: Introduction to Computing
REPETITION CONTROL STRUCTURE
Loops BIS1523 – Lecture 10.
Repetition Structures Chapter 9
Control Statements in Matlab
The switch Statement, and Introduction to Looping
Lecture 7: Repeating a Known Number of Times
Matlab Training Session 4: Control, Flow and Functions
Topics Introduction to Repetition Structures
Python: Control Structures
Chapter 2 Assignment and Interactive Input
CS1371 Introduction to Computing for Engineers
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Scripts & Functions Scripts and functions are contained in .m-files
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Topics Introduction to Repetition Structures
Starter Write a program that asks the user if it is raining today.
User Defined Functions
Introduction to MATLAB
Conditions and Ifs BIS1523 – Lecture 8.
Additional Control Structures
T. Jumana Abu Shmais – AOU - Riyadh
Coding Concepts (Basics)
CIS 16 Application Development Programming with Visual Basic
Design and Implementation
Logical Operations In Matlab.
Nested Loops & The Step Parameter
Computing Fundamentals
Loop Statements & Vectorizing Code
Python programming exercise
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.
For loops Taken from notes by Dr. Neil Moore
Data Structures & Algorithms
Topics Introduction to Repetition Structures
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Matlab Basics.
Loop Statements & Vectorizing Code
Software Development Techniques
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

“Clumsy mixture of ingredients…” Hodgepodge “Clumsy mixture of ingredients…” - today, hodgepodge of things, hopefully not really clumsy as Webster’s dictionary says - start with recap on functions & for loops, revisit exercise from end last lecture, collecting golden ratios, get a tip on debugging loops, then how we can create optional inputs for functions we write, more on “if” statements, nested for loops, how use to loop through 2-D matrix, exercise uses nested loops in different way - that’s hodgepodge of topics for today

function collectGoldenRatios (ntimes) % prompts user for “ntimes” hand & forearm lengths and stores % ratios in a vector. The loop stops if the user enters a 0 for % the hand length. Number of entries is printed at the end ratios = []; for index = 1:ntimes     hand = input('Enter a hand length: ');     if (hand == 0)         break     else         forearm = input('Enter a forearm length: ');         ratios(index) = forearm/hand;     end end disp(['You entered ' num2str(length(ratios)) ' ratios']); - solution for collectGoldenRatios exercise, header begins with keyword “function”, no outputs, single input in parens, loop to keep asking user to enter hand & forearm lengths, and as entered, ratio stored on vector, but if user gets tired doing this over/over, enter 0 for hand length & stop loop immediately - don’t know how many will enter, start with empty vector of ratios, keep adding onto end (auto-expand as go), note break right after 0 hand (terminate loop), don’t need to get forearm in this case, print number of lengths at end - careful about auto-expand, MATLAB creates new vector and copies contents to new – takes time! - suppose wanted to return ratios? How modify header? Hodgepodge

Tip on debugging loops Print statements are your friends! % calculate 10! and print the result factorial = 0; for num = 10:1:1 disp('inside loop'); factorial = factorial * num; disp(['num: ' num2str(num) 'factorial : ' num2str(factorial)] end disp(['10! = ' num2str(factorial)]); Print statements are your friends! - run code, disp would say 10! = 0 - two problems (spot?): factorial must start at 1, and for num = 10:-1:1 (10:1:1 is empty vector) - suppose not so obvious and need help figure out - tip: add print statements, e.g. one at beginning of loop, check to be sure actually getting into loop, printout would show that loop never entered, and when this problem is fixed, printout would show that factorial stays at 0 Hodgepodge

The return of Peter Piper function peterPiper (numReps) % peterPiper(numReps) % repeats a tongue twister “numReps” times for count = 1:numReps disp('Peter Piper picked a peck of pickled peppers'); end Can we make the numReps input optional? - we’ve seen several built-in functions that have optional inputs, e.g. sum and plot: sum(myMatrix) sums across rows - optional second input, where sum(myMatrix, 2) sums across columns - plot(xcoords, ycoords) - optional color/style string - function we write: can we define so that one or more inputs are optional, with default values? >> peterPiper(4) or >> peterPiper  default - as it stands, can call peterPiper, but when reach for loop, error message that input argument numReps is undefined - need way to define this variable if user doesn’t supply Hodgepodge

Optional input arguments Inside a user-defined function, nargin returns the number of inputs entered when the function was called function peterPiper (numReps) % repeats a tongue twister multiple times % numReps input is optional if (nargin == 0) numReps = 5; end for count = 1:numReps disp('Peter Piper picked a peck of pickled peppers'); - questions: how can we determine whether user entered input when calling function? - if not entered, how specify default value? - nargin short for “number of arguments input” (e.g. >> peterPiper  nargin would be 0) - “if” statement assigns default value if 0 - this example has only one input - what if more? - first expand what know about “if” statement Hodgepodge

A third form of the if statement true false cond1 cond2 cond3 . if (cond1) … elseif (cond2) elseif (cond3) else end - third form has “elseif” clauses - if cond1 true, first group of statements executed, then move to code after “end” (picture) - otherwise, if cond1 false, check cond2, and if true, second group of statements & jump to end - if all conditions fail, move to “else” - note: final “else” is optional - to see this form of “if” statement in action, return to previous question, how can handle optional inputs in functions with multiple inputs (more than one) Hodgepodge

The elseif clause in action function drawCircle (radius, xcenter, ycenter, properties, width) % drawCircle(radius, xcenter, ycenter, properties, width) % draws a circle with specified radius, centered on (xcenter, ycenter) % with the (optional) properties and width angles = linspace(0, 2*pi, 50); xcoords = xcenter + radius * cos(angles); ycoords = ycenter + radius * sin(angles); if (nargin == 3) plot(xcoords, ycoords, 'b', 'LineWidth', 1); elseif (nargin == 4) plot(xcoords, ycoords, properties, 'LineWidth', 1); else plot(xcoords, ycoords, properties, 'LineWidth', width); end axis equal - revisit drawCircle function - suppose require inputs radius, xcenter, ycenter - list required inputs first - let’s say properties, width optional, then: >> drawCircle(50, 30, 60) >> drawCircle(50, 30, 60, ‘g:*’) >> drawCircle(50, 30, 60, ‘g:*’, 3) - still maintain order as listed in header - depending on inputs entered, call plot differently (supply defaults where needed) - think carefully about order of inputs - what if usually default properties but often want to specify width? more common optional inputs first Hodgepodge

Looping through a 2-D matrix count = 0; for row = 1:5 for col = 1:5 if (nums(row,col) ~= 0) count = count + 1; end 3 7 6 2 5 4 1 9 - suppose want to step through 2-D matrix in systematic way and perform computation at each location – some kinds of computations MATLAB can perform on elements of matrix all at once, e.g. Arithmetic operations on contents, but some tasks will require us to step through elements, one by one, in systematic way (example in moment) – here simple example to illustrate mechanics for doing this - nested for loops, one inside other (row 1-5, col 1-5) for each value of row, execute inner for loop, so for each row, step through 5 columns, then next row, etc. - know that nested for loops not needed here… nums But why bother with nested loops here?!? count = sum(sum(nums ~= 0)) Hodgepodge

Counting peaks A peak is a value that is larger than its 4 neighbors* 1 4 5 2 7 9 12 3 6 8 10 - consider another problem where it makes sense to loop through matrix with nested for loops - count number of peaks in matrix - function, one input: matrix, one output: number of peaks - step through all locations (not including border), and if value > each of four neighbors, increment number of peaks (comments  code) A peak is a value that is larger than its 4 neighbors* * Don’t bother checking locations around the border of the matrix two peaks Hodgepodge

How many peaks? function numPeaks = countPeaks (matrix) % counts the number of peaks in a matrix of numbers, where % a peak is a value that is larger than its 4 neighbors [rows cols] = size(matrix); numPeaks = 0; for row = 2:rows-1 for col = 2:cols-1 val = matrix(row, col); if (val > matrix(row-1, col)) & ... (val > matrix(row+1, col)) & ... (val > matrix(row, col+1)) & ... (val > matrix(row, col-1)) numPeaks = numPeaks + 1; end bumpy = peaks; surf(bumpy) npeaks = countPeaks(bumpy) Hodgepodge

Simulating population growth Goal: define a function that generates a figure with curves for different rates of population growth over multiple generations, using the logistic growth model for population growth: pt+1 = r * pt * (K – pt)/K pt: current population pt+1: population in the next generation r: growth rate K: carrying capacity - formula captures particular model of how population grows over time, Pt population at generation t, Pt+1 is population of next generation, rate r, K carrying capacity (max population that can be sustained by environment) - suppose want to create plot like this, shows growth of population for different values of r (rate) Hodgepodge

Guidelines & tips Define a function named popGrowth with four inputs: vector of growth rates to simulate (default [1.2 1.4 1.6 1.8 2.0]) initial population (default 2) number of generations (default 25) carrying capacity (default 1000) For each growth rate: create a vector to store the populations for each generation and store the initial population in the first location of the vector for each new generation, apply the formula to calculate the new population size and store it in the vector plot the populations for this growth rate Add figure embellishments at the end - start with simpler problem, single input rate and plot population growth for this single rate (leave gap between function header and loop - then add second loop around, to loop through multiple rates, lastly add multi-color plots (like spin) Hodgepodge