Using MATLAB (779505), страница 91
Текст из файла (страница 91)
You create a function handle within a confined scopeso that it provides access to that method alone. The function shown below,21-2321Function Handlestest_myfun, receives this function handle in the first argument, arg1, andevaluates it.Before evaluating the handle in arg1, test_myfun checks it against anotherfunction handle that has a broader definition. This other handle, @myfun,provides access to all methods for the function. If the function handle in arg1represents more than the one intended method, an error message is displayedand the function is not evaluated.function test_myfun(arg1, arg2)if isequal(arg1, @myfun)disp 'Function handle holds unexpected context'elsefeval(arg1, arg2);end21-24Saving and Loading Function HandlesSaving and Loading Function HandlesYou can use the MATLAB save and load functions to save function handles toMAT files, and then load them back into your MATLAB workspace later on.This example shows an array of function handles saved to the file, savefile,and then restored.fh_array = [@sin @cos @tan];save savefile fh_array;clearload savefilewhosNameSizeBytes Classfh_array1x348 function_handle arrayGrand total is 3 elements using 48 bytesPossible Effects of Changes Made Between Save and LoadIf you load a function handle that you saved in an earlier MATLAB session, thefollowing conditions could cause unexpected behavior:• Any of the M-files that define the function have been moved, and thus nolonger exist on the path stored in the handle.• You load the function handle into an environment different from that inwhich it was saved.
For example, the source for the function either doesn’texist or is located in a different directory than on the system on which thehandle was saved.• You have overloaded the function with additional methods since the savewas done. The function handle you just loaded doesn’t know about the newmethods.In the first two cases, the function handle is now invalid, since it no longermaps to any existing source code. Although the handle is invalid, MATLAB stillperforms the load successfully and without displaying a warning. An attemptto evaluate the handle however results in an error.21-2521Function HandlesHandling Error ConditionsThe following are error conditions associated with the use of function handles.Handles to Nonexistent FunctionsIf you create a handle to a function that does not exist, MATLAB catches theerror when the handle is evaluated by feval.
MATLAB allows you to assign aninvalid handle and use it in such operations as func2str, but will catch andreport an error when you attempt to use it in a runtime operation. For example,fhandle = @no_such_function;func2str(fhandle)ans =no_such_functionfeval(fhandle)??? Error using ==> fevalUndefined function 'no_such_function'.Including Path In the Function Handle ConstructorYou construct a function handle using the at sign, @, or the str2func function.In either case, you specify the function using only the simple function name.The function name cannot include path information.
Either of the followingsuccessfully creates a handle to the deblank function.fhandle = @deblank;fhandle = str2func('deblank');The next example includes the path to deblank.m, and thus returns an error.fhandle = str2func(which('deblank'))??? Error using ==> str2funcInvalid function name'matlabroot\toolbox\matlab\strfun\deblank.m'.21-26Handling Error ConditionsEvaluating a Nonscalar Function HandleThe feval function evaluates function handles only if they are scalar. Callingfeval with a nonscalar function handle results in an error.feval([@sin @cos], 5)??? Error using ==> fevalFunction_handle argument must be scalar.21-2721Function HandlesHistorical Note - Evaluating Function NamesEvaluating a function by means of a function handle replaces the formerMATLAB mechanism of evaluating a function through a string containing thefunction name.
For example, of the following two lines of code that evaluate thehumps function, the second supersedes the first and is considered to be thepreferable mechanism to use.feval('humps', 0.5674);% uses a function name stringfeval(@humps, 0.5674);% uses a function handleTo support backward compatibility, feval still accepts a function name stringas a first argument and evaluates the function named in the string. However,function handles offer you the additional performance, reliability, and sourcefile control benefits listed in the section “Benefits of Using Function Handles”on page 21-3.21-2822MATLAB Classes andObjectsClasses and Objects: An Overview .
. . . . . . . . . 22-3Designing User Classes in MATLAB. . . . . . . . . 22-9Overloading Operators and Functions . . . . . . . 22-21Example - A Polynomial Class . . . . . . . . . . . 22-24Building on Other Classes . . . . . . . . . . . . . 22-35Example - Assets and Asset Subclasses . . . . .
. . 22-38Example - The Portfolio Container . . . . . . . . . 22-54Saving and Loading Objects . . . . . . . . . . . . 22-60Example - Defining saveobj and loadobj for Portfolio22-61Object Precedence . . . . . . . . . . . . . . . . 22-65How MATLAB Determines Which Method to Call . . 22-6722MATLAB Classes and ObjectsThis chapter describes how to define classes in MATLAB. Classes and objectsenable you to add new data types and new operations to MATLAB. The class ofa variable describes the structure of the variable and indicates the kinds ofoperations and functions that can apply to the variable.
An object is an instanceof a particular class. The phrase object-oriented programming describes anapproach to writing programs that emphasizes the use of classes and objects.The following topics and examples are presented in this chapter:• “Classes and Objects: An Overview”• “Designing User Classes in MATLAB”• “Overloading Operators and Functions”• “Example - A Polynomial Class”• “Building on Other Classes”• “Example - Assets and Asset Subclasses”• “Example - The Portfolio Container”• “Saving and Loading Objects”• “Example - Defining saveobj and loadobj for Portfolio”• “Object Precedence”• “How MATLAB Determines Which Method to Call”22-2Classes and Objects: An OverviewClasses and Objects: An OverviewYou can view classes as new data types having specific behaviors defined forthe class.
For example, a polynomial class might redefine the addition operator(+) so that it correctly performs the operation of addition on polynomials.Operations defined to work with objects of a particular class are known asmethods of that class.You can also view classes as new items that you can treat as single entities. Anexample is an arrow object that MATLAB can display on graphs (perhapscomposed of MATLAB line and patch objects) and that has properties like aHandle Graphics object. You can create an arrow simply by instantiating thearrow class.You can add classes to your MATLAB environment by specifying a MATLABstructure that provides data storage for the object and creating a classdirectory containing M-files that operate on the object. These M-files containthe methods for the class.
The class directory can also include functions thatdefine the way various MATLAB operators, including arithmetic operations,subscript referencing, and concatenation, apply to the objects. Redefining howa built-in operator works for your class is known as overloading the operator.Features of Object-Oriented ProgrammingWhen using well-designed classes, object-oriented programming cansignificantly increase code reuse and make your programs easier to maintainand extend. Programming with classes and objects differs from ordinarystructured programming in these important ways:• Function and operator overloading.
You can create methods thatoverride existing MATLAB functions. When you call a function with auser-defined object as an argument, MATLAB first checks to see if there is amethod defined for the object’s class. If there is, MATLAB calls it, ratherthan the normal MATLAB function.• Encapsulation of data and methods.
Object properties are not visiblefrom the command line; you can access them only with class methods. Thisprotects the object properties from operations that are not intended for theobject’s class.• Inheritance. You can create class hierarchies of parent and child classes inwhich the child class inherits data fields and methods from the parent. A22-322MATLAB Classes and Objectschild class can inherit from one parent (single inheritance) or many parents(multiple inheritance).
Inheritance can span one or more generations.Inheritance enables sharing common parent functions and enforcingcommon behavior amongst all child classes.• Aggregation. You can create classes using aggregation, in which an objectcontains other objects. This is appropriate when an object type is part ofanother object type. For example, a savings account object might be a part ofa financial portfolio object.MATLAB Data Class HierarchyAll MATLAB data types are designed to function as classes in object-orientedprogramming.
The diagram below shows the fourteen fundamental data types(or classes) defined in MATLAB. You can add new data types to MATLAB byextending the class hierarchy.ARRAYcharNUMERICcellstructureuser classint8, uint8,int16, uint16,int32, uint32singlefunction handlejava classdoublesparseThe diagram shows a user class that inherits from the structure class. Allclasses that you create are structure based since this is the point in the classhierarchy where you can insert your own classes.
(For more information aboutMATLAB data types, see the section on “Data Types.”)Creating ObjectsYou create an object by calling the class constructor and passing it theappropriate input arguments. In MATLAB, constructors have the same nameas the class name. For example, the statement,22-4Classes and Objects: An Overviewp = polynom([1 0 −2 −5]);creates an object named p belonging to the class polynom. Once you havecreated a polynom object, you can operate on the object using methods that aredefined for the polynom class. See “Example - A Polynomial Class” on page22-24 for a description of the polynom class.Invoking Methods on ObjectsClass methods are M-file functions that take an object as one of the inputarguments. The methods for a specific class must be placed in the classdirectory for that class (the @class_name directory).
This is the first place thatMATLAB looks to find a class method.The syntax for invoking a method on an object is similar to a function call.Generally, it looks like[out1,out2,...] = method_name(object,arg1,arg2, ...);For example, suppose a user-defined class called polynom has a char methoddefined for the class. This method converts a polynom object to a characterstring and returns the string. This statement calls the char method on thepolynom object p.s = char(p);Using the class function, you can confirm that the returned value s is acharacter string.class(s)ans =charss =x^3−2*x−5You can use the methods command to produce a list of all of the methods thatare defined for a class.22-522MATLAB Classes and ObjectsPrivate MethodsPrivate methods can be called only by other methods of their class.
















