### Create a StudySoup account

#### Be part of our community, it's free to join!

Already have a StudySoup account? Login here

# Computer Methods in Biomedical Engineering BME 201

NCS

GPA 3.83

### View Full Document

## 21

## 0

## Popular in Course

## Popular in Biomedical Engineering

This 43 page Class Notes was uploaded by Raphaelle Heathcote on Thursday October 15, 2015. The Class Notes belongs to BME 201 at North Carolina State University taught by Gregory Sawicki in Fall. Since its upload, it has received 21 views. For similar materials see /class/223802/bme-201-north-carolina-state-university in Biomedical Engineering at North Carolina State University.

## Similar to BME 201 at NCS

## Reviews for Computer Methods in Biomedical Engineering

### What is Karma?

#### Karma is the currency of StudySoup.

#### You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 10/15/15

SM uRS M DEBUGGING 101 my program isn t working lt Good Programming Practices Pseudocude is a compact and inlorrnal highlevel description oi a computer programming algorithm that uses lhe structural conventions of a programming g 9 1 identify givens variables and equations v 2 Determine what parts of the problem are dependent upon other steps 3 Write out how you are going to solve the problem n at aw a r 4 Turn this into comments 5 Fill in the program beneath the comments Give variables and functions unique and meaningful names Variables and functions CANNOT share the same I name i Break the program into small Eartsl d Make your functions very speci c Le do notrtry an do everything with one function b 1 Make sure each of these small parts work e 9 Test simple cases before moving to complex ones known mcs pig l LESJHS M GM39 3 1 A o Tips for Debugging CTRL c in Command Window to stop code from executing NEVER deiete anything until the end just comment it out Block commenting Check the starting and ending conditions in L loops 4 RAEng zuem u O Try hard coding in a test case BMWquot Woldg Piay close attention to quotconfusingquot concepts ME M DEFINE 4 Aigtt Wk Come by HA4 SLOWLy W V m VMWSLJE W Lure ya me Mmmg m follow iixe Lacie LfN in LIME L121 A COOKQVL Raw 6 Ways to Debug Don39t suppress output if you want to make sure that a variable has the correct value gt quotDummy variablesquot for loops I I V Lu Mai Cvele in VnNaHEr W71 mg SUSPMh dew Summary g wipqu and we LPPN t 717 i If Imam whiz s 1 go a Ubd vgmj mam Pm h tm linL WM j ltzro wn Wm m mg mic Awe L in Hang l2 Debugging Check List Clear the MATLAB workspace in the Co w mmand Windo clear removes all variables from workspace clc clears the Command Window close all closes all open gures Check you file function and variable names Make sure your function name matches your le name A Make sure that you are not using a quotreservedquot wordname Make sure that your names do not contain aces 3 Make surefthat alLof the les you are trying to 39 t use are In eff1Warmquot3 DinaM7 Debugging Check List What the outp ut should be Check for typos Verify that all equations are correct Make sure that you are not over writing variables Make sure that you are using scalars and vectorsarrays correctly Filing in vectorsarrays 8 Make sure you are looping correctly Logical operators vs assigning values to variables 223 239 IKE MAME COMFMP amt lt1va clam mum ME 0K GDQM EA rim Hm ml meme Erwinl MA MB RF EAJMMeS OWN The objective of this chapter is to enable you 0 E llecogxize and avoid common errors and pitfalls Even experienced programmers seldom have progams run correcin me rst time In computer jargon an error in a program is a bug The story is that ermionic valves in one of the earliest compmers This primeval charcoaled 39bugquot look days to nd The process of detecting and correCLing errors is therefore called debugging There are many typa of errors and pitfalls some that are peculiar to MAME and some thai may occur when programming in any language These are discuSSed brie y in this chapter 91 SYNTAX ERRORS Syntax errors are typing mistakes in MA39l39lAB statements egrl pl cg instead of plot They are the most frequenl type of error and they are fatal MATIAB stops execution and displays an error message As evolves from one version to the next error messages improve Try the following examples to examine the latest error messages 213 disp39the answer is 39 nusttr2 WWW Ewyrlgmezmo Danlal r wemim Publlshed m Euwler un All ngmx Inserted um mars5mmammaslaaucwa 10 clue VL 8 XU 7 There are many possible syntax errors you will probably have discovered a few yourself Wilh experience you will become more adept at spelling your miSlakes The mc on l a ste r r returns me last error message generated 911 Incompatible vector sizes With the following statements Dpi203pi siMx Opi403pi loclxy you will gel the error message Error using gt plot Vectors must be the same lengths inrremem wh 05 reveals the problem x 1x121 y 1x61 912 Namehiding l1 MEMME VWGVE ll Lhzt a workspace variable quothidesquot 3 pi or ncrion owsame name a The only way to access 5L a script or function S Lo clearme offending van r able from the workspace Furthermore aMATLAB 086 hides 3 script ofthe DK la S same name For example ueate a script Led39luhym that displays a junk W Ja message and rhen type why 21 the command line quot 39 J 39 H 39K quot quot uLduugsayblUb S 936 maybeaMA39llAB uonuyhelp l3th rsL g x J39s12 LOGIC ERRORS Logic mors occur in the actual algorithm you are using to solve a prob lem and they are the most dif cult to ndLhe program runs but gives Lhe wrong answers It is even worse if you don t realize the answers are wrong The following u39ps might help you to check the logic Try 0 run Lhe program for some spedal cases where you know the answers 1e nk E If you don39t know any exact answers use your insight inro rhe problem 0 to check whether the answers seem r0 be of the right order of magnitude interactive debugging facilities see Chapter 10 ro see if you an e Try working through the Erogram by hand or use MATLAB39s excellent or MIL CODE spot where things start going wrong i M ham t Attimes as we have seem a program will give numerical answers rhat we know are wrong This can be due to rounding mm which results from the nite precision available on the computer eight bytes per variable instead of an in nite number 93 ROUNDING ERROR Run Lhe following program 1 arinth 24g gn39 xl x 02 end You will need to crash the program to stop it with Ctrl break on a PC The variable x never has the value 02 exactly because of rounding erro In fact x misses 02 by about 83 x 10 1 as can be seen from displaying the wlue of x 7 02 lt would be better ro replace the whi l e clause with whlle x lt 0 2 or even better with while absx 02 gt lE G ln vpnprzl 39 equality as follows if absaba lt leE disp 39a practically equals 339 end Dl39 if absua bllbj le Note that this equality test is based on the relative difference between a and b rather than on the absolute di erence Rounding error may sometimes be reduced by a mathematical rearrangement 39 of a fonuula Recall yet again the quadraLic equation M2bxc0 pirrznv9gr xnbrsa dgt eiiraus v v 39 39 wiLh soluticms x bWw XZbAmZa Taldnga 1 b 107 and c 0001 gives x1 107 and x2 0 The second 39 quot 39 39 numbers and con quot 39 39 I v However 04 I h yulduu of the two roots is given by 611 The second root can Lherzfore be expressed as cax1 Using rhis form gives 62 10 which is more accurate Syntax errors are mistakes in the consuuclion of MAT LAB statement 39 Logical errors are errors in the algorithm used to solve a problem Compuler quot to a niLe accuracy Lecture 14 Wednesday March 2 2011 Announcements 0 Case 2 resubmission is due today Be sure to submit you re your original and the new version of your solution Please take advantage of Prof Sawicki s Office Hours on M s and T s from 45PM 4212C EB3 Ben s hours are still being held Thursday afternoons 8H6 and Case 3 will be posted by the end of the week These will be due Wed March 16th 8H6 and Monday March 21St Case 3 SL5 is not due until after Spring Break Thursday March 17 Lab tomorrow will be a demonstration of a powered ankle exoskeleton to give you a flavor of what is to come following spring break lam still grading the exam and hope to return in Monday March 14 Thanks for your patience Reading for Next Time Reading on Functions and Program Development Palm Chapter 3133 Palm Chapter 41 Reading on Debugging Palm Chapter 48 SH EC How could we modify the pendulum simulation script file from last time so that it is a userdefined function called PendSim It should take lengthgravtfinaldtang0angvel0 asinputsandretu ltimeangangvel See posted code on Moode for solution Today s Goals Continue discussing functions I REMEMBER turn on your diary to save your Command Window gtgtdiary LectureMar2m ll Functions Continued Functions or commands are defined blocks of code that live in their own files Functions are predefined blocks of code that can be used over and over again Parameters and variables may be passed into or returned from functions Functions can be userdefined or already defined in MATLAB Help files will always give instructions on how previously defined functions are used You can nest subfunctions within primary functions subfunctions can only be called from within the primaryparent function Functions are handy because you can write a block of code once and then reuse it as many times as you want in as many other programs as you want Using a given function from other pieces of code is referred to as calling that function For example let s say l have some code that l have programmed in a script file Example of Conditional Code Block x3 y0 2 if xy use to compare for equivalence y z X X 139 elseif x lt y otherwise if X is less than y y xli else if previous statements are false but I want to be able to execute it for many different combinations of x y 2 To do this I could create a userdefined function by placing the above code in its own file called computeThis1m with the following syntax function x y z computeThislX y a simple function that takes 3 input values and returns the same 3 values that may or may not have been updated in the function body mm am if xy use to compare for equivalence y z x 202 elseif x lt y less tLan y x else if previous statements are false y 202 x 2 end terminate code block end a terminate parent function The above function requires 3 input variables x y and z The body of the function will modify these variables as needed and the updated values will be returned as 3 output variables x y 2 Here is howl could use the function computeThis1 by calling it from a separate script file eg main programm ee variables ion that takes 3 variables and returns 3 variables computeThisla b c as 9 mo Q0 D H7 The function does not change the values of a b or c but instead it returns 3 values that I chose to save as d e and f I could have chosen to overwrite a b c but in this case I want to save the original values NOTE WELL The variable names in the function de nition le do not have to match the variable names that use When calling the function The order that the variables are passed in will be maintained that is xa yb and zc inside the function And on the return dx ey and fz It is also possible to nest functions ie subfunctions within other functions primaryparent functions For example function x y z computeThi52x y z a simple function that takes 3 input values and returns the same 3 values that may or may not have been updated in the function body This is the parentprimary function mm mm if xy use to compare for equivalence z x XA2 elseif x lt y less than y xli else if previous statements are false x y z subElsex y 2 end terminate code block end terminate parent function A subfunction that can only be used by functions in this file function l m n subElsel m n m l 2 l n end In the above example when computeThis2 uses the subEIse function and we overwrite the original values for x y and 2 since these are being returned inside the parent function SOME RULES FOR FUNCTIONS Rule 1 To build a userdefined function you must have consistency between the mfile name and the function name Don t use a name already in use in MATLAB Use the exist command to check if you are unsure gtgt help exist EXIST Check if variables or functions are defined 0 if Adoes not exist 1 if A is a variable in the workspace 2 if A is an Mfile on MATLAB39s search path Rule 2 You must follow proper syntax in the function definition line That is the function output arguments what it computes go on the left of the in brackets and the function input arguments what it works on go on the right of the in parentheses For example the basic structure of the userdefined function FunctionNamem is as follows The first line of the file FunctionNamem must contain functionoutputiargs FunctionNameinputiargs then FunctionNamem Summary of this function goes here Detailed explanation of function goes here CODE GOES HERElllll end Rule 3 Variables inside the function file are called local variables and cannot be accessed except from within the function itself ie they are protected Rule 4 When calling a function only the order of the inputsarguments and outputs matter not the names Rule 5 Functions can have any number of inputs or outputs including no inputs or outputs For example sometimes a function just returns a plot or screen display and has no outputs Or sometimes a function just initializes some local variables and has no inputs See pages 121 and 122 in Palm for other examples Rule 6 NEVER define global variables ie lgnore Palm top of pg 124 IN CLASS PROBLEMS Do an example similar to that on 8H6 Palm Ch 3 page 141 degF to degC 1 Write a function that accepts temperature in degrees Fahrenheit degF and computes the corresponding value in degrees Celsius degC TdegC 59Tdeg F32 Now write a script that uses your function to create and plot values in degC vs values in degF over the range 200 degF to 200 degF 2 Do an example similar to SL5 by realtime programming in front of class Palm Ch 4 page 216217 Problem 48 Inventory Model Start as a scriptthen think about how to make a function N EXT TIME First enjoy Spring Break We ll return with more on functions including anonymous functions function handles function functions and other methods of calling functions Then we begin with numerical analysis topics signal processing data acquisition curve fitting integration and differentiation etc Lecture 15 Monday March 14 2011 Announcements 0 8H6 due Wednesday 16th hardcopyprintouts in class Be sure to submit a m file for each of your functions You can zip them for the electronic handin SL5 is due this Thursday March 17 0 Case 3 is due Monday March 215 Please take advantage of Prof Sawicki s Office Hours on M s and T s from 45PM 4212C EB3 Ben s hours are still being held Thursday afternoons o I will return the exam on Wednesday or Thursday March 16th or 17 Thanks for your patience Reading for Next Time Reading on Functions and Program Development Palm Chapter 3133 Palm Chapter 41 Reading on Debugging Palm Chapter 48 Today s Goals Continue discussing functions and do some examples I REMEMBER turn on your diary to save your Command Window gtgtdiary LectureMarl4m ll Post Spring Break Function Refresher Functions or commands are defined blocks of code that live in their own files Functions are predefined blocks of code that can be used over and over again Parameters and variables may be passed into or returned from functions Functions can be userdefined or already defined in MATLAB Help files will always give instructions on how previously defined functions are used You can nest subfunctions within primary functions subfunctions can only be called from within the primaryparent function Functions are handy because you can write a block of code once and then reuse it as many times as you want in as many other programs as you want Using a given function from other pieces of code is referred to as calling that function For example let s say l have some code that l have programmed in a script file Example of Conditional Code Block x3 y0 2 if xy use to compare for equivalence y z x x 2 e eif x lt y otherwise if X is less than y y 39 m H llllullullll Dc e if previous statements are false XAZ y x 2 end terminate code block but I want to be able to execute it for many different combinations of x y 2 To do this I could create a userdefined function by placing the above code in its own file called computeThis1m with the following syntax The first line of the file computeThis1m must contain functionoutput7args computeThisinputiargs J CODE GOES HERElllll end Here goes function x y z computeThislx y z a simple function that takes 3 input va u s a ns the same 3 values that may or may not have been updated in the function body if xey use to compare for equivalence y z x 202 elseif x lt y less than y x1i else if previous statements are false y 202 x end terminate code block end a terminate parent function The above function requires 3 input variables x y and z The body of the function will modify these variables as needed and the updated values will be returned as 3 output variables x y 2 Here is howl could use the function computeThis1 by calling it from a separate script file eg main programm define three variables a4 b3 c7 call function that take 5 3 variables and returns 3 Variables id e f computeThisla b c The function does not change the values of a b or c but instead it returns 3 values that I chose to save as d e and f I could have chosen to overwrite a b c but in this case I want to save the original values NOTE WELL The variable names in the function de nition le do not have to match the variable names that use When calling the function The order that the variables are passed in will be maintained that is xa yb and zc inside the function And on the return dx ey and fz It is also possible to nest functions ie use subfunctions within other functions primaryparent functions For example function x y z computeThi52x y z a simple function that takes 3 input values and returns the same 3 values that ma or may not have been updated in the function body This is the parentprimary function mm am if y use to compare for equivalence y z x A elseif x lt y less than y else if previous statements are false x y z subElsex y end a terminate code block end a terminate parent function A subfunction that can only be used by functions in this file function l m n subElsel m m l 2 l n end In the above example when computeThis2 uses the subElse function and we overwrite the original values for x y and 2 since these are being returned inside the parent function IN CLASS PROBLEMS 1 Do an example similar to SL5 by realtime programming in front of class Palm Ch 4 page 216217 Problem 48 Inventory Model Start as a scriptthen think about how to make a function 2 Do SH6 Palm problem Section 32 12 The Fence Problem Solutions to these will be posted after class N EXT TIME Anonymous functions function handles function functions and other methods of calling functions Cover gradient or diff for use to get velocity from delta length in Case 3 If time we will begin with numerical analysis topics integration and differentiation signal processing curve fitting and data acquisition Lecture 19 Monday March 28 2011 Announcements 0 SH is due Thursday March 31St in lab 0 Lab Exp 1 DAQ Book Weight vs iEMG is due Thursday March 31St in lab Follow Ben s write up instructions Case 4 will be posted today and is due Wednesday April 13 Please take advantage of Prof Sawicki s Office Hours on M s and T s from 45PM 4212C EB3 or by appt Ben s hours are still being held Thursday afternoons 0 Exam 2 is scheduled for Wednesday April 6th inclass Practice exam 2 will be posted by afternoonevening of Wed March 30 We will review the practice exam Monday April 4th in class 0 Debugging Cheat Sheet up on Moodle today Reading for Next Time Debugging Palm Chapter 48 Ch 92 on Numerical Integration Ch 8 on Linear Algebraic Equations SH EC Use fminbnd to find the minimum value of cosine between 0 and 2pi Today s Goals Continue with Examples similar to 8H7 using Anonymous Functions and Function Functions IN CLASS PROBLEMS w GROUP HELP 1 Palm Ch 32 p129 T32Problem 3 Irrigation Ditch 2 Palm Ch 92 p 412 Problem 17 Derivative and MinMax 3 Palm Ch 32 p143 Problem 14 Rainfall Estimates See posted solution to each of these on Moodle I REMEMBER turn on your diary to save your Command Window gtgtdiary LectureMarZB m Anonymous Functions Palm Ch 3 pg 132133 Anonymous functions provide a quick inline method of defining and executing a function without having it in a separate mfile This is useful for simple expressions like exponential equations or polynomial equations Syntax is as follows function name argument list expression The function handle ie reference is just the name of yourfunction The argument list can be as long as you like or even empty see Palm page 133 The expression can only be a single executable MATLAB expression To callexecute the anonymous function output variable name function handleargument list For example to define an anonymous function called sq that can compute the square of any input value X gt Example of an anonymous function with one inpu function handle input arguments function expression o0 This defines a function sq that computes the sq x XA2 square of the input value x which can be an array note element wise definition call it Then a bunch of ways to y Sq5 2 sq 5 6 8 a6 b12 cl3 ha b c tsq h Anonymous functions can be defined with multiple inputs For example gt Example of an anonymous function with two inputs This defines the function sumsqrt xy sqrtxA2 yA2 a sumsqrt To call it y sumsqrt45 Anonymous functions can call each other Palm p 133 For example gt Example of anonymous functions calling each other f x XA3i g x 5sinx h X gfX answerh2 Function Functions Palm p124 129 eg fzero fminbnd fminsearch and fsolve and Function Handles p 124 Afunction handle is a referralreference to an already defined userfunction Syntax is as follows function handle function name Function handles are important for using MATLAB s function functions Le a function that calls another function over and over again Some examples of numerical operations that use function handles to callreference functions from other functions are 1 finding zeros of a function 2 minimizing or maximizing a function of one or several variables ie optimization See Table 321 in Palm for some key Function Functionsgt fminbndfunction name x1 x2 for single value minimization with the range x1ltxltx2 fminsearchfunction name x0 for multivariable minimization with init guess vector x0 fzerofunction name x0 use start value x0 to find a zero of single variable function fplotfunction name lower xlimit upper x limit N EXT TIME General rules for debugging Continue with numerical integration commands matrix operations simple statistics curve fittingregressioninterpolation Lectures 26 and 27 Wednesday April 20 and Monday April 25 2011 Announcements 0 Note NO lab tomorrow Thursday April 21 Enjoy Spring Recess lvvill hold office hours today Wed April 20 from 56 PM REMAINING ASSIGNMENTS 1 Case 4 Cortical Probe Optimization is now due Monday April 25h in class 2 SH8 is due Wednesday April 27 h in class Posted Code will help 3 Case HW EC 30 Robot Arm Trajectory problem 7 from Palm p36162 Due Friday April 29th by noon in Prof Sawicki s office 4 Lab Exp 2 iEMG Controller Gain vs Artificial Muscle Force from April 7th data session writeup is due Thursday April 28th in final lab session Please continue to take advantage of Prof Sawicki s Office Hours on M s and T s from 45PM in 4212C EB3 or by appt Ben s hours are still being held Thursday afternoons REMINDER Complete official course evaluations online neon signs around EB3 Be fair Reading for Next Time Ch 7 Simple Statistics Histograms and Interpolation Ch 6 on Simple Regression and CurveFitting SH ECs 420 Matrix Algebra Problem from Palm p 365 11 7x 9y 92 22 3x 2y 42 12 x 5y z 2 425 Interpolation Problem from Palm p 328 23 Hour Mon Tues Wed Thurs Fri 17 15 12 16 16 1 2 13 8 11 12 3 14 14 9 15 4 17 15 14 15 19 5 23 18 17 20 24 Goals 1 420 Go over histograms summary statistics and interpolation 2 425 Go over curve fittingregression linearpolynomial exponential and power fits I REMEMBER turn on your diary to save your Command Window gtgtdiary LectureApr20 25m 1 39 quot and Summary Statistics Palm Ch 71 and 73 pp299303 HIST Histogram N HISTY bins the elements on into 10 equally spaced containers and returns the number of elements in each container lfY is a matrix HIST works down the columns N HlSTYM where M is a scalar uses M bins N HlSTYX where X is a vector returns the distribution of Y among bins with centers specified by X The first bin includes data between inf and the first center and the last bin includes data between the last bin and inf Note Use HISTC if it is more natural to specify bin edges instead MEAN Average or mean value For vectors MEANX is the mean value of the elements in X For matrices MEANX is a row vector containing the mean value of each column For ND arrays MEANX is the mean value of the elements along the first nonsingleton dimension of X STD Standard deviation For vectors Y STDX returns the standard deviation For matrices Y is a row vector containing the standard deviation of each column For ND arrays STD operates along the first nonsingleton dimension of X MEDIAN Median value MODE Mode or most frequent value in a sample RECALL For normally distributed datagt MEAN 1 SD covers 68 of the samples MEAN 2 SD covers 95 of the samples There are three types of hsitograms you should be aware of absolute frequency relative frequency and scaled See posted code on Moode for examples The scaled histogram has total area to 1 So integrating yvalues scaled frequencies up to a given xvalue iebin location using cumsumbinwidth gives information on the fraction of data represented in a given range Again see posted code on Moode for examples Finally rememberthat on a figure plot of sample data you can click on Toolsgt Data Statistics to quickly get values for min max mean etc Yl NTERP1XYXIMETHOD specifies alternate methods The default is linear interpolation Use an empty matrix to specify the default Available methods are 39nearest39 nearest neighbor interpolation 39linear39 linear interpolation 39spline39 piecewise cubic spline interpolation SPLINE 39pchip39 shapepreserving piecewise cubic interpolation 39cubic39 same as 39pchip39 Yl NTERP1XYXlMETHOD39extrap39 uses the specified method for extrapolation for any elements of XI outside the interval spanned by X Alternatively Yl INTERP1XYXlMETHODEXTRAPVAL replaces the values outside of the interval spanned by X with EXTRAPVAL NaN and O are often used for EXTRAPVAL The default extrapolation behavior with four input arguments is 39extrap39 for 39spline39 and 39pchip39 and EXTRAPVAL NaN for the other methods lNCLASS PROBLEMS ON HISTOGRAMSINTERPOLATION Soln s are posted 1 Palm Ch 72 5 on p 325 Histogram Summary Stats Example 2 Palm Ch 74 22 on p 328 Interpolation Example 2 CurveFitting Regression Palm Ch 61 p266 and Ch 62 p273 POLYFIT Fit polynomial to data P POLYFTXYN finds the coefficients of a polynomial PX of degree N that fits the data Y best in a leastsquares sense P is a row vector of length N1 containing the polynomial coefficients in descending powers P1XquotN P2XquotN1 PNX PN1 POLYVAL Evaluate polynomial Y POLYVALPX returns the value of a polynomial P evaluated at X P is a vector of length N1 whose elements are the coefficients of the polynomial in descending powers Y P1XquotN P2XquotN1 PNX PN1 If X is a matrix or vector the polynomial is evaluated at all points in X See POLYVALM for evaluation in a matrix sense Fitting a polynomial is easy using POLYFIT with N1 for linear use N2 for quadratic N3 for cubic etc Evaluating the polynomial fit is then straightforward using POLYVAL with the coefficients in P from POLYFIT output in conjunction with the x values from the original x data or in the case of a power curve fit the log transformed x data For example N1 yfit P1xsample P2 where P1 m the slope and P2 b the intercept of yfitmxsample b N2 yfit P2xsample2 P1xsample P3 N3 In addition exponential and power curve fitsregressions can both be transformed into the form of a linear ie N1 polynomial fit See Palm p266 for more details as well as the example code that is posted for your study Briefly for exponential y yoekquot and power yy kquot relationships if you take the log of both sides of the equation you will get a linear relationship For exponential logy log yo kx For power logy log yo klogx After this conversion is made a line can be fit to the transformed sample data using P POLYFITxinputyinput1 ie fitting a line y mx b where P1m and P2b For exponential x inputxsample yinput logysample P2mk and P1b log yo For power x inputlogxsample yinput logysample P2mk and P1b log yo Of course once you have the values of k and y0 it becomes easy to plot the fitted relationship for any vector x eg using an anonymous function or elementbyelement arithmetic The residual is an important concept and is a way of evaluating how well your curve fitregression actually fits It is simply the difference of the original output sample data y and the fitted data ym residual y y t a vector of error values Sometimes the norm of the residual is computed ie sqrt of the sum of squares along the residualerror vector as a simple metric indicating goodness of fit Smaller norm residual indicates a better fit of the curve to the original data The MATLAB command norm can be used to compute the norm of the residual vector normresidual normresidual a single value summarizing goodness of fit Finally remember that on a figure plot of sample data you can click on Toolsgt Basic Fitting to quickly get spline curve fits and many orders of polynomials complete with equations forthe fit and residuals for evaluating goodness of the fit lNCLASS PROBLEMS ON CURVEFITREGRESSION Soln s are posted 1 Palm Ch 61 2a on p 286 Fitting Different Function Types to Data 2 Palm Ch 6262 18 on p 29192 Fitting and Residuals N EXT TIME Regression CurveFitting continued Lecture 13 Monday February 28 2011 Announcements 0 Nothing is due today 0 Case 2 resubmission is due Wednesday March 2 Be sure to submit you re your original and the new version of your solution Please take advantage of Prof Sawicki s Office Hours on M s and T s from 45PM 4212C EB3 Ben s hours are still being held Thursday afternoons 8H6 and Case 3 will be posted by the end of the week These will be due Wed March 16th 8H6 and Monday March 21St Case 3 SL5 is not due until after Spring Break Thursday March 17 Lab this Thursday will be a demonstration of a powered ankle exoskeleton to give you a flavor of what is to come following spring break lam still grading the exam and hope to return in Monday March 14 Thanks for your patience Reading for Next Time Reading on Functions and Program Development Palm Chapter 3133 Palm Chapter 41 Reading on Debugging Palm Chapter 48 Today s Goals Review Euler s Method eg similar to SL5 Begin discussing functions MATLAB built in and userdefined I REMEMBER turn on your diary to save your Command Window gtgtdiary LectureFeb28m ll Euler s Method for solving differential equations revisited There are many differential equations that cannot be solved analytically ie on pencil and paper Forthese we need a computer to march through time Explain Euler s method on whiteboard As an example derive simple pendulum equations of motion and make them into two first order equations Step 1 deltaYdeltaTsomedifquuation Step 2 y1 y0 deltay Step 3 deltay somedifquuationdt o Eller39s Method Example Integrating equations of motion describing pendulum mechanics gto PROBLEM DESCRIPTION Start pendulum at angle thetapi2 radians and angular velocity omega0 rads Find the time when the pendulum passes through D radians Your code should be flexible enough to handle pendula of different lengths and masses as well as different initial conditions clear all Set pendulum and environment parameters gravity981 msA2 lengthl m pendulum length masslO kg pendulum mass Set dt and initial conditions for all variables dtOOOS s Set time step size for numerical integration thetaOpi2 rad Positve is counterclockwise from bottom omegaOO rads Starts at rest Set event condition to control when simulation should stop Use this in While loop control thetalimit pi2 rad timel0 s thetaltheta0rad omegalomegaO rads indexl initialize index for time theta and omega array While thetaindex gt thetalimit Check if theta is at limit yet lUpdate the value of pendulum angular velocity based on Newtons39 Laws omegaindexl omegaindex gravitysinthetaindexlengthdt 2Update the value of pendulum angle based on thetaindexl thetaindex omegaindexdt 3Advance time one timestep timeindexltimeindexdt 4Increase array index by l to move to next location for storage indexindexl end 5Print the time when condition is satisfied tfinaltimeend thetadegthetalBOpi convert radians to degrees omegadegomegalBOpi convert radians to degrees 6Create subplot for angle and angular velocity figurel subplot2ll plottimethetadeg title39Pendulum Angle and Angular Velocity vs Time39 ylabel39Angle deg39 gr39d on subplot2l2 plot timeomegadeg xlabel 39Time sec 39 ylabel 39Angular Velocity degs 39 grid on Group Exercise Q1 How could we modify the code above so that it stops at a given end time rather than end angleposition lll Functions Functions or commands are defined blocks of code that live in their own files unctions are predefined blocks of code that can be used over and over again Parameters and variables may be passed into or returned from functions Functions can be userdefined or already defined in MATLAB Help files will always give instructions on how previously defined functions are used You can nest subfunctions within primary functions subfunctions can only be called from within the primaryparent function Functions are handy because you can write a block of code once and then reuse it as many times as you want in as many other programs as you want Using a given function from other pieces of code is referred to as calling that function For example let s say l have some code that l have programmed in a script file Example of Conditional Code Block 3 x y0 zl0 if xy use to compare for equivalence y z x 202 elseif x lt y otherwise if x is less than y y xl else if previous statements are false y 202 X end terminate code block but I want to be able to execute it for many different combinations of x y 2 To do this I could create a userdefined function by placing the above code in its own file called computeThis1m with the following syntax function x y z computeThislx y z a simple function that takes 3 input values w m nd returns the same 3 values that may or may not have been updated in the function body if x us to compare for equivalence y l x 2 elseif x lt y less than y else if previous statements are false y 202 x 239 end terminate code block end terminate parent function The above function requires 3 input variables x y and z The body of the function will modify these variables as needed and the updated values will be returned as 3 output variables x y 2 Here is howl could use the function computeThis1 by calling it from a separate script file eg main programm define three variables a4 b3 c7 call function that takes 3 variables and returns 3 Variables d e f computeThisla b c The function does not change the values of a b or c but instead it returns 3 values that I chose to save as d e and f I could have chosen to overwrite a b c but in this case I want to save the original values NOTE WELL The variable names in the function de nition le do not have to match the variable names that use When calling the function The order that the variables are passed in will be maintained that is xa yb and zc inside the function And on the return dx ey and fz It is also possible to nest functions ie subfunctions within other functions primaryparent functions For example function x y z computeThi52x y z a simple function that takes 3 input values and returns the same 3 values that maquot or ma39 not have been updated in Y the function body This is the parentprimary function w m if xy use to compare for equivalence Llt2 ll elseif x lt y less than 1 else if previous statements are false x z subElsex y end a terminate code block end a terminate parent function A subfunction that can only be used by functions in this file function 1 m n subElsel m n m l 2 l n end In the above example when computeThis2 uses the subElse function and we overwrite the original values for x y and 2 since these are being returned inside the parent function SOME RULES FOR FUNCTIONS Rule 1 To build a userdefined function you must have consistency between the mfile name and the function name Don t use a name already in use in MATLAB Use the exist command to check if you are unsure gtgt help exist EXIST Check if variables or functions are defined 0 if Adoes not exist 1 if A is a variable in the workspace 2 if A is an Mfile on MATLAB39s search path Rule 2 You must follow proper syntax in the function definition line That is the function output arguments what it computes go on the left of the in brackets and the function input arguments what it works on go on the right of the in parentheses For example the basic structure of the userdefined function FunctionNamem is as follows The first line of the file FunctionNamem must contain functionoutput7args FunctionNameinput7args then Functi nNamem Summary of this function goes here Detailod explanation of function goes here CODE GOES HEREl l i ll end Rule 3 Variables inside the function file are called local variables and cannot be accessed except from within the function itself ie they are protected Rule 4 When calling a function only the order of the inputsarguments and outputs matter not the names Rule 5 Functions can have any number of inputs or outputs including no inputs or outputs For example sometimes a function just returns a plot or screen display and has no outputs Or sometimes a function just initializes some local variables and has no inputs See pages 121 and 122 in Palm for other examples Rule 6 NEVER define global variables ie lgnore Palm top of pg 124 Group Exercise Q2 How could we modify your pendulum simulation script file so that it is a userdefined function called PendSim It should take lengthgravtfinaldtang0angve10 asinputsandrenun timeangangvel See posted code on Moode for solution NEXT TIME More on functions lncluding function handles function functions calling functions anonymous functions etc Lecture 18 Wednesday March 23 2011 Announcements 0 Case 3 is due today Case 4 will be posted by Friday afternoon and is due Wednesday April 14 0 Please take advantage of Prof Sawicki s Office Hours on M s and T s from 45PM 4212C EB3 or by appt Ben s hours are still being held Thursday afternoons Still have a couple of graded exams to be picked up 8H7 is up and will be due Th March 31St in lab 0 Exam 2 is scheduled for Wednesday April 6th inclass Practice exam 2 will be posted by afternoon of Wed March 30m We will review the practice exam Monday April 4th in class Reading for Next Time Debugging Palm Chapter 48 Ch 91 and 92 more on Numerical Differentiation and Integration Ch 8 on Linear Algebraic Equations SH EC Write two anonymous functions for hz 6e2 and gy 3cosy Then use themto plot 6e3 syfor 1ltylt20 Today s Goals Examples similar to 8H7 using Anonymous Functions and Function Functions IN CLASS PROBLEMS w GROUP HELP 1 Palm Ch 32 p129 T32Problems 1 2 3 2 Palm Ch 92 p 412 Problem 17 3 Palm Ch 32 p143 Problem 14 Rainfall Estimates I REMEMBER turn on your diary to save your Command Window gtgtdiary LectureMar23 m Anonymous Functions Palm Ch 3 pg 132133 Anonymous functions provide a quick inline method of defining and executing a function without having it in a separate mfile This is useful for simple expressions like exponential equations or polynomial equations Syntax is as follows function name argument list expression The function handle ie reference is just the name of yourfunction The argument list can be as long as you like or even empty see Palm page 133 The expression can only be a single executable MATLAB expresion To callexecute the anonymous function output variable name function handleargument list For example to define an anonymous function called sq that can compute the square of any input value X gt Example of an anonymous function with one input input arguments function expression sq x XA2 Then a bunch of ways to call it y sq5 z sq5 6 8 a6 b12 cl3 ha b c tsqh Anonymous functions can be defined with multiple inputs For example gt Example of an anonymous function with two inputs sumsqrt xy sqrtxA2 yA2 This defines the functiOJ sumsqrt To call it y sumsqrt45 Anonymous functions can call each other Palm p 133 For example gt oanmple of anOJymous functions calling each other f x XA3 g X 5Sinx h X gfX Function Functions Palm p124 129 eg fzero fminbnd fminsearch and fsolve and Function Handles p 124 Afunction handle is a referralreference to an already defined userfunction Syntax is as follows function handle function name Function handles are important for using MATLAB s function functions Le a function that calls another function over and over again Some examples of numerical operations that use function handles to callreference functions from other functions are 1 finding zeros of a function 2 minimizing or maximizing a function of one or several variables ie optimization See Table 321 in Palm for some key Function Functionsgt fminbndfunction name x1 x2 for single value minimization with the range x1ltxltx2 fminsearchfunction name x0 for multivariable minimization with init guess vector x0 fzerofunction name x0 use start value x0 to find a zero of single variable function N EXT TIME General rules for debugging data acquisition commands for lab Continue with addt l numerical differentiation and integration commands matrix operations simple statistics curve fitingregressioninterpolation Lecture 23 Monday April 11 2011 Announcements 0 Note NO lab next Thursday April 215 Spring Recess REMAINING ASSIGNMENTS 1 Case 4 Cortical Probe Optimization is due Wednesday April 20th in class 2 The last SH8 is now up and is due Wednesday April 27th in class 3 Case 5 Robot Arm Trajectory will be posted soon Due Wednesday April 27 h in class 4 Lab Exp 2 iEMG Controller Gain vs Artificial Muscle Force from April 7th data session writeup is due Thursday April 28th in lab Please continue to take advantage of Prof Sawicki s Office Hours on M s and T s from 45PM in 4212C EB3 or by appt Ben s hours are still being held Thursday afternoons EVALS Preliminary Evaluation 3 due this Wed April 13th 2 extra points on Exam 2 REMINDER Complete official course evaluations online neon signs around EB3 Be fair Reading for Next Time ReRead the Debugging Cheat Sheet finish Ch 8 on Solving Linear Algebraic Equations start Ch 6 on Simple Regression and CurveFitting Coming Up Ch 7 Simple Statistics Histograms and Interpolation SH EC Write a function that returns the value of the definite integral of the sine function over a range from a lower to upper limit that is specified by the user Do this using two different methods for integration eg trapz versus quad Today s Goals 1Refresh methods for Numerical Integration 2Get into Methods for Solving Systems of Linear Equations I REMEMBER turn on your diary to save your Command Window gtgtdiary LectureAprll m 1 Numerical Integration Palm Ch 9 pg 370377 FIVE METHODS of NUMERICAL INTEGRATION gt 1 SUM Sum of elements S SUMX is the sum of the elements of the vector X If X is a matrix S is a row vector with the sum over each column For ND arrays SUMX operates along the first nonsingleton dimension le is floating point that is double or single 8 is accumulated natively that is in the same class as X and S has the same class as X le is not floating point 8 is accumulated in double and S has class double 8 SUMXDM sums along the dimension DIMsum Example If X O 1 2 3 4 5 then sumX1 is 3 5 7 and sumX2 is 3 Forthis method MATLAB will assume unit spacing ie that dx 1 Therefore you must multiply S the SUM over the array for fx by the appropriate dx to get the correct yintegra fx dx See example code Mar30m for an example 2 CUMSUM Cumulative sum of elements CUMSUM Cumulative sum of elements For vectors CUMSUMX is a vector containing the cumulative sum of the elements of X For matrices CUMSUMX is a matrix the same size as X containing the cumulative sums over each column For ND arrays CUMSUMX operates along the first nonsingleton dimension CUMSUMXDM works along the dimension DIM Example IfX O 1 2 3 4 5 then cumsumX1 is O 1 2 and cumsumX2 is O 1 3 3 5 7 3 7 12 Forthis method MATLAB will assume unit spacing ie that dx 1 Therefore you must multiply the last element end of the CUMSUM output fx by the appropriate dx to get the correct yintegra fx dx See example code Mar30m for an example 3 TRAPZ lntegral over elements using the trapezoidal rule of integration TRAPZ Trapezoidal numerical integration Z TRAPZY computes an approximation of the integral of Y via the trapezoidal method with unit spacing To compute the integral for spacing different from one multiply Z by the spacing increment For vectors TRAPZY is the integral of Y For matrices TRAPZY is a row vector with the integral over each column For ND arrays TRAPZY works across the first nonsingleton dimension Z TRAPZXY computes the integral of Y with respect to X using the trapezoidal method X and Y must be vectors of the same length or X must be a column vector and Y an array whose first nonsingleton dimension is lengthX TRAPZ operates along this dimension Z TRAPZXYDM or TRAPZYDM integrates across dimension DIM of Y The length of X must be the same as sizeYDlM Example lfY 01 2 3 4 5 then trapzY1 is 15 25 35 and trapzY2 is 2 8 For ZtrapzY MATLAB will assume unit spacing ie that dx 1 Therefore you must multiply fy by the appropriate dx to get the correct zintegra fy dx For ZtrapzXY the spacing dx is calculated and taken into account so no need to multiply by dx See example code Mar30m for an example 4 QUAD DBLQUAD TRIPLEQUAD Uses quadrature to evaluate the integral over a definite range for defined functions in MATLAB rather than defined arrays or matrices of data QUAD Numerically evaluate integral adaptive Simpson quadrature Q QUADFUNAB tries to approximate the integral of scalarvalued function FUN from Ato B to within an error of 1e6 using recursive adaptive Simpson quadrature FUN is a function handle The function YFUNX should accept a vector argument X and return a vector result Y the integrand evaluated at each element of X Example Q quadmyfun02 where myfunm is the Mfile function function y myfunx y 1xquot32x5 or use a parameterforthe constant Q quadxmyfun2x502 where myfun2 is the Mfile function function y myfun2xc y 1xquot32xc Or could define myfun Anonymously my fun x 1xquot3 2x5 then Q quadmyfun02 No worries here regarding dx Simpson s Rule takes care of things See example code Mar30m or Apr1 1 m for an example 5 POLYINT POLYINT Integrate a polynomial analytically POLYINTPK returns a polynomial representing the integral of polynomial P using a scalar constant of integration K POLYINTP assumes a constant of integration KO See example code Mar30m for an example IN CLASS PROBLEMS ON NUMERICAL INTEGRATION w GROUP HELP 1 See accelerometer example 91 1 Palm p 372373 2 Palm Ch 91 T911 on p 373 3 Palm Section 91 6 on p 410 2 Solvinq Systems of Linear 39 quot Palm Ch 8 pgs 331356 There are three types of problems involving sets of linear equations MATLAB can handle all three types 1 UNIQUELY DETERMINED Unique Equations Unknowns x invAb gt solves Ax b using Matrix Inversion xA b also works Left Division 2 UNDERDETERMINED Unique Equations lt than Unknowns x A b gt solves Ax b using Left Division but makes at one unknown O x pinv Arb gt solves Ax b using PseudoMatrix Inversion rrefA b will return linear combinations of unknowns forming a general soln 3 OVERDETERMINED Unique Equations gt Unknowns x A b gt solves Ax b using Left Division But in the Ieastsquares sense ie will find values that satisfy all of the equations as closely as possible NOTE See the decision flow chart in Fig 851 Palm pg 355 for a rubric on what method to use and when by evaluating the rank of the problem IN CLASS PROBLEMS ON LINEAR EQUATIONS w GROUP HELP Palm Ch 81 1 on p 357 Matrix Inversion 2 Palm Ch 82 4 on p 358 Circuit Example Left Division 3 Palm Ch 83 11 on p 365 Underdetermined Example 4 Palm Ch 84 14 on p 366 Overdetermined Example N EXT TIME More on Linear Equations then begin Interpolation Regression CurveFitting Lecture 16 Wednesday March 16 2011 Announcements 8H6 is due today SL5 is due tomorrow Thursday March 17 Happy St Patty s Day Case 3 is due Monday March 215 Please take advantage of Prof Sawicki s Office Hours on M s and T s from 45PM 4212C EB3 or by appt Ben s hours are still being held Thursday afternoons You can pick up your graded exam after lab on Thursday 17 Questions on grading please see Prof Sawicki 8H7 will be up early next week Case 4 will be up late next week 0 Exam 2 is scheduled for Wednesday April 6th inclass Reading for Next Time Function Functions Palm p124129 ie fzero fminbnd fminsearch and fsolve Function Handles p 124 Debugging Palm Chapter 48 Ch 91 and 92 more on Numerical Differentiation and Integration Afterthat start looking at Ch 8 on Linear Algebraic Equations SH EC Work the Torus problem from 8H6 on the board Today s Goals 1 Cover gradientand difffor use to get velocity from delta length in Case 3 assignment Questions on Case 3 IN CLASS GROUP PROBLEM Do example similarto SL5 Palm Ch 4 page 216217 Problem 48 Writeup Inventory Model as a function 2 Discuss Anonymous Functions and Subfunctions I REMEMBER turn on your diary to save your Command Window gtgtdiary LectureMar16m ll Numerical Derivative Two Methods DIFF Difference and approximate derivative DIFFX for a vector X is X2X1 X3X2 XnXn1 GRADIENT Approximate gradient FXFY GRADIENTF returns the numerical gradient of the matrix F FX corresponds to dFdx the differences in x horizontal direction FY corresponds to dFdy the differences in y vertical direction The spacing between points in each direction is assumed to be one When F is a vector DF GRADIENTFis the 1D gradient lll More on Functions MW Palm Ch 3 pg 132133 Anonymous functions provide a quick inline method of defining and executing a function without having it in a separate mfile This is useful for simple expressions like exponential equations or polynomial equations Syntax is as follows function handle argument list expression The function handle ie reference is just the name of yourfunction The argument list can be as long as you like or even empty see Palm page 133 The expression can only be a single executable MATLAB expresion To callexecute the anonymous function output variable name function handeargument list For example to define an anonymous function called sqthat can compute the square of any input value x gt Example of an anonymous function with one input function handle input arguments function expression sq x XA2 This defines a function sq that computes the square of the input value x which can be an array note element Wise definition z sq5 6 8 a6 b12 cl3 ha b c tSQh Anonymous functions can be defined with multiple inputs For example gt Example of an anonymous function with two inputs sumsqrt xy sqrtxA2 yA2 This defines the function sumsqrt To call it y sumsqrt45 Anonymous functions can call each other Palm p 133 For example gt hxample of alotymous functions calling each other f x XA3 g X 5SinX h X 9fX answerh 2 Subfunctions Palm p 134 You can nest subfunctions within primary functions subfunctions can only be called from within the primaryparent function For example x3 y0 210 function x y z computeThi52x y z a simple function that takes 3 input values and returns the same 3 values that may or may not have been updated in the function body This is the parentprimary function mm mm if xy use to compare for equivalence y z x 202 elseif x lt y less than y x else if previous statements are false x z subElsex y z y end a terminate code block end a terminate parent function A subfunction that can only be used by functions in this file function l m n subElsel m n ml 2 ln end In the above example when computeThis2 uses the subElse function and we overwrite the original values for x y and 2 since these are being returned inside the parent function N EXT TIME Begin with key function functions Palm pg 128 and then move into numerical analysis topics signal processing curve fittingregression data acquisition differentiation and integration matrix operation Also hand outupload a cheat sheet on DEBUGGING 9 2m 6 A certain object moves with the velocity u1givcn in Lhe table below Determine the object s position r1 all 10 5 if x0 3 The following list gives the measured breaking force in newtons for at sample of 60 pieces of certain type of cord Plot the absolute frequency histogram Try bin widths of 10 30 and 50 N Which gives the most meaningful histogram Try to nd a better value for Lhe bin width 311 138 340 199 270 255 332 279 231 296 1 98 269 257 236 313 281 288 225 216 250 259 323 280 205 279 159 276 354 278 221 192 281 204 361 321 282 254 273 334 172 240 327 261 232 208 213 299 318 356 269 355 232 275 234 V39 740 331 222 370 226 For the data given in Problem 3 1 Plot the scaled freqUency histogram b Compute the mean and standard deviation and use them to estimate the lower and upper limits of breaking force corresponding to 68 and 96 percent of cord pieces of this type Compare these limits with those of the data 57 25 The following data are the measured temperature T of water owing from 2 it is turned on at time t 0 ab Jr a r E E E E e 2 1 Plot the data connecting them rst with strnivht lions and then with a cubic spline Estimate the temperature values at me following times using lineal in xerpnlation and then cubic spline interpolation 06 1547 F3 Use both the linear and cubic spline interpolations to estimate he time it will take for the temperature to equal the following values T 75 85 90 105 V 6 Flurd ows in pipe networks can be analyzed in a manner similar to that used for electric resistance networks Figure P6 shows a network with three pipes The vulume nwgates in the pipes are 1 1 and q The pressures at the pipe ends are pa pp and pp The pressure at thejunction is In Under certain condiLions the pressure llow rate relation in a pipe has the same form as the voltagecurrent relation in a resistor Tltus1 for Lhe three pipes we have 1 m V Rfth 41Rflm rm Fl PM El i 7 it t 171 f 139 q RzU I Pa 1 FL ape WP 1 In Em In where the R are the pipe resistances From conservation of mass III 12 4 113 a Set up these equutions in a matrix form Ax b suitable for solving for Lhc three ow rates q 3 and q and the pressurepi given the values of pressures pmpb and pr and the values of resistnnces R1 R1 and R3 Find the expressions for A and b in part a or the d I Use MATLAB to solve thc mamx cquauonsobtarne 7 2 case where p z 4320 lb pl 3600 lbftz and pr 2880 lhrlt 2 These correspond to 30 25 and 20 psi respectively l psr l and atmospheric pressure is 147 psi Use the resistance ValUES 10 000 R1 14 000 lb secL5 These values corresppnd to fuel 01 ec owing through pipes 2 ft long with 2 and l4 m diameters ftlsgm2 tively The units of the answers are ft lscc for the ow rates rm f or pressure it Equot The population data for a certain country are as follows 2006 2007 2003 7009 117 126 138 149 109 Obtain n function that describes these datn Plot tile function nod the data on the some plot Estimate when the population Will be double it 2004 size 3 l9 Chemists and engineers must be able to predict the chan es in chemical concenu39ntion in a reaction A model used for mnny single reactttnt processes is Rate of change of concentration ItCquot where C is the chemical concentration and kis the rate constant The the reaction is the value of the exponent 71 Solution methods for differential equations which are discussed in Chapter 9 can show that the solution for a rstorder reaction n t is Cl C02quotquot The solution for a secondorder reaction 71 2 is l l mv m i kt and the solution for a thirdorder reaction n 2 3 is i7 k1 2011 260 The preceding data describe at certain reaction By examining residuals determine whether this is a firstorder secondorder thirdorder reaction and estimate the value of Lht rate constnn Lecture 17 Monday March 21 2011 Announcements Case 3 is due Wednesday March 23 Please take advantage of Prof Sawicki s Office Hours on M s and T s from 45PM 4212C EB3 or by appt Ben s hours are still being held Thursday afternoons Still have some graded exams to be picked up 8H7 will be up by tomorrow afternoon Case 4 will be up late this week Exam 2 is scheduled for Wednesday April 6th inclass Reading for Next Time Debugging Palm Chapter 48 Ch 91 and 92 more on Numerical Differentiation and Integration Afterthat start looking at Ch 8 on Linear Algebraic Equations Today s Goals Discuss Subfunctions Anonymous Functions and Function Functions IN CLASS GROUP PROBLEM Do example in Palm Ch 4 page 216217 Problem 48 Define and use a function to code up the Inventory Model I REMEMBER turn on your diary to save your Command Window gtgtdiary LectureMar21m II More on Functions Subfunctions Palm p 134 You can nest subfunctions within primary functions subfunctions can only be called from within the primaryparent function For example x3 y0 210 function x y z computeThi52x y z 9 a simple function that takes 3 input values and returns the same 3 values that may or may not have been updated in the function body This is the parentprimary function if xy use to compare for equivalence y z X 139 elseif x lt y less than y xl else if previous statements are false x y z subElsex y 2 end terminate code block end terminate parent function A subfunction that can only be used by functions in this file function n 5ubElsel m m l 2 l n end In the above example when computeThis2 uses the subEIse function and we overwrite the original values for x y and 2 since these are being returned inside the parent function Anonymous Functions Palm Ch 3 pg 132133 Anonymous functions provide a quick inline method of defining and executing a function without having it in a separate mfile This is useful for simple expressions like exponential equations or polynomial equations Syntax is as follows function name argument list expression The function handle ie reference isjust the name of yourfunction The argument list can be as long as you like or even empty see Palm page 133 The expression can only be a single executable MATLAB expresion To callexecute the anonymous function output variable name function handleargument list For example to define an anonymous function called sqthat can compute the square of any input value x gt Example of an anonymous function with one input function handle input arguments function expression a function sq that computes the sq x XA2 This defines which can be an array note square of the input value x element wise definition Then a bunch of ways to call it y Sq5 z sq5 6 8 a6 b12 cl3 ha b c tsqlthgt Anonymous functions can be defined with multiple inputs For example gt Example of an anonymous function with two inputs sumsqrt xy sqrtxA2 yA2 This defines the function sumsqrt To call it y sumsqrt 4 5 Anonymous functions can call each other Palm p 133 For example gt Example of anonymous functions calling each other x x A3 g x 5sin x h X gfx answerh 2 Function Functions Palm p124 129 eg fzero fminbnd fminsearch and fsolve and Function Handles p 124 Afunction handle is a referralreference to an already defined userfunction Syntax is as follows function handle function name Function handles are important for using MATLAB s function functions Le a function that calls another function over and over again Some examples of numerical operations that use function handles to callreference functions from other functions are 1 finding zeros of a function 2 minimizing or maximizing a function of one or several variables ie optimization See Table 321 in Palm for some key Function Functionsgt fminbndfunction name x1 x2 for single value minimization with the range x1ltxltx2 fminsearchfunction name x0 for multivariable minimization with init guess vector x0 fzerofunction name x0 use start value x0 to find a zero of single variable function Do example in Palm Ch 3 p143 Problem 14 Rainfall Estimates N EXT TIME Some on debugging then move into numerical analysis topics signal processing curve fittingregression data acquisition quot and a matrix

### BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.

### You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

## Why people love StudySoup

#### "I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

#### "When you're taking detailed notes and trying to help everyone else out in the class, it really helps you learn and understand the material...plus I made $280 on my first study guide!"

#### "I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

#### "It's a great way for students to improve their educational experience and it seemed like a product that everybody wants, so all the people participating are winning."

### Refund Policy

#### STUDYSOUP CANCELLATION POLICY

All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email support@studysoup.com

#### STUDYSOUP REFUND POLICY

StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here: support@studysoup.com

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to support@studysoup.com

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.