23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

9 Classes and Objects<br />

function n = getAccountNumber(p)<br />

% provides a account number for object p<br />

n = [upper(p.name(1:3)) strcat(num2str(round(rand(1,7)*10))')'];<br />

Note that the portfolio object is indexed by field name, and then by numerical<br />

subscript to extract the first three letters. The subsref method must be<br />

written to support this form of subscripted reference.<br />

The Portfolio subsref Method<br />

When <strong>MATLAB</strong> encounters a subscripted reference, such as that made in the<br />

getAccountNumber function<br />

p.name(1:3)<br />

<strong>MATLAB</strong> calls the portfolio subsref method to interpret the reference. If<br />

you do not define a subsref method, the above statement is undefined for<br />

portfolio objects (recall that here p is an object, not just a structure).<br />

The portfolio subsref method must support field-name and numeric indexing<br />

for the getAccountNumber function to access the portfolio name field.<br />

function b = subsref(p,index)<br />

% SUBSREF Define field name indexing for portfolio objects<br />

switch index(1).type<br />

case '.'<br />

switch index(1).subs<br />

case 'name'<br />

if length(index)== 1<br />

b = p.name;<br />

else<br />

switch index(2).type<br />

case '()'<br />

b = p.name(index(2).subs{:});<br />

end<br />

end<br />

end<br />

end<br />

Note that the portfolio implementation of subsref is designed to provide<br />

access to specific elements of the name field; it is not a general implementation<br />

9-68

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

Saved successfully!

Ooh no, something went wrong!