MATLAB Programming

MATLAB Programming MATLAB Programming

cda.psych.uiuc.edu
from cda.psych.uiuc.edu More from this publisher
23.06.2015 Views

9 Classes and Objects function n = getAccountNumber(p) % provides a account number for object p n = [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 numerical subscript to extract the first three letters. The subsref method must be written to support this form of subscripted reference. The Portfolio subsref Method When MATLAB encounters a subscripted reference, such as that made in the getAccountNumber function p.name(1:3) MATLAB calls the portfolio subsref method to interpret the reference. If you do not define a subsref method, the above statement is undefined for portfolio objects (recall that here p is an object, not just a structure). The portfolio subsref method must support field-name and numeric indexing for the getAccountNumber function to access the portfolio name field. function b = subsref(p,index) % SUBSREF Define field name indexing for portfolio objects switch index(1).type case '.' switch index(1).subs case 'name' if length(index)== 1 b = p.name; else switch index(2).type case '()' b = p.name(index(2).subs{:}); end end end end Note that the portfolio implementation of subsref is designed to provide access to specific elements of the name field; it is not a general implementation 9-68

Example — Defining saveobj and loadobj for Portfolio that provides access to all structure data, such as the stock class implementation of subsref. See the subsref help entry for more information about indexing and objects. 9-69

Example — Defining saveobj and loadobj for Portfolio<br />

that provides access to all structure data, such as the stock class<br />

implementation of subsref.<br />

See the subsref help entry for more information about indexing and objects.<br />

9-69

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!