Presentation is loading. Please wait.

Presentation is loading. Please wait.

“Clumsy mixture of ingredients…”

Similar presentations


Presentation on theme: "“Clumsy mixture of ingredients…”"— Presentation transcript:

1 “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

2 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

3 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

4 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

5 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

6 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

7 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

8 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

9 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

10 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

11 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

12 Guidelines & tips Define a function named popGrowth with four inputs:
vector of growth rates to simulate (default [ ]) 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


Download ppt "“Clumsy mixture of ingredients…”"

Similar presentations


Ads by Google