Using MATLAB (779505), страница 99
Текст из файла (страница 99)
You can then use a portfolio object to present theindividual’s financial portfolio. For example, given the following assetsXYZStock = stock('XYZ',200,12);SaveAccount = savings('Acc # 1234',2000,3.2);Bonds = bond('U.S. Treasury',1600,12);Create a portfolio object.p = portfolio('Gilbert Bates',XYZStock,SaveAccount,Bonds)The portfolio display method summarizes the portfolio contents (because thisstatement is not terminated by a semicolon).Descriptor: XYZDate: 24-Nov-1998Current Value:2400.00Type: stockNumber of shares: 200Share price: 12.00Descriptor: Acc # 1234Date: 24-Nov-1998Current Value:2000.00Type: savingsInterest Rate: 3.2%22-58Example - The Portfolio ContainerDescriptor: U.S.
TreasuryDate: 24-Nov-1998Current Value:1600.00Type: bondInterest Rate: 12%Assets for Client: Gilbert BatesTotal Value:6000.00The portfolio pie3 method displays the relative mix of assets using a pie chart.pie3(p)22-5922MATLAB Classes and ObjectsSaving and Loading ObjectsYou can use the MATLAB save and load commands to save and retrieveuser-defined objects to and from .mat files, just like any other variables.When you load objects, MATLAB calls the object’s class constructor to registerthe object in the workspace. The constructor function for the object class youare loading must be able to be called with no input arguments and return adefault object. See “Guidelines for Writing a Constructor” on page 22-10 formore information.Modifying Objects During Save or LoadWhen you issue a save or load command on objects, MATLAB looks for classmethods called saveobj and loadobj in the class directory.
You can overloadthese methods to modify the object before the save or load operation. Forexample, you could define a saveobj method that saves related data along withthe object or you could write a loadobj method that updates objects to a newerversion when this type of object is loaded into the MATLAB workspace.22-60Example - Defining saveobj and loadobj for PortfolioExample - Defining saveobj and loadobj for PortfolioIn the section “Example - The Portfolio Container” on page 22-54, portfolioobjects are used to collect information about a client’s investment portfolio.Now suppose you decide to add an account number to each portfolio object thatis saved. You can define a portfolio saveobj method to carry out this taskautomatically during the save operation.Suppose further that you have already saved a number of portfolio objectswithout the account number.
You want to update these objects during the loadoperation so that they are still valid portfolio objects. You can do this bydefining a loadobj method for the portfolio class.Summary of Code ChangesTo implement the account number scenario, you need to add or change thefollowing functions:• portfolio – The portfolio constructor method needs to be modified to createa new field, account_number, which is initialized to the empty string whenan object is created.• saveobj – A new portfolio method designed to add an account number to aportfolio object during the save operation, only if the object does not alreadyhave one.• loadobj – A new portfolio method designed to update older versions ofportfolio objects that were saved before the account number structure fieldwas added.• subsref – A new portfolio method that enables subscripted reference toportfolio objects outside of a portfolio method.• getAccountNumber – a MATLAB function that returns an account numberthat consists of the first three letters of the client’s name.New Portfolio Class BehaviorWith the additions and changes made in this example, the portfolio class now:• Includes a field for an account number• Adds the account number when a portfolio object is saved for the first time22-6122MATLAB Classes and Objects• Automatically updates the older version of portfolio objects when you loadthem into the MATLAB workspaceThe saveobj MethodMATLAB looks for the portfolio saveobj method whenever the save commandis passed a portfolio object.
If @portfolio/saveobj exists, MATLAB passes theportfolio object to saveobj, which must then return the modified object as anoutput argument. The following implementation of saveobj determines if theobject has already been assigned an account number from a previous saveoperation. If not, saveobj calls getAccountNumber to obtain the number andassigns it to the account_number field.function b = saveobj(a)if isempty(a.account_number)a.account_number = getAccountNumber(a);endb = a;The loadobj MethodMATLAB looks for the portfolio loadobj method whenever the load commanddetects portfolio objects in the .mat file being loaded.
If loadobj exists,MATLAB passes the portfolio object to loadobj, which must then return themodified object as an output argument. The output argument is then loadedinto the workspace.If the input object does not match the current definition as specified by theconstructor function, then MATLAB converts it to a structure containing thesame fields and the object’s structure with all the values intact (that is, younow have a structure, not an object).The following implementation of loadobj first uses isa to determine whetherthe input argument is a portfolio object or a structure.
If the input is an object,it is simply returned since no modifications are necessary. If the inputargument has been converted to a structure by MATLAB, then the newaccount_number field is added to the structure and is used to create an updatedportfolio object.function b = loadobj(a)% loadobj for portfolio classif isa(a,'portfolio')22-62Example - Defining saveobj and loadobj for Portfoliob = a;else % a is an old versiona.account_number = getAccountNumber(a);b = class(a,'portfolio');endChanging the Portfolio ConstructorThe portfolio structure array needs an additional field to accommodate theaccount number.
To create this field, add the linep.account_number = '';to @portfolio/portfolio.m in both the zero argument and variable argumentsections.The getAccountNumber FunctionIn this example, getAccountNumber is a MATLAB function that returns anaccount number composed of the first three letters of the client nameprepended to a series of digits. To illustrate implementation techniques,getAccountNumber is not a portfolio method so it cannot access the portfolioobject data directly.
Therefore, it is necessary to define a portfolio subsrefmethod that enables access to the name field in a portfolio object’s structure.For this example, getAccountNumber simply generates a random number,which is formatted and concatenated with elements 1 to 3 from the portfolioname field.function n = getAccountNumber(p)% provides a account number for object pn = [upper(p.name(1:3)) strcat(num2str(round(rand(1,7)*10))')'];Note that the portfolio object is indexed by field name, and then by numericalsubscript to extract the first three letters.
The subsref method must be writtento support this form of subscripted reference.22-6322MATLAB Classes and ObjectsThe Portfolio subsref MethodWhen MATLAB encounters a subscripted reference, such as that made in thegetAccountNumber functionp.name(1:3)MATLAB calls the portfolio subsref method to interpret the reference. If youdo not define a subsref method, the above statement is undefined for portfolioobjects (recall that here p is an object, not just a structure).The portfolio subsref method must support field-name and numeric indexingfor the getAccountNumber function to access the portfolio name field.function b = subsref(p,index)% SUBSREF Define field name indexing for portfolio objectsswitch index(1).typecase '.'switch index(1).subscase 'name'if length(index)== 1b = p.name;elseswitch index(2).typecase '()'b = p.name(index(2).subs{:});endendendendNote that the portfolio implementation of subsref is designed to provide accessto specific elements of the name field; it is not a general implementation thatprovides access to all structure data, such as the stock class implementation ofsubsref.See the subsref help entry for more information about indexing and objects.22-64Object PrecedenceObject PrecedenceObject precedence is a means to resolve the question of which of possibly manyversions of an operator or function to call in a given situation.
Objectprecedence enables you to control the behavior of expressions containingdifferent classes of objects. For example, consider the expressionobjectA + objectBOrdinarily, MATLAB assumes that the objects have equal precedence and callsthe method associated with the leftmost object. However, there are twoexceptions:• User-defined classes have precedence over MATLAB built-in classes.• User-defined classes can specify their relative precedence with respect toother user-defined classes using the inferiorto and superiorto functions.For example, in the section “Example - A Polynomial Class” on page 22-24 thepolynom class defines a plus method that enables addition of polynom objects.Given the polynom object pp = polynom([1 0 −2 −5])p =x^3−2*x−5The expression,1 + pans =x^3−2*x−4calls the polynom plus method (which converts the double, 1, to a polynomobject, and then adds it to p).
The user-defined polynom class has precedenceover the MATLAB double class.22-6522MATLAB Classes and ObjectsSpecifying Precedence of User-Defined ClassesYou can specify the relative precedence of user-defined classes by calling theinferiorto or superiorto function in the class constructor.The inferiorto function places a class below other classes in the precedencehierarchy. The calling syntax for the inferiorto function isinferiorto('class1','class2',...)You can specify multiple classes in the argument list, placing the class belowmany other classes in the hierarchy.Similarly, the superiorto function places a class above other classes in theprecedence hierarchy. The calling syntax for the superiorto function issuperiorto('class1','class2',...)Location in the HierarchyIf objectA is above objectB in the precedence hierarchy, then the expressionobjectA + objectBcalls @classA/plus.m. Conversely, if objectB is above objectA in theprecedence hierarchy, then MATLAB calls @classB/plus.m.See “How MATLAB Determines Which Method to Call” on page 22-67 forrelated information.22-66How MATLAB Determines Which Method to CallHow MATLAB Determines Which Method to CallIn MATLAB, functions exist in directories in the computer’s file system.
















