| Programming and Data Types | ![]() |
The Portfolio Constructor Method
The portfolio constructor method takes as input arguments a client's name and a variable length list of asset subclass objects (stock, bond, and savings objects in this example). The portfolio object uses a structure array with the following fields:
name - The client's name.ind_assets - The array of asset subclass objects (stock, bond, savings).total_value - The total value of all assets. The constructor calculates this value from the objects passed in as arguments.account_number - The account number. This field is assigned a value only when you save a portfolio object (see Saving and Loading Objects).
function p = portfolio(name,varargin)
% PORTFOLIO Create a portfolio object containing the
% client's name and a list of assets
switch nargin
case 0
% if no input arguments, create a default object
p.name = 'none';
p.total_value = 0;
p.ind_assets = {};
p.account_number = '';
p = class(p,'portfolio');
case 1
% if single argument of class portfolio, return it
if isa(name,'portfolio')
p = name;
else
disp([inputname(1) ' is not a portfolio object'])
return
end
otherwise
% create object using specified arguments
p.name = name;
p.total_value = 0;
for i = 1:length(varargin)
p.ind_assets(i) = {varargin{i}};
asset_value = get(p.ind_assets{i},'CurrentValue');
p.total_value = p.total_value + asset_value;
end
p.account_number = '';
p = class(p,'portfolio');
end
Constructor Calling Syntax
The portfolio constructor method can be called in one of three different ways:
isa function checks for this case. isa function to determine if the arguments are the correct class of objects. | Example - The Portfolio Container | The Portfolio display Method | ![]() |