| Programming | ![]() |
The Stock subsref Method
The subsref method defines subscripted indexing for the stock class. In this example, subsref is implemented to enable numeric and structure field name indexing of stock objects.
function b = subsref(s,index) % SUBSREF Define field name indexing for stock objects fc = fieldcount(s.asset); switch index.type case '()' if (index.subs{:} <= fc) b = subsref(s.asset,index); else switch index.subs{:} - fc case 1 b = s.numShares; case 2 b = s.sharePrice; otherwise error(['Index must be in the range 1 to ',num2str(fc + 2)]) end end case '.' switch index.subs case 'numShares' b = s.numShares; case 'sharePrice' b = s.sharePrice; otherwise b = subsref(s.asset,index); end end
The outer switch statement determines if the index is a numeric or field name syntax.
The fieldcount asset method determines how many fields there are in the asset structure, and the if statement calls the asset subsref method for indices 1 to fieldcount. See The Asset fieldcount Method and The Asset subsref Method for a description of these methods.
Numeric indices greater than the number returned by fieldcount are handled by the inner switch statement, which maps the index value to the appropriate field in the stock structure.
Field-name indexing assumes field names other than numShares and sharePrice are asset fields, which eliminates the need for knowledge of asset fields by child methods. The asset subsref method performs field-name error checking.
See the subsref help entry for general information on implementing this method.
| The Stock set Method | The Stock subsasgn Method | ![]() |
© 1994-2005 The MathWorks, Inc.