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

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

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

If necessary, place the object in an objecthierarchy using the superiorto and inferiorto functions.Using the class Function in ConstructorsWithin a constructor method, you use the class function to associate an objectstructure with a particular class. This is done using an internal class tag thatis only accessible using the class and isa functions. For example, this call tothe class function identifies the object p to be of type polynom.p = class(p,'polynom');Examples of Constructor MethodsSee the following sections for examples of constructor methods:• “The Polynom Constructor Method” on page 22-24• “The Asset Constructor Method” on page 22-39• “The Stock Constructor Method” on page 22-46• “The Portfolio Constructor Method” on page 22-55Identifying Objects Outside the Class DirectoryThe class and isa functions used in constructor methods can also be usedoutside of the class directory.

The expressionisa(a,'class_name');checks whether a is an object of the specified class. For example, if p is apolynom object, each of the following expressions is true.isa(pi,'double');isa('hello','char');isa(p,'polynom');Outside of the class directory, the class function takes only one argument (itis only within the constructor that class can have more than one argument).22-1122MATLAB Classes and ObjectsThe expressionclass(a)returns a string containing the class name of a. For example,class(pi),class('hello'),class(p)return'double','char','polynom'Use the whos function to see what objects are in the MATLAB workspace.whosNamepSize1x1Bytes Class156 polynom objectThe display MethodMATLAB calls a method named display whenever an object is the result of astatement that is not terminated by a semicolon.

For example, creating thevariable a, which is a double, calls MATLAB’s display method for doubles.a = 5a =5You should define a display method so MATLAB can display values on thecommand line when referencing objects from your class. In many classes,display can simply print the variable name, and then use the char convertermethod to print the contents or value of the variable, since MATLAB displaysoutput as strings. You must define the char method to convert the object’s datato a character string.22-12Designing User Classes in MATLABExamples of display MethodsSee the following sections for examples of display methods:• “The Polynom display Method” on page 22-28• “The Asset display Method” on page 22-44• “The Stock display Method” on page 22-52• “The Portfolio display Method” on page 22-56Accessing Object DataYou need to write methods for your class that provide access to an object’s data.Accessor methods can use a variety of approaches, but all methods that changeobject data always accept an object as an input argument and return a newobject with the data changed.

This is necessary because MATLAB does notsupport passing arguments by reference (i.e., pointers). Functions can changeonly their private, temporary copy of an object. Therefore, to change an existingobject, you must create a new one, and then replace the old one.The following sections provide more detail about implementation techniquesfor the set, get, subsasgn, and subsref methods.The set and get MethodsThe set and get methods provide a convenient way to access object data incertain cases. For example, suppose you have created a class that defines anarrow object that MATLAB can display on graphs (perhaps composed ofexisting MATLAB line and patch objects).To produce a consistent interface, you could define set and get methods thatoperate on arrow objects the way the MATLAB set and get functions operateon built-in graphics objects.

The set and get verbs convey what operationsthey perform, but insulate the user from the internals of the object.Examples of set and get MethodsSee the following sections for examples of set and get methods:• “The Asset get Method” on page 22-41 and “The Asset set Method” on page22-41• “The Stock get Method” on page 22-48 and “The Stock set Method” on page22-4822-1322MATLAB Classes and ObjectsProperty Name MethodsAs an alternative to a general set method, you can write a method to handlethe assignment of an individual property.

The method should have the samename as the property name.For example, if you defined a class that creates objects representing employeedata, you might have a field in an employee object called salary. You couldthen define a method called salary.m that takes an employee object and avalue as input arguments and returns the object with the specified value set.Indexed Reference Using subsref and subsasgnUser classes implement new data types in MATLAB. It is useful to be able toaccess object data via an indexed reference, as is possible with MATLAB’sbuilt-in data types. For example, if A is an array of class double, A(i) returnsthe ith element of A.As the class designer, you can decide what an index reference to an objectmeans.

For example, suppose you define a class that creates polynomial objectsand these objects contain the coefficients of the polynomial.An indexed reference to a polynomial object,p(3)could return the value of the coefficient of x3, the value of the polynomial atx = 3, or something different depending on the intended design.You define the behavior of indexing for a particular class by creating two classmethods – subsref and subsasgn. MATLAB calls these methods whenever asubscripted reference or assignment is made on an object from the class.

If youdo not define these methods for a class, indexing is undefined for objects of thisclass.In general, the rules for indexing objects are the same as the rules for indexingstructure arrays. For details, see “Structures” on page 20-4.Handling Subscripted ReferenceThe use of a subscript or field designator with an object on the right-hand sideof an assignment statement is known as a subscripted reference. MATLAB callsa method named subsref in these situations.

Object subscripted references canbe of three forms – an array index, a cell array index, and a structure field22-14Designing User Classes in MATLABname:A(I)A{I}A.fieldEach of these results in a call by MATLAB to the subsref method in the classdirectory. MATLAB passes two arguments to subsref.B = subsref(A,S)The first argument is the object being referenced. The second argument, S, is astructure array with two fields:• S.type is a string containing '()', ’{}', or '.' specifying the subscript type.The parentheses represent a numeric array; the curly braces, a cell array;and the dot, a structure array.• S.subs is a cell array or string containing the actual subscripts.

A colon usedas a subscript is passed as the string ':'.For instance, the expressionA(1:2,:)causes MATLAB to call subsref(A,S), where S is a 1-by-1 structure withS.type = '()'S.subs = {1:2,':'}Similarly, the expressionA{1:2}usesS.type ='{}'S.subs = {1:2}The expressionA.fieldcalls subsref(A,S) whereS.type = '.'S.subs = 'field'22-1522MATLAB Classes and ObjectsThese simple calls are combined for more complicated subscriptingexpressions. In such cases, length(S) is the number of subscripting levels.

Forexample,A(1,2).name(3:4)calls subsref(A,S), where S is a 3-by-1 structure array with the values:S(1).type = '()'S(2).type = '.'S(1).subs = '{1,2}' S(2).subs = 'name'S(3).type = '()'S(3).subs = '{3:4}'How to Write subsrefThe subsref method must interpret the subscripting expressions passed in byMATLAB.

A typical approach is to use the switch statement to determine thetype of indexing used and to obtain the actual indices. The following three codefragments illustrate how to interpret the input arguments. In each case, thefunction must return the value B.For an array index:switch S.typecase '()'B = A(S.subs{:});endFor a cell array:switch S.typecase '{}'B = A(S.subs{:}); % A is a cell arrayendFor a structure array:switch S.typecase '.'switch S.subscase 'field1'B = A.field1;case 'field2'B = A.field2;endend22-16Designing User Classes in MATLABExamples of the subsref MethodSee the following sections for examples of the subsref method:• “The Polynom subsref Method” on page 22-28• “The Asset subsref Method” on page 22-42• “The Stock subsref Method” on page 22-49• “The Portfolio subsref Method” on page 22-64Handling Subscripted AssignmentThe use of a subscript or field designator with an object on the left-hand side ofan assignment statement is known as a subscripted assignment.

MATLABcalls a method named subsasgn in these situations. Object subscriptedassignment can be of three forms – an array index, a cell array index, and astructure field name.A(I) = BA{I} = BA.field = BEach of these results in a call to subsasgn of the formA = subsasgn(A,S,B)The first argument, A, is the object being referenced. The second argument, S,has the same fields as those used with subsref.

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

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

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

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