92.272 Introduction to Programming with MATLAB User-Deﬁned Functions, Part 2 A. Anonymous Functions It is possible to deﬁne a function within a script...

0 downloads 0 Views 28KB Size

Loading...

A. Anonymous Functions It is possible to define a function within a script file, a function file, or the command window without creating a separate function file. Functions defined in this way are called anonymous functions. Here is an example of a script file in which an anonymous function is defined. circle_area = @ (r) pi*r^2; r=1; while r>0 r = input(’Enter the radius of a circle. Enter a negative value to stop the program: ’); if r>0 area = circle_area(r); fprintf(’The area of your circle is %.2f\n’,area) end end The first line of the script file defines a function named circle_area which has one input argument (r) and one output (the area of a circle of radius r.) The command defining an anonymous function has the form function_name = @ (list of input arguments) function_formula. B. Function Functions Some MATLAB functions require the name of another function as an input argument. For example, the built-in MATLAB routine fzero finds a root of a function, but you have to tell fzero what function you want a root of. Try this example. First create the function file f.m defining the function given by f (x) = x − cos(x): function y = f(x) y = x - cos(x); end In the command window, type the command fzero(@f, 1) This will calculate a root of the function f near x = 1. Notice that the first input argument to fzero is the @ symbol followed directly by the function file name. (Exception to the rule: If your function has been defined as an anonymous function, you don’t need the @ symbol before the function name.)

C. Subfunctions It is possible to define more than one function within a single function file. If you do this, the first function defined in the file is called the primary function and the others are called subfunctions. Here is an example of a file containing multiple function definitions. function [circ, area] = circle_measurements(radius) %circle_measurements calculates the circumference and area of a circle of %given radius %Input argument: %radius = radius of circle %Output arguments: %circ = circumference of circle %area = area of circle circ = circumf(radius); area = circle_area(radius); function perim = circumf(r) perim = 2*pi*r; end function area_of_circle = circle_area(r) area_of_circle = pi*r^2; end end

Try executing this command in the command window: [c, a] = circle_measurements(1)

Practice Problems. 1. Modify the script file example in the section on anonymous functions to calculate both circumference and area. 2. Use fzero to find a root of the function given by f (x) = tan(x) − x near x = 4. 3. Create a function file that calculates the volume and surface area of a sphere given the radius of the sphere. Use subfunctions to calculate volume and surface area.