Using MATLAB (779505), страница 92
Текст из файла (страница 92)
You defineprivate methods by placing the associated M-files in a private subdirectory ofthe @class_name directory. In the example,@class_name/private/update_obj.mthe method update_obj has scope only within the class_name class. Thismeans that update_obj can be called by any method that is defined in the@class_name directory, but it cannot be called from the MATLAB commandline or by methods outside of the class directory, including parent methods.Private methods and private functions differ in that private methods (in factall methods) have an object as one of their input arguments and privatefunctions do not. You can use private functions as helper functions, such asdescribed in the next section.Helper FunctionsIn designing a class, you may discover the need for functions that performsupport tasks for the class, but do not directly operate on an object. Thesefunctions are called helper functions.
A helper function can be a subfunction ina class method file or a private function. When determining which version of aparticular function to call, MATLAB looks for these functions in the orderlisted above. For more information about the order in which MATLAB callsfunctions and methods, see “How MATLAB Determines Which Method to Call”on page 22-67.Debugging Class MethodsYou can use the MATLAB debugging commands with object methods in thesame way that you use them with other M-files.
The only difference is that youneed to include the class directory name before the method name in thecommand call, as shown in this example using dbstop.dbstop @polynom/charWhile debugging a class method, you have access to all methods defined for theclass, including inherited methods, private methods, and private functions.22-6Classes and Objects: An OverviewChanging Class DefinitionIf you change the class definition, such as the number or names of fields in aclass, you must issue aclear classescommand to propagate the changes to your MATLAB session.
This commandalso clears all objects from the workspace. See the clear command help entryfor more information.Setting Up Class DirectoriesThe M-files defining the methods for a class are collected together in a directoryreferred to as the class directory. The directory name is formed with the classname preceded by the character @.
For example, one of the examples used inthis chapter is a class involving polynomials in a single variable. The name ofthe class, and the name of the class constructor, is polynom. The M-filesdefining a polynomial class would be located in directory with the name@polynom.The class directories are subdirectories of directories on the MATLAB searchpath, but are not themselves on the path. For instance, the new @polynomdirectory could be a subdirectory of MATLAB’s working directory or your ownpersonal directory that has been added to the search path.Adding the Class Directory to the MATLAB PathAfter creating the class directory, you need to update the MATLAB path so thatMATLAB can locate the class source files. The class directory should not bedirectly on the MATLAB path.
Instead, you should add the parent directory tothe MATLAB path. For example, if the @polynom class directory is located atc:\my_classes\@polynomyou add the class directory to the MATLAB path with the addpath commandaddpath c:\my_classes;If you create a class directory with the same name as another class, MATLABtreats the two class directories as a single directory when locating classmethods.
For more information, see “How MATLAB Determines WhichMethod to Call” on page 22-67.22-722MATLAB Classes and ObjectsData StructureOne of the first steps in the design of a new class is the choice of the datastructure to be used by the class. Objects are stored in MATLAB structures.The fields of the structure, and the details of operations on the fields, arevisible only within the methods for the class.
The design of the appropriatedata structure can affect the performance of the code.Tips for C++ and Java ProgrammersIf you are accustomed to programming in other object-oriented languages, suchas C++ or Java, you will find that the MATLAB programming language differsfrom these languages in some important ways:• In MATLAB, method dispatching is not syntax based, as it is in C++ andJava.
When the argument list contains objects of equal precedence,MATLAB uses the left-most object to select the method to call.• In MATLAB, there is no equivalent to a destructor method. To remove anobject from the workspace, use the clear function.• Construction of MATLAB data types occurs at runtime rather than compiletime.
You register an object as belonging to a class by calling the classfunction.• When using inheritance in MATLAB, the inheritance relationship isestablished in the child class by creating the parent object, and then callingthe class function. For more information on writing constructors forinheritance relationships, see “Building on Other Classes” on page 22-35.• When using inheritance in MATLAB, the child object contains a parentobject in a property with the name of the parent class.• In MATLAB, there is no passing of variables by reference.
When writingmethods that update an object, you must pass back the updated object anduse an assignment statement. For instance, this call to the set methodupdates the name field of the object A and returns the updated object.A = set(A,'name','John Smith');• In MATLAB, there is no equivalent to an abstract class.• In MATLAB, there is no equivalent to the C++ scoping operator.• In MATLAB, there is no virtual inheritance or virtual base classes.• In MATLAB, there is no equivalent to C++ templates.22-8Designing User Classes in MATLABDesigning User Classes in MATLABThis section discusses how to approach the design of a class and describes thebasic set of methods that should be included in a class.The MATLAB Canonical ClassWhen you design a MATLAB class, you should include a standard set ofmethods that enable the class to behave in a consistent and logical way withinthe MATLAB environment.
Depending on the nature of the class you aredefining, you may not need to include all of these methods and you may includea number of other methods to realize the class’s design goals.This table lists the basic methods included in MATLAB classes.Class MethodDescriptionclass constructorCreates an object of the classdisplayCalled whenever MATLAB displays the contentsof an object (e.g., when an expression is enteredwithout terminating with a semicolon)set and getAccesses class propertiessubsref and subsasgnEnables indexed reference and assignment foruser objectsendSupports end syntax in indexing expressionsusing an object; e.g., A(1:end)subsindexSupports using an object in indexing expressionsconverters like doubleand charMethods that convert an object to a MATLABdata typeThe following sections discuss the implementation of each type of method, aswell as providing references to examples used in this chapter.22-922MATLAB Classes and ObjectsThe Class Constructor MethodThe @ directory for a particular class must contain an M-file known as theconstructor for that class.
The name of the constructor is the same as the nameof the directory (excluding the @ prefix and .m extension) that defines the nameof the class. The constructor creates the object by initializing the data structureand instantiating an object of the class.Guidelines for Writing a ConstructorClass constructors must perform certain functions so that objects behavecorrectly in the MATLAB environment. In general, a class constructor musthandle three possible combinations of input arguments:• No input arguments• An object of the same class as an input argument• The input arguments used to create an object of the class (typically data ofsome kind)No Input Arguments.
If there are no input arguments, the constructor shouldcreate a default object. Since there are no inputs, you have no data from whichto create the object, so you simply initialize the object’s data structures withempty or default values, call the class function to instantiate the object, andreturn the object as the output argument. Support for this syntax is requiredfor two reasons:• When loading objects into the workspace, the load function calls the classconstructor with no arguments.• When creating arrays of objects, MATLAB calls the class constructor to addobjects to the array.Object Input Argument.
If the first input argument in the argument list is anobject of the same class, the constructor should simply return the object. Usethe isa function to determine if an argument is a member of a class. See“Overloading the + Operator” on page 22-29 for an example of a method thatuses this constructor syntax.Data Input Arguments. If the input arguments exist and are not objects of thesame class, then the constructor creates the object using the input data.
Ofcourse, as in any function, you should perform proper argument checking inyour constructor function. A typical approach is to use a varargin input22-10Designing User Classes in MATLABargument and a switch statement to control program flow. This provides aneasy way to accommodate the three cases: no inputs, object input, or the datainputs used to create an object.It is in this part of the constructor that you assign values to the object’s datastructure, call the class function to instantiate the object, and return theobject as the output argument.















