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.

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

same fields and the object’s structure with all the values intact (that is, you<br />

now have a structure, not an object).<br />

The following implementation of loadobj first uses isa to determine whether<br />

the input argument is a portfolio object or a structure. If the input is an<br />

object, it is simply returned since no modifications are necessary. If the<br />

inputargumenthasbeenconvertedto a structure by <strong>MATLAB</strong>, then the<br />

new accountNumber field is added to the structure and is used to create an<br />

updated portfolio object.<br />

function b = loadobj(a)<br />

% loadobj for portfolio class<br />

if isa(a,'portfolio')<br />

b = a;<br />

else % a is an old version<br />

a.accountNumber = getAccountNumber(a);<br />

b = class(a,'portfolio');<br />

end<br />

Changing the Portfolio Constructor<br />

The portfolio structure array needs an additional field to accommodate the<br />

account number. To create this field, add the line<br />

p.accountNumber = '';<br />

to @portfolio/portfolio.m in both the zero argument and variable<br />

argument sections.<br />

The getAccountNumber Function<br />

In this example, getAccountNumber is a <strong>MATLAB</strong> function that returns<br />

an account number composed of the first three letters of the client name<br />

prepended to a series of digits. To illustrate implementation techniques,<br />

getAccountNumber is not a portfolio method so it cannot access the portfolio<br />

object data directly. Therefore, it is necessary to define a portfolio subsref<br />

method that enables access to the name field in a portfolio object’s structure.<br />

For this example, getAccountNumber simply generates a random number,<br />

which is formatted and concatenated with elements 1 to 3 from the portfolio<br />

name field.<br />

9-67

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

Saved successfully!

Ooh no, something went wrong!