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

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

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

The third argument, B, is thenew value.Examples of the subsasgn MethodSee the following sections for examples of the subsasgn method:• “The Asset subsasgn Method” on page 22-43• “The Stock subsasgn Method” on page 22-51Object Indexing Within MethodsIf a subscripted reference is made within a class method, MATLAB uses itsbuilt-in subsref function to access data within the method’s own class.

If themethod accesses data from another class, MATLAB calls the overloadedsubsref function in that class. The same holds true for subscripted assignmentand subsasgn.22-1722MATLAB Classes and ObjectsThe following example shows a method, testref, that is defined in the class,employee. This method makes a reference to a field, address, in an object of itsown class. For this, MATLAB uses the built-in subsref function. It alsoreferences the same field in another class, this time using the overloadedsubsref of that class.% ---- EMPLOYEE class method: testref.m ---function testref(myclass,otherclass)myclass.addressotherclass.address% use built-in subsref% use overloaded subsrefThe example creates an employee object and a company object.empl = employee('Johnson','Chicago');comp = company('The MathWorks','Natick');The employee class method, testref, is called.

MATLAB uses an overloadedsubsref only to access data outside of the method’s own class.testref(empl,comp)ans =% built-in subsref was calledChicagoans =% @company\subsref was calledExecuting @company\subsref ...NatickDefining end Indexing for an ObjectWhen you use end in an object indexing expression, MATLAB calls the object’send class method. If you want to be able to use end in indexing expressionsinvolving objects of your class, you must define an end method for your class.The end method has the calling sequenceend(a,k,n)22-18Designing User Classes in MATLABwhere a is the user object, k is the index in the expression where the end syntaxis used, and n is the total number of indices in the expression.For example, consider the expressionA(end−1,:)MATLAB calls the end method defined for the object A using the argumentsend(A,1,2)That is, the end statement occurs in the first index element and there are twoindex elements.

The class method for end must then return the index value forthe last element of the first dimension. When you implement the end methodfor your class, you must ensure it returns a value appropriate for the object.Indexing an Object with Another ObjectWhen MATLAB encounters an object as an index, it calls the subsindexmethod defined for the object. For example, suppose you have an object a andyou want to use this object to index into another object b.c = b(a);A subsindex method might do something as simple as convert the object todouble format to be used as an index, as shown in this sample code.function d = subsindex(a)%SUBSINDEX% convert the object a to double format to be used% as an index in an indexing expressiond = double(a);subsindex values are 0-based, not 1-based.22-1922MATLAB Classes and ObjectsConverter MethodsA converter method is a class method that has the same name as another class,such as char or double.

Converter methods accept an object of one class asinput and return an object of another class. Converters enable you to:• Use methods defined for another class• Ensure that expressions involving objects of mixed class types executeproperlyA converter function call is of the formb = class_name(a)where a is an object of a class other than class_name. In this case, MATLABlooks for a method called class_name in the class directory for object a. If theinput object is already of type class_name, then MATLAB calls the constructor,which just returns the input argument.Examples of Converter MethodsSee the following sections for examples of converter methods:• “The Polynom to Double Converter” on page 22-25• “The Polynom to Char Converter” on page 22-2622-20Overloading Operators and FunctionsOverloading Operators and FunctionsIn many cases, you may want to change the behavior of MATLAB’s operatorsand functions for cases when the arguments are objects.

You can accomplishthis by overloading the relevant functions. Overloading enables a function tohandle different types and numbers of input arguments and perform whateveroperation is appropriate for the highest-precedence object. See “ObjectPrecedence” on page 22-65 for more information on object precedence.Overloading OperatorsEach built-in MATLAB operator has an associated function name (e.g., the +operator has an associated plus.m function). You can overload any operator bycreating an M-file with the appropriate name in the class directory.

Forexample, if either p or q is an object of type class_name, the expressionp + qgenerates a call to a function @class_name/plus.m, if it exists. If p and q areboth objects of different classes, then MATLAB applies the rules of precedenceto determine which method to use.Examples of Overloaded OperatorsSee the following sections for examples of overloaded operators:• “Overloading the + Operator” on page 22-29• “Overloading the − Operator” on page 22-30• “Overloading the ∗ Operator” on page 22-3022-2122MATLAB Classes and ObjectsThe following table lists the function names for most of MATLAB’s operators.22-22OperationM-FileDescriptiona + bplus(a,b)Binary additiona - bminus(a,b)Binary subtraction-auminus(a)Unary minus+auplus(a)Unary plusa.*btimes(a,b)Element-wise multiplicationa*bmtimes(a,b)Matrix multiplicationa./brdivide(a,b)Right element-wise divisiona.\bldivide(a,b)Left element-wise divisiona/bmrdivide(a,b)Matrix right divisiona\bmldivide(a,b)Matrix left divisiona.^bpower(a,b)Element-wise powera^bmpower(a,b)Matrix powera < blt(a,b)Less thana > bgt(a,b)Greater thana <= ble(a,b)Less than or equal toa >= bge(a,b)Greater than or equal toa ~= bne(a,b)Not equal toa == beq(a,b)Equalitya & band(a,b)Logical ANDa | bor(a,b)Logical OR~anot(a)Logical NOTOverloading Operators and FunctionsOperationM-FileDescriptiona:d:ba:bcolon(a,d,b)colon(a,b)Colon operatora'ctranspose(a)Complex conjugate transposea.'transpose(a)Matrix transposecommand windowoutputdisplay(a)Display method[a b]horzcat(a,b,...)Horizontal concatenation[a; b]vertcat(a,b,...)Vertical concatenationa(s1,s2,...sn)subsref(a,s)Subscripted referencea(s1,...,sn) = bsubsasgn(a,s,b)Subscripted assignmentb(a)subsindex(a)Subscript indexOverloading FunctionsYou can overload any function by creating a function of the same name in theclass directory.

When a function is invoked on an object, MATLAB always looksin the class directory before any other location on the search path. To overloadthe plot function for a class of objects, for example, simply place your versionof plot.m in the appropriate class directory.Examples of Overloaded FunctionsSee the following sections for examples of overloaded functions:• “Overloading Functions for the Polynom Class” on page 22-31• “The Portfolio pie3 Method” on page 22-5722-2322MATLAB Classes and ObjectsExample - A Polynomial ClassThis example implements a MATLAB data type for polynomials by defining anew class called polynom.

The class definition specifies a structure for datastorage and defines a directory (@polynom) of methods that operate on polynomobjects.Polynom Data StructureThe polynom class represents a polynomial with a row vector containing thecoefficients of powers of the variable, in decreasing order. Therefore, a polynomobject p is a structure with a single field, p.c, containing the coefficients.

Thisfield is accessible only within the methods in the @polynom directory.Polynom MethodsTo create a class that is well behaved within the MATLAB environment andprovides useful functionality for a polynomial data type, the polynom classimplements the following methods:• A constructor method polynom.m• A polynom to double converter• A polynom to char converter• A display method• A subsref method• Overloaded +, −, and * operators• Overloaded roots, polyval, plot, and diff functionsThe Polynom Constructor MethodHere is the polynom class constructor, @polynom/polynom.m.function p = polynom(a)%POLYNOM Polynomial class constructor.%p = POLYNOM(v) creates a polynomial object from the vector v,%containing the coefficients of descending powers of x.if nargin == 0p.c = [];p = class(p,'polynom');22-24Example - A Polynomial Classelseifp =elsep.cp =endisa(a,'polynom')a;= a(:).';class(p,'polynom');Constructor Calling SyntaxYou can call the polynom constructor method with one of three differentarguments:• No Input Argument – If you call the constructor function with no arguments,it returns a polynom object with empty fields.• Input Argument is an Object – If you call the constructor function with aninput argument that is already a polynom object, MATLAB returns the inputargument.

The isa function (pronounced “is a”) checks for this situation.• Input Argument is a coefficient vector – If the input argument is a variablethat is not a polynom object, reshape it to be a row vector and assign it to the.c field of the object’s structure. The class function creates the polynomobject, which is then returned by the constructor.An example use of the polynom constructor is the statementp = polynom([1 0 -2 -5])This creates a polynomial with the specified coefficients.Converter Methods for the Polynom ClassA converter method converts an object of one class to an object of another class.Two of the most important converter methods contained in MATLAB classesare double and char.

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

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

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

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