Using MATLAB (779505), страница 98

Файл №779505 Using MATLAB (Using MATLAB) 98 страницаUsing MATLAB (779505) страница 982017-12-27СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 98)

See “The Asset fieldcount Method” on page 22-45 and“The Asset subsref Method” on page 22-42 for a description of these methods.Numeric indices greater than the number returned by fieldcount are handledby the inner switch statement, which maps the index value to the appropriatefield in the stock structure.Field-name indexing assumes field names other than num_shares andshare_price are asset fields, which eliminates the need for knowledge of assetfields by child methods. The asset subsref method performs field-name errorchecking.22-50Example - Assets and Asset SubclassesSee the subsref help entry for general information on implementing thismethod.The Stock subsasgn MethodThe subsasgn method enables you to change the data contained in a stockobject using numeric indexing and structure field name indexing.

MATLABcalls subsasgn whenever you execute an assignment statement(e.g., A(i) = val, A{i} = val, or A.fieldname = val).function s = subsasgn(s,index,val)% SUBSASGN Define index assignment for stock objectsfc = fieldcount(s.asset);switch index.typecase '()'if (index.subs{:} <= fc)s.asset = subsasgn(s.asset,index,val);elseswitch index.subs{:}−fccase 1s.num_shares = val;case 2s.share_price = val;otherwiseerror(['Index must be in the range 1 to ',num2str(fc + 2)])endendcase '.'switch index.subscase 'num_shares's.num_shares = val;case 'share_price's.share_price = val;otherwises.asset = subsasgn(s.asset,index,val);endendThe outer switch statement determines if the index is a numeric or field namesyntax.22-5122MATLAB Classes and ObjectsThe fieldcount asset method determines how many fields there are in theasset structure and the if statement calls the asset subsasgn method forindices 1 to fieldcount.

See “The Asset fieldcount Method” on page 22-45 and“The Asset subsasgn Method” on page 22-43 for a description of these methods.Numeric indices greater than the number returned by fieldcount are handledby the inner switch statement, which maps the index value to the appropriatefield in the stock structure.Field-name indexing assumes field names other than num_shares andshare_price are asset fields, which eliminates the need for knowledge of assetfields by child methods.

The asset subsasgn method performs field-name errorchecking.The subsasgn method enables you to assign values to stock object datastructure using two techniques. For example, suppose you have a stock objects = stock('XYZ',100,25)You could change the descriptor field with either of the following statementss(1) = 'ABC';ors.descriptor = 'ABC';See the subsasgn help entry for general information on assignment statementsin MATLAB.The Stock display MethodWhen you issue the statement (without terminating with a semicolon)XYZStock = stock('XYZ',100,25)MATLAB looks for a method in the @stock directory called display.

Thedisplay method for the stock class produces this output.Descriptor: XYZDate: 17-Nov-1998Type: stockCurrent Value: 2500.00Number of shares: 100Share price: 25.0022-52Example - Assets and Asset SubclassesHere is the stock display method.function display(s)% DISPLAY(s) Display a stock objectdisplay(s.asset)stg = sprintf('Number of shares: %g\nShare price: %3.2f\n',...s.num_shares,s.share_price);disp(stg)First, the parent asset object is passed to the asset display method to displayits fields (MATLAB calls the asset display method because the inputargument is an asset object). The stock object’s fields are displayed in a similarway using a formatted text string.Note that if you did not implement a stock class display method, MATLABwould call the asset display method.

This would work, but would display onlythe descriptor, date, type, and current value.22-5322MATLAB Classes and ObjectsExample - The Portfolio ContainerAggregation is the containment of one class by another class. The basicrelationship is: each contained class “is a part of” the container class.For example, consider a financial portfolio class as a container for a set ofassets (stocks, bonds, savings, etc.). Once the individual assets are grouped,they can be analyzed, and useful information can be returned. The containedobjects are not accessible directly, but only via the portfolio class methods.See “Example - Assets and Asset Subclasses” on page 22-38 for informationabout the assets collected by this portfolio class.Designing the Portfolio ClassThe portfolio class is designed to contain the various assets owned by a givenindividual and provide information about the status of his or her investmentportfolio.

This example implements a somewhat over-simplified portfolio classthat:• Contains an individual’s assets• Displays information about the portfolio contents• Displays a 3-D pie chart showing the relative mix of asset types in theportfolioRequired Portfolio MethodsThe portfolio class implements only three methods:• portfolio – The portfolio constructor.• display – Displays information about the portfolio contents.• pie3 – Overloaded version of pie3 function designed to take a single portfolioobject as an argument.Since a portfolio object contains other objects, the portfolio class methods canuse the methods of the contained objects. For example, the portfolio displaymethod calls the stock class display method, and so on.22-54Example - The Portfolio ContainerThe Portfolio Constructor MethodThe portfolio constructor method takes as input arguments a client’s name anda variable length list of asset subclass objects (stock, bond, and savings objectsin this example).

The portfolio object uses a structure array with the followingfields:• 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 thisvalue from the objects passed in as arguments.• account_number – The account number. This field is assigned a value onlywhen you save a portfolio object (see “Saving and Loading Objects” on page22-60).function p = portfolio(name,varargin)% PORTFOLIO Create a portfolio object containing the% client's name and a list of assetsswitch nargincase 0% if no input arguments, create a default objectp.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 itif isa(name,'portfolio')p = name;elsedisp([inputname(1) ' is not a portfolio object'])returnendotherwise% create object using specified argumentsp.name = name;p.total_value = 0;for k = 1:length(varargin)22-5522MATLAB Classes and Objectsp.ind_assets(k) = {varargin{k}};asset_value = get(p.ind_assets{k},'CurrentValue');p.total_value = p.total_value + asset_value;endp.account_number = '';p = class(p,'portfolio');endConstructor Calling SyntaxThe portfolio constructor method can be called in one of three different ways:• No input arguments – If called with no arguments, it returns an object withempty fields.• Input argument is an object – If the input argument is already a portfolioobject, MATLAB returns the input argument.

The isa function checks forthis case.• More than two input arguments – If there are more than two inputarguments, the constructor assumes the first is the client’s name and therest are asset subclass objects. A more thorough implementation wouldperform more careful input argument checking, for example, using the isafunction to determine if the arguments are the correct class of objects.The Portfolio display MethodThe portfolio display method lists the contents of each contained object bycalling the object’s display method. It then lists the client name and total assetvalue.function display(p)% DISPLAY Display a portfolio objectfor k = 1:length(p.ind_assets)display(p.ind_assets{k})endstg = sprintf('\nAssets for Client: %s\nTotal Value: %9.2f\n',...p.name,p.total_value);disp(stg)22-56Example - The Portfolio ContainerThe Portfolio pie3 MethodThe portfolio class overloads the MATLAB pie3 function to accept a portfolioobject and display a 3-D pie chart illustrating the relative asset mix of theclient’s portfolio.

MATLAB calls the @portfolio/pie3.m version of pie3whenever the input argument is a single portfolio object.function pie3(p)% PIE3 Create a 3-D pie chart of a portfoliostock_amt = 0; bond_amt = 0; savings_amt = 0;for k = 1:length(p.ind_assets)if isa(p.ind_assets{k},'stock')stock_amt = stock_amt + ...get(p.ind_assets{k},'CurrentValue');elseif isa(p.ind_assets{k},'bond')bond_amt = bond_amt + ...get(p.ind_assets{k},'CurrentValue');elseif isa(p.ind_assets{k},'savings')savings_amt = savings_amt + ...get(p.ind_assets{k},'CurrentValue');endendi = 1;if stock_amt ~= 0label(i) = {'Stocks'};pie_vector(i) = stock_amt;i = i +1;endif bond_amt ~= 0label(i) = {'Bonds'};pie_vector(i) = bond_amt;i = i +1;endif savings_amt ~= 0label(i) = {'Savings'};pie_vector(i) = savings_amt;endpie3(pie_vector,label)set(gcf,'Renderer','zbuffer')set(findobj(gca,'Type','Text'),'FontSize',14)cm = gray(64);22-5722MATLAB Classes and Objectscolormap(cm(48:end,:))stg(1) = {['Portfolio Composition for ',p.name]};stg(2) = {['Total Value of Assets: $',num2str(p.total_value)]};title(stg,'FontSize',12)There are three parts in the overloaded pie3 method.• The first uses the asset subclass get methods to access the CurrentValueproperty of each contained object.

The total value of each class is summed.• The second part creates the pie chart labels and builds a vector of graph data,depending on which objects are present.• The third part calls the MATLAB pie3 function, makes some font andcolormap adjustments, and adds a title.Creating a PortfolioSuppose you have implemented a collection of asset subclasses in a mannersimilar to the stock class.

Характеристики

Тип файла
PDF-файл
Размер
6,57 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Зачем заказывать выполнение своего задания, если оно уже было выполнено много много раз? Его можно просто купить или даже скачать бесплатно на СтудИзбе. Найдите нужный учебный материал у нас!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
7021
Авторов
на СтудИзбе
261
Средний доход
с одного платного файла
Обучение Подробнее