Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMPLETE GUIDE TO MATLAB ®

Similar presentations


Presentation on theme: "COMPLETE GUIDE TO MATLAB ®"— Presentation transcript:

1 COMPLETE GUIDE TO MATLAB ®
Chapter 3 : Types of Functions

2 Chapter Outline Nested functions Private functions
Overloaded functions Function handles Chapter Outline Nested functions Private functions Overloaded functions Function handles

3 Nested Function function T = tax(income)
You can define one or more functions within another function in MATLAB. These inner functions are said to be nested within the function that contains them. To write a nested function, simply define one function within the body of another function in an M-file. Like any M-file function, a nested function contains any or all of the components described in Basic Parts of an M-File. In addition, you must always terminate a nested function with an end statement: function x = A(p1, p2) ... function y = B(p3) end End A simple nested function is shown below : function T = tax(income) adjusted_income = max(income , 0); T = compute_tax; function t = compute_tax t = 0.28*adjusted_income; %call function %tax(10000) function T = tax(income) adjusted_income = max(income , 0); T = compute_tax; function t = compute_tax t = 0.28*adjusted_income; end %call function %tax(10000)

4 Private Functions Reside in a subdirectory named private
Only accessible to functions in parent directory Only accessible to functions in parent directory. private directory Private Functions Private functions are functions residing in a subdirectory named private and are accessible only to functions in the parent directory. For example, assume the directory \Project A is on the MATLAB search path. A subdirectory Project A\private can contain functions that can only be called by the functions in \Project A. Because private functions are invisible outside of the parent directory, they can use the same names as functions in other directories. MATLAB looks for private functions before standard M-file functions, so it will find a private function named func1.m before finding a nonprivate M-file named func1.m. You can create your own private directories simply by creating a subdirectory or folder called private below the directory to access the private functions. (Make sure that the parent directory is on the MATLAB path.) Any M-files that you place in the private directory are accessible only to functions in the directory above it. Note: Do not put the private directory on the MATLAB search path. Only the parent of the private directory should be on the MATLAB search path.

5 Chapter Outline Nested functions Private functions Function handles
Overloaded functions Function handles

6 Object Oriented Programming (OOPs) in MATLAB
What is Object-Oriented Programming? Helps you work on big projects which has activities/elements with properties that can be grouped in a structured way What are operations and how do I perform them? First define the elements – class Define the properties of the class Define methods – constructor for creating new objects/elements/activities Other Methods are defined to manipulate the input data What is object-oriented programming? Object-oriented programming is an approach to writing programs that emphasizes the use of classes and objects. A class is a defined data type. Classes can be built into MATLAB or users can add their own classes into MATLAB. Whenever a value is returned of a particular class, the value is an object of that particular class. For example, built-in MATLAB classes are int, double, cell, and struct. After defining a class and using objects from this class, you probably want to perform operations with these objects. Prior to creating operations there are two questions that are answered: What are operations? How do I perform operations? Operations defined to work with objects of a particular class are known as methods of that class. For example, a polynomial class might redefine the addition operator (+) so that it correctly performs the operation of addition on polynomials.

7 Object Oriented Programming
Classes In class definition we create a prototype or specification for construction of a objects of a certain class or type. Eg. classdef person Terminology: Classes One of the primary benefits of an object- oriented programming language is the ability to organize complex code by modeling various components as real-world objects. A class contains all of the instructions for creating an object. The main idea behind classes is to describe/ to model an object, or we called it as instantiate an object. Properties List of properties by which the class is desired to be characterized Objects Run-time instance of a class

8 obj=Person(name,age,gender) obj.name=name; obj.age=age;
classdef Person properties name age gender end methods function obj=Person(name,age,gender) obj.name=name; obj.age=age; obj.gender=gender; End function y=isRetired(obj) y=obj.age > 65; Object Oriented Programming There are two block in this diagram. First is the program , second is the Real World. An object is an instance of a class. In another words, a class is to describe an object. For example, there is a person to model. So, we have a person , and this person is the object to be modeled. The details of this person, or we called this details as the property in program will be data or variable in our program. For example, this details/ or property of object might be the name, age , department and salary. Then, we will need to model the behaviour of object. BBut, what is the behaviour of object. The behavior is something the object is doing. In more specific, you can see this behavior as the task of the object doing. For example, a car has 4 doors, so this 4 doors is the property of object. Then lets say this car is running. Then running is the behaviour. The example here show the behaviour of the person: a promotion or salary adjustment, then in our program , we use a specific term called method to describe this behaviour.

9 >> x=Person('john',35,'male') x = Person Properties:
x = Person Properties: name: 'john' age: 35 gender: 'male' Methods General Procedure for Creating Objects In MATLAB In order to create your user-defined classes in MATLAB, you must follow some basic steps. The basic steps for creating user-defined classes are listed below: 1. Choose the data structure to be used by the new class. In MATLAB, objects are stored as structures. The fields of the structure are visible only within the methods for the class. 2. Add a class directory to the MATLAB path by using either the pathtool or the addpath function. A class directory begins with the at symbol and uses the class name that you want to create. For example, you can add a directory named: ML_files to the MATLAB search path and then add a subdirectory if you are creating a class named polynom. 3. Create a class constructor method. In directory, create a function M-file that lets you create an object based on the following three conditions. You should be able to create this object if no input arguments are specified. You should be able to create this object if an object of the same type is an input argument. You should be able to create this object if you put in any other type of input argument. The steps that are listed above are explained further in the remainder of this section. >> x.isRetired ans =

10 Access to object properties
Exercise Extend the Person class with a list of book numbers that a person borrowed and the method holdsBook to check whether a person has borrowed a particular book. Check your class with the commands: x=Person('John',35,'male'); x.books=[ ]; x.holdsBook(3) Access to object properties x.age=70; x.isRetired returns ‘1’ Setting up Class Directories What is a class directory? M-files defining the methods for a class are collected together in a directory referred to as the class directory. Where should it be set up? The directory name should be the name of the class with in front of it The class directory should be a subdirectory of a directory that has been added to the MATLAB path (e.g., where ML_files is the name of a directory added to the MATLAB path). In this section we will create a class for polynomials as an example to better understand object-oriented programming. To do so, we will create a class directory called polynom. Since we are working under c:\class and since this is part of the MATLAB path, we will add our class directory there. Note The commands addpath or pathtool can be used to add the ML_files directory to the MATLAB path.

11 Use ‘handle’ to pass class – person as reference not a value.
Class Constructor Method The class constructor method creates an object of a certain class. Below are some conditions that the class constructor must satisfy: directory must contain an M-file known as the constructor for that class. The name of the constructor is the same as the name of the directory, class_name (e.g polynom.). The constructor creates the object by initializing the data structure of the class. A constructor must handle three possible combinations of inputs: The input arguments used to create an object of the class (data) >> a = polynom([3 1 5]) Given the input arguments, a new object is created. An object of the same class >> b = polynom(a) When the input is an object of the same class, a copy of the object is made. No inputs >> c = polynom When no input is given, a default object is created. Use ‘handle’ to pass class – person as reference not a value. classdef Person < handle function changeAge(obj,age) obj.age=age; end >>x=Person('John',35,'male'); >>x.changeAge(70); >>x.age

12 classdef date % write a description of the class here. properties % define the properties of the class here, (like fields of a struct) minute = 0; %calcSecs(d2) hour; day; month; year; end properties(Constant = true) DAYS_PER_YEAR = 365; MONTHS_PER_YEAR = 12; WEEKS_PER_YEAR = 52; Methods (Access=public) % Change to private and run % methods, including the constructor are defined in this block function obj = date(minute,hour,day,month,year) % class constructor if(nargin > 0) obj.minute = minute; obj.hour = hour; obj.day = day; obj.month = month; obj.year = year; function obj = rollDay(obj,numdays) obj.day = obj.day + numdays;

13 1st argument is the object of the class
……..Contd Create Object >>d1=date(0,3,27,2,1998) >>d2=date(1,0,0,0,2002) Properties >>day =d1.day %Access the day property >>d1.year=2008; %Set the year property Methods >>d1=rollDay(d1,3) % rollDay methods adds a specified number of days to the day property Exercise Add the following methods function sec=calcSecs(obj) sec=obj.minute*60 + obj.hour*60*60+obj.day*24*60*60; end And calculate secs for object date 1 min. 1st argument is the object of the class

14 feval Function Syntax If function is a quoted string containing the name of a function (usually defined by an M-file), then feval(function,x1,...,xn) evaluates the function with the given arguments. [y1,y2,...] = feval(function,x1,...,xn) The feval Function The feval command executes a function that you have specified with its needed inputs. The syntax for the feval command is The function parameter must be a simple function name; it cannot contain path information. If function is a quoted string containing the name of a function (usually defined by an M-file), then feval(function,x1,...,xn) evaluates the function with the given arguments. >> x = 0:.1:2*pi; >> y = feval('sin', 0:.1:2*pi); >> plot(x,y) [y1,y2,...] = feval(function,x1,...,xn) >> x = 0:.1:2*pi; >> y = feval('sin', 0:.1:2*pi); >> plot(x,y)

15 Representing Mathematical Functions
A mathematical function can be represented in MATLAB as a function Representing Mathematical Functions A mathematical function can be represented in MATLAB as a function function y = my_humps(x) y = 1 ./ ((x-.3).^ ) + 1 ./ ((x-.9).^ ) - 6; y = 1 ./ ((x-.3).^ ) + 1 ./ ((x-.9).^ ) - 6; function y = my_humps(x) y = 1 ./ ((x-.3).^ ) + 1 ./ ((x-.9).^ ) - 6;

16 Function Handles What are they?
MATLAB data types that contain information used in referencing a function. Benefits: Allow wider access to subfunctions and private functions. Improve performance in repeated operations. Reduce the number of files that define your function. Ensure reliability when evaluating functions. Function Handles Function handles are MATLAB data types that contain information used in referencing a function. Benefits: Allow wider access to subfunctions and private functions. A handle can be created for a subfunction while it is in scope (that is, it is created within the M-file that defines the subfunction), and passed outside of that M-file for evaluation. Improve performance in repeated operations. Performance delay associated with function lookup is incurred only once when the function handle is created. Reduce the number of files that define your function. Rather than use subfunctions, functions can be grouped using function handles. Ensure reliability when evaluating functions. Overloaded methods can be isolated so that the correct method is called. General comments Function handles are similar to pointers. They are better than using the name of the function for function functions (such as feval). By using function handles name conflicts can be avoided.

17 Function Handles – continued
Syntax fhandle Example Function Handles (continued) The syntax for creating a function handles is fhandle Note: The maximum length for a function name is 31 characters. Example Construct a function handle in MATLAB using the at before the function name. Note: The function_name should not include the path of where the file is located, for example, fhanlde is not valid. function y = my_humps(x) y = 1 ./ ((x-.3).^ ) + 1 ./ ((x-.9).^ ) - 6; % end of file my_humps.m ----- >> x = 0:.1:2; >> fhandle >> out = feval(fhandle,x); % or… out = feval('my_humps',x); >> plot(x,out); function y = my_humps(x) y = 1 ./ ((x-.3).^ ) + 1 ./ ((x-.9).^ ) - 6; % end of file showdemo.m ----- >> x = 0:.1:2; >> fhandle >> out = feval(fhandle,x); % or… out = feval(‘my_humps’,x); >> plot(x,out);

18 Function Handles – continued
The command functions allows the function handle information to be displayed. This function is helpful when working with overloaded function handles. >> fhandle >> functions(fhandle) ans = function: 'my_humps' type: 'simple' file: 'c:\class\my_humps.m' Function Handles (continued) Given the handle of a function, fhandle, you can display the function handle information using the functions command. For example, This function is helpful when working with overloaded function handles. >> fhandle >> functions(fhandle) ans = function: 'my_humps' type: 'simple' file: 'c:\class\my_humps.m'

19 Function Handle Operations
Converting function handle to function name Converting function name to function handle >> fhandle >> func2str(fhandle) ans = sin Function Handle Operations To convert a function handle to a function name, use To converting a function name to a function handle, use See “Function Handle Operations” in the MATLAB documentation. >> fhandle >> func2str(fhandle) ans = sin >> fh = str2func('sin') fh = @sin >> fh = str2func('sin') fh = @sin

20 Section Summary Nested Function Private Function Objects in MATLAB
Constructing a new class Function precedence Function Handles Section Summary Nested Function Private Function Objects in MATLAB Constructing a new class Overload functions Function precedence Function Handles


Download ppt "COMPLETE GUIDE TO MATLAB ®"

Similar presentations


Ads by Google