{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

19 - MATLAB Programming II

# 19 - MATLAB Programming II - Engineering 101 Quote of the...

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Engineering 101 Quote of the Day The cure for boredom is curiosity. There is no cure for curiosity. - Dorothy Parker MATLAB Programming II Selection on Logic Vectors What does the following do, if x is an array (and, therefore, the condition expression is an array of bools)? bools)? if x > 20 disp('condition disp('condition is true') else disp('condition disp('condition is false') The "condition is true" iff the condition holds for all elts of x, otherwise the "condition is false" Example: Vector Equality Suppose x and y are vectors of the same length if x == y disp('vectors disp('vectors are equal') else disp('vectors disp('vectors not equal') This works as intended Example: Vector Equality Suppose x and y are vectors of the same length if not(x == y) disp('vectors disp('vectors are not equal') else disp('vectors disp('vectors are equal') This does not work as intended...why? Try x = `abc' and y = `abd' `abc' `abd' Example: Vector Equality Suppose x and y are vectors of the same length if not(all(x == y)) disp('vectors disp('vectors are not equal') else disp('vectors disp('vectors are equal') This works as intended because: all(A): Returns true if all elements in A are true Returns false if any elements in A are false 1 .p Files MATLAB stores function definitions in an internal format called pcode It avoids repeating some interpreter processing (e.g., parsing text) every time a function is invoked It's a form of compilation, but not to a native machine language Nested Function Definitions You can also define a function within another function definition: function [a, b] = someFunction (x, y) ... function c = nestOne(z) nestOne(z) ... end nestOne is a nested function of someFunction someFunction is the nesting function of nestOne ... end Create pcode with the command: pcode fn_name This creates a file called fn_name.p fn_name.p Stored in a binary format (not readable in text editor) Nested Functions Unlike subfunctions, nested functions share the subfunctions, scope of their nesting function: They can access and modify variables in the nesting function's scope Variables introduced in the nested function are accessible within the nesting function's scope The formal parameters (input and output) of the nested function are not accessible to the nesting function Nested Functions A function can call its nested functions A nested function can call its nesting function (recursion), as well as any functions its nesting function can call All nesting and nested functions must finish with the end statement Multiple Nested Functions (Same Level) function [a, b] = someFunction (x, y) ... function c = nestOne(z) nestOne(z) ... end ... function d = nestTwo(w) nestTwo(w) ... nestOne and nestTwo are nested functions of someFunction end someFunction is the nesting function of nestOne ... and nestTwo end Multilevel Function Nesting function y = A (a1,a2) (a1,a2) ... function z = B(b1,b2) ... function w = C(c1,c2) ... end end function u = D(d1,d2) ... function h = E(e1,e2) ... end end ... end Function scope What can A call? A, B, and D What can B / C call? A, B, C, and D What can D / E call? A, B, D, and E 2 Multilevel Function Nesting function y = A (a1,a2) (a1,a2) ... function z = B(b1,b2) ... function w = C(c1,c2) ... end end function u = D(d1,d2) ... function h = E(e1,e2) ... end end ... end Default Arguments in Functions MATLAB functions can accept and return different numbers of arguments. This is handled by using the values nargin and nargout. nargout. Variable scope Which functions have access to a1, a1, a2, and y? a2, All functions The other formal parameters? B / C have access to B's formals Only C has access to C's formals The same applies to D and E Other variables (e.g. what if B introduces b3)? b3)? b3 would be accessible to A and C It would also be accessible to D and E, but only if A refers to b3. b3. nargin/nargout nargin is equal to the number of input arguments passed into the function. nargout is equal to the number of output arguments requested from the function. Using nargin Let's say I want to have a procedure that has some default arguments if none is specified. function val = simulate(time, startval) val = zeros(time); if nargin<2 | isempty(startval) val(1) = 0; else val(1) = startval; end for t = 2:time val(t) = someFunction(val(t-1)); someFunction(val(tend Using nargout function [m,v]=MeanVar(X) % MeanVar Computes the mean and variance 1 Exercise Which function will take in up to 3 matrices and return the average of these matrices? 2 n=size(X,1); m=mean(X); if nargout>1 temp=Xtemp=X-m(ones(n,1),:); v=sum(temp.*temp)/(nv=sum(temp.*temp)/(n-1); end 3 Which program will take in up to 4 string arguments and save the matrix with the name corresponding to each string in a .mat file with the same name? i.e. savevars(`this', `that') would save the matrix this in the file this.mat and the matrix that in the file that.mat Functions as Input Subfunctions and the nested function facility make it relatively easy to encapsulate helper functions within their primary function What we would really like is to supply the functions f and df as part of the input. So far, the only way to invoke a function is to call based on name associated with definition in program text To pass functions as input requires a way to construct a function as a data element 1 2 ...here's where function handles come in Function Handles Create a function handle by prepending @ before a function name. For example, suppose we have defined: function y = myfunc(x) y = x^3 + x 3; Anonymous Functions Suppose you want to make a simple function that does a single calculation Also, you don't want to make a new .m file to do this You can do this using anonymous functions which can be created in the command window, in a script file, or in a normal user function Then @myfunc is a function handle, and feval( myfunc, expr) feval(@myfunc, expr) behaves just like myfunc(expr) myfunc(expr) If we assign myf2 = @myfunc , then myf2(expr) also @myfunc myf2(expr) behaves just like myfunc(expr) myfunc(expr) Anonymous Functions name = @ (argumentList) expression (argumentList) name: name: the name of the function argumentList: argumentList: a list of one, or many, independent variable(s) passed in as arguments separated by commas expression: expression: a single, valid mathematical MATLAB expression written according to the dimensions of the arguments Anonymous Functions name = @ (argumentList) expression (argumentList) Notes: expression can contain built-in or user functions builtexpression can use predefined variables, however, it will use those same variables every time it is used unless it is redefined coolFunc = @ (m, n) m^2 + n 4*x*y The values passed to the anonymous function are assigned to variables based on their order in argumentList 4 Calling Anon Fns with Handles Examples: calcThis = @ (m) m^2 2*m + 1; (m 2*m Example What does b equal after executing the following code? >> func = @ (x,y) sqrt(x.^2-y.^2); sqrt(x.^2>> a = func([5 5], [3 3]); >> b = 3 + func(a,a); 1 2 4 4 0 0 3 5 5 4 3 3 calcThat = @ (m,n,p) n 2*p + m; (m,n,p) 2*p calcIt = @ (m) m.^2; (m calcIt([3 4 5]) Using Anonymous Functions Example: f = @(x) x.^3 + x 3 df = @(x) 3*x.^2 + 1 Use them in expressions: plot(1:20,f(1:20)) Pass them into functions: someFunc(1.0,f,df) someFunc(1.0,f,df) Handles are not actually needed: someFunc(1.0, someFunc(1.0, @(x) x.^3 + x 3, ... @(x) 3*x.^2 + 1 ) Next Lecture Subarrays and Vectorization calcThat(5,4,3) calcThis(5) 16 3 [9 16 25] Anonymous Functions: Scope @ (paramList) expr (paramList) Try this in MATLAB Variables in paramList have scope local to anonymous function Body expr may also refer to any variables or functions available in the scope where anonymous function was defined Note: Any external references in the anon function are evaluated at definition time, not at runtime... x = 999; z = -111; myFunc = @(z) sqrt(x+z); y = myFunc(601) x = 24; y2 = myFunc(601) myFunc2 = @(y) 2*myFunc(y); y3 = myFunc2(601) myFunc = @(x) x^2; y4 = myFunc2(601) 5 ...
View Full Document

{[ snackBarMessage ]}

### What students are saying

• As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

Kiran Temple University Fox School of Business ‘17, Course Hero Intern

• I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

Dana University of Pennsylvania ‘17, Course Hero Intern

• The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

Jill Tulane University ‘16, Course Hero Intern