Using MATLAB (779505), страница 97
Текст из файла (страница 97)
See “The Stock set Method” on page 22-48 for an example.The Asset subsref MethodThe subsref method provides access to the data contained in an asset objectusing one-based numeric indexing and structure field name indexing. Theouter switch statement determines if the index is a numeric or field namesyntax. The inner switch statements map the index to the appropriate value.MATLAB calls subsref whenever you make a subscripted reference to anobject (e.g., A(i), A{i}, or A.fieldname).function b = subsref(a,index)%SUBSREF Define field name indexing for asset objectsswitch index.typecase '()'switch index.subs{:}case 1b = a.descriptor;case 2b = a.date;case 3b = a.current_value;otherwiseerror('Index out of range')end22-42Example - Assets and Asset Subclassescase '.'switch index.subscase 'descriptor'b = a.descriptor;case 'date'b = a.date;case 'current_value'b = a.current_value;otherwiseerror('Invalid field name')endcase '{}'error('Cell array indexing not supported by asset objects')endSee the “The Stock subsref Method” on page 22-49 for an example of how thechild subsref method calls the parent subsref method.The Asset subsasgn MethodThe subsasgn method is the assignment equivalent of the subsref method.This version enables you to change the data contained in an object usingone-based numeric indexing and structure field name indexing.
The outerswitch statement determines if the index is a numeric or field name syntax.The inner switch statements map the index value to the appropriate value inthe stock structure.MATLAB calls subsasgn whenever you execute an assignment statement (e.g.,A(i) = val, A{i} = val, or A.fieldname = val).function a = subsasgn(a,index,val)% SUBSASGN Define index assignment for asset objectsswitch index.typecase '()'switch index.subs{:}case 1a.descriptor = val;case 2a.date = val;case 3a.current_value = val;22-4322MATLAB Classes and Objectsotherwiseerror('Index out of range')endcase '.'switch index.subscase 'descriptor'a.descriptor = val;case 'date'a.date = val;case 'current_value'a.current_value = val;otherwiseerror('Invalid field name')endendThe subsasgn method enables you to assign values to the asset object datastructure using two techniques.
For example, suppose you have a child stockobject s.s = stock('XYZ',100,25);Within stock class methods, you could change the descriptor field with eitherof the following statementss.asset(1) = 'ABC';ors.asset.descriptor = 'ABC';See the “The Stock subsasgn Method” on page 22-51 for an example of how thechild subsasgn method calls the parent subsasgn method.The Asset display MethodThe asset display method is designed to be called from child-class displaymethods. Its purpose is to display the data it stores for the child object. Themethod simply formats the data for display in a way that is consistent with theformatting of the child’s display method.function display(a)% DISPLAY(a) Display an asset object22-44Example - Assets and Asset Subclassesstg = sprintf(...'Descriptor: %s\nDate: %s\nType: %s\nCurrent Value:%9.2f',...a.descriptor,a.date,a.current_value);disp(stg)The stock class display method can now call this method to display the datastored in the parent class.
This approach isolates the stock display methodfrom changes to the asset class. See “The Stock display Method” on page 22-52for an example of how this method is called.The Asset fieldcount MethodThe asset fieldcount method returns the number of fields in the asset objectdata structure.
fieldcount enables asset child methods to determine thenumber of fields in the asset object during execution, rather than requiring thechild methods to have knowledge of the asset class. This allows you to makechanges to the number of fields in the asset class data structure without havingto change child-class methods.function num_fields = fieldcount(asset_obj)% Determines the number of fields in an asset object% Used by asset child class methodsnum_fields = length(fieldnames(asset_obj));The struct function converts an object to its equivalent data structure,enabling access to the structure’s contents.Designing the Stock ClassA stock object is designed to represent one particular asset in a person’sinvestment portfolio.
This object contains two properties of its own and inheritsthree properties from its parent asset object.Stock properties:• NumberShares – The number of shares for the particular stock object.• SharePrice – The value of each share.Asset properties:• Descriptor – The identifier of the particular asset (e.g., stock name, savingsaccount number, etc.).22-4522MATLAB Classes and Objects• Date – The date the object was created (calculated by the date command).• CurrentValue – The current value of the asset.Note that the property names are not actually the same as the field names ofthe structure array used internally by stock and asset objects.
The propertyname interface is controlled by the stock and asset set and get methods and isdesigned to resemble the interface of other MATLAB object properties.The asset field in the stock object structure contains the parent asset objectand is used to access the inherited fields in the parent structure.Stock Class MethodsThe stock class implements the following methods:• Constructor• get and set• subsref and subsasgn• displayThe Stock Constructor MethodThe stock constructor creates a stock object from three input arguments:• The stock name• The number of shares• The share priceThe constructor must create an asset object from within the stock constructorto be able to specify it as a parent to the stock object. The stock constructormust, therefore, call the asset constructor.
The class function, which is calledto create the stock object, defines the asset object as the parent.Keep in mind that the asset object is created in the temporary workspace of thestock constructor function and is stored as a field (.asset) in the stockstructure. The stock object inherits the asset fields, but the asset object is notreturned to the base workspace.function s = stock(varargin)% STOCK Stock class constructor.% s = stock(descriptor, num_shares, share_price)switch nargin22-46Example - Assets and Asset Subclassescase 0% if no input arguments, create a default objects.num_shares = 0;s.share_price = 0;a = asset('none',0);s = class(s, 'stock',a);case 1% if single argument of class stock, return itif (isa(varargin{1},'stock'))s = varargin{1};elseerror('Input argument is not a stock object')endcase 3% create object using specified valuess.num_shares = varargin{2};s.share_price = varargin{3};a = asset(varargin{1},’stock’,varargin{2} * varargin{3});s = class(s,'stock',a);otherwiseerror('Wrong number of input arguments')endConstructor Calling SyntaxThe stock constructor method can be called in one of three ways:• No Input Argument – If called with no arguments, the constructor returns adefault object with empty fields.• Input Argument is a Stock Object – If called with a single input argumentthat is a stock object, the constructor returns the input argument.
A singleargument that is not a stock object generates an error.• Three Input Arguments – If there are three input arguments, the constructoruses them to define the stock object.Otherwise, if none of the above three conditions are met, return an error.For example, this statement creates a stock object to record the ownership of100 shares of XYZ corporation stocks with a price per share of 25 dollars.XYZ_stock = stock('XYZ',100,25);22-4722MATLAB Classes and ObjectsThe Stock get MethodThe get method provides a way to access the data in the stock object using a“property name” style interface, similar to Handle Graphics. While in thisexample the property names are similar to the structure field name, they canbe quite different.
You could also choose to exclude certain fields from accessvia the get method or return the data from the same field for a variety ofproperty names, if such behavior suits your design.function val = get(s,prop_name)% GET Get stock property from the specified object% and return the value. Property names are: NumberShares% SharePrice, Descriptor, Date, CurrentValueswitch prop_namecase 'NumberShares'val = s.num_shares;case 'SharePrice'val = s.share_price;case 'Descriptor'val = get(s.asset,'Descriptor'); % call asset get methodcase 'Date'val = get(s.asset,'Date');case 'CurrentValue'val = get(s.asset,'CurrentValue');otherwiseerror([prop_name ,'Is not a valid stock property'])endNote that the asset object is accessed via the stock object’s asset field (s.asset).MATLAB automatically creates this field when the class function is calledwith the parent argument.The Stock set MethodThe set method provides a “property name” interface like the get method.
It isdesigned to update the number of shares, the share value, and the descriptor.The current value and the date are automatically updated.function s = set(s,varargin)% SET Set stock properties to the specified values% and return the updated objectproperty_argin = varargin;22-48Example - Assets and Asset Subclasseswhile length(property_argin) >= 2,prop = property_argin{1};val = property_argin{2};property_argin = property_argin(3:end);switch propcase 'NumberShares's.num_shares = val;case 'SharePrice's.share_price = val;case 'Descriptor's.asset = set(s.asset,'Descriptor',val);otherwiseerror('Invalid property')endends.asset = set(s.asset,'CurrentValue',...s.num_shares * s.share_price,'Date',date);Note that this function creates and returns a new stock object with the newvalues, which you then copy over the old value. For example, given the stockobject,s = stock('XYZ',100,25);the following set command updates the share price.s = set(s,'SharePrice',36);It is necessary to copy over the original stock object (i.e., assign the output tos) because MATLAB does not support passing arguments by reference.
Hencethe set method actually operates on a copy of the object.The Stock subsref MethodThe subsref method defines subscripted indexing for the stock class. In thisexample, subsref is implemented to enable numeric and structure field nameindexing of stock objects.function b = subsref(s,index)% SUBSREF Define field name indexing for stock objectsfc = fieldcount(s.asset);switch index.type22-4922MATLAB Classes and Objectscase '()'if (index.subs{:} <= fc)b = subsref(s.asset,index);elseswitch index.subs{:} − fccase 1b = s.num_shares;case 2b = s.share_price;otherwiseerror(['Index must be in the range 1 to ',num2str(fc + 2)])endendcase '.'switch index.subscase 'num_shares’b = s.num_shares;case 'share_price’b = s.share_price;otherwiseb = subsref(s.asset,index);endendThe outer switch statement determines if the index is a numeric or field namesyntax.The fieldcount asset method determines how many fields there are in theasset structure, and the if statement calls the asset subsref method forindices 1 to fieldcount.
















