| Programming and Data Types | ![]() |
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 that provides access to all structure data, such as the stock class implementation of subref.
See the subsref help entry for more information about indexing and objects.
| Changing the Portfolio Constructor | Object Precedence | ![]() |