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

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

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

Conversion to double produces MATLAB’s traditionalmatrix, although this may not be appropriate for some classes. Conversion tochar is useful for producing printed output.The Polynom to Double ConverterThe double converter method for the polynom class is a very simple M-file,@polynom/double.m, which merely retrieves the coefficient vector.22-2522MATLAB Classes and Objectsfunction c = double(p)% POLYNOM/DOUBLE Convert polynom object to coefficient vector.%c = DOUBLE(p) converts a polynomial object to the vector c%containing the coefficients of descending powers of x.c = p.c;On the object p,p = polynom([1 0 -2 -5])the statementdouble(p)returnsans =10-2-5The Polynom to Char ConverterThe converter to char is a key method because it produces a character stringinvolving the powers of an independent variable, x. Therefore, once you havespecified x, the string returned is a syntactically correct MATLAB expression,which you can then evaluate.Here is @polynom/char.m.function s = char(p)% POLYNOM/CHAR% CHAR(p) is the string representation of p.cif all(p.c == 0)s = '0';elsed = length(p.c) - 1;s = [];for a = p.c;if a ~= 0;if ~isempty(s)if a > 0s = [s ' + '];elses = [s ' - '];a = -a;22-26Example - A Polynomial Classendendif a ~= 1 | d == 0s = [s num2str(a)];if d > 0s = [s '*'];endendif d >= 2s = [s 'x^' int2str(d)];elseif d == 1s = [s 'x'];endendd = d - 1;endendEvaluating the OutputIf you create the polynom object pp = polynom([1 0 -2 -5]);and then call the char method on pchar(p)MATLAB produces the resultans =x^3 - 2*x - 5The value returned by char is a string that you can pass to eval once you havedefined a scalar value for x.

For example,x = 3;eval(char(p))ans =16See “The Polynom subsref Method” on page 22-28 for a better method toevaluate the polynomial.22-2722MATLAB Classes and ObjectsThe Polynom display MethodHere is @polynom/display.m. This method relies on the char method toproduce a string representation of the polynomial, which is then displayed onthe screen. This method produces output that is the same as standardMATLAB output. That is, the variable name is displayed followed by an equalsign, then a blank line, then a new line with the value.function display(p)% POLYNOM/DISPLAY Command window display of a polynomdisp(' ');disp([inputname(1),' = '])disp(' ');disp(['' char(p)])disp(' ');The statementp = polynom([1 0 -2 -5])creates a polynom object.

Since the statement is not terminated with asemicolon, the resulting output isp =x^3 - 2*x - 5The Polynom subsref MethodSuppose the design of the polynom class specifies that a subscripted referenceto a polynom object causes the polynomial to be evaluated with the value of theindependent variable equal to the subscript. That is, for a polynom object p,p = polynom([1 0 -2 -5]);the following subscripted expression returns the value of the polynomial atx = 3 and x = 4.p([3 4])ans =1622-2851Example - A Polynomial Classsubsref Implementation DetailsThis implementation takes advantage of the char method already defined inthe polynom class to produce an expression that can then be evaluated.function b = subsref(a,s)% SUBSREFswitch s.typecase '()'ind = s.subs{:};for k = 1:length(ind)b(k) = eval(strrep(char(a),'x',num2str(ind(k))));endotherwiseerror('Specify value for x as p(x)')endOnce the polynomial expression has been generated by the char method, thestrrep function is used to swap the passed in value for the character x.

Theeval function then evaluates the expression and returns the value in theoutput argument.Overloading Arithmetic Operators for polynomSeveral arithmetic operations are meaningful on polynomials and should beimplemented for the polynom class. When overloading arithmetic operators,keep in mind what data types you want to operate on. In this section, the plus,minus, and mtimes methods are defined for the polynom class to handleaddition, subtraction, and multiplication on polynom/polynom and polynom/double combinations of operands.Overloading the + OperatorIf either p or q is a polynom, the expressionp + qgenerates a call to a function @polynom/plus.m, if it exists (unless p or q is anobject of a higher precedence, as described in “Object Precedence” on page22-65).22-2922MATLAB Classes and ObjectsThe following M-file redefines the + operator for the polynom class.function r = plus(p,q)% POLYNOM/PLUS Implement p + q for polynoms.p = polynom(p);q = polynom(q);k = length(q.c) - length(p.c);r = polynom([zeros(1,k) p.c] + [zeros(1,-k) q.c]);The function first makes sure that both input arguments are polynomials.

Thisensures that expressions such asp + 1that involve both a polynom and a double, work correctly. The function thenaccesses the two coefficient vectors and, if necessary, pads one of them withzeros to make them the same length. The actual addition is simply the vectorsum of the two coefficient vectors. Finally, the function calls the polynomconstructor a third time to create the properly typed result.Overloading the − OperatorYou can implement the overloaded minus operator (-) using the same approachas the plus (+) operator. MATLAB calls @polynom/minus.m to compute p−q.function r = minus(p,q)% POLYNOM/MINUS Implement p - q for polynoms.p = polynom(p);q = polynom(q);k = length(q.c) - length(p.c);r = polynom([zeros(1,k) p.c] - [zeros(1,-k) q.c]);Overloading the ∗ OperatorMATLAB calls the method @polynom/mtimes.m to compute the product p*q.The letter m at the beginning of the function name comes from the fact that itis overloading MATLAB’s matrix multiplication.

Multiplication of twopolynomials is simply the convolution of their coefficient vectors.function r = mtimes(p,q)% POLYNOM/MTIMESImplement p * q for polynoms.p = polynom(p);q = polynom(q);r = polynom(conv(p.c,q.c));22-30Example - A Polynomial ClassUsing the Overloaded OperatorsGiven the polynom objectp = polynom([1 0 -2 -5])MATLAB calls these two functions @polynom/plus.m and @polynom/mtimes.mwhen you issue the statementsq = p+1r = p*qto produceq =x^3 - 2*x - 4r =x^6 - 4*x^4 - 9*x^3 + 4*x^2 + 18*x + 20Overloading Functions for the Polynom ClassMATLAB already has several functions for working with polynomialsrepresented by coefficient vectors. They should be overloaded to also work withthe new polynom object.

In many cases, the overloading methods can simplyapply the original function to the coefficient field.Overloading roots for the Polynom ClassThe method @polynom/roots.m finds the roots of polynom objects.function r = roots(p)% POLYNOM/ROOTS. ROOTS(p) is a vector containing the roots of p.r = roots(p.c);The statementroots(p)results inans =2.0946-1.0473 + 1.1359i-1.0473 - 1.1359i22-3122MATLAB Classes and ObjectsOverloading polyval for the Polynom ClassThe function polyval evaluates a polynomial at a given set of points.@polynom/polyval.m uses nested multiplication, or Horner’s method to reducethe number of multiplication operations used to compute the various powers ofx.function y = polyval(p,x)% POLYNOM/POLYVAL POLYVAL(p,x) evaluates p at the points x.y = 0;for a = p.cy = y.*x + a;endOverloading plot for the Polynom ClassThe overloaded plot function uses both root and polyval.

The function selectsthe domain of the independent variable to be slightly larger than an intervalcontaining all real roots. Then polyval is used to evaluate the polynomial at afew hundred points in the domain.function plot(p)% POLYNOM/PLOT PLOT(p) plots the polynom p.r = max(abs(roots(p)));x = (-1.1:0.01:1.1)*r;y = polyval(p,x);plot(x,y);title(char(p))grid onOverloading diff for the Polynom ClassThe method @polynom/diff.m differentiates a polynomial by reducing thedegree by 1 and multiplying each coefficient by its original degree.function q = diff(p)% POLYNOM/DIFF DIFF(p) is the derivative of the polynom p.c = p.c;d = length(c) - 1; % degreeq = polynom(p.c(1:d).*(d:-1:1));22-32Example - A Polynomial ClassListing Class MethodsThe function callmethods('class_name')or its command formmethods class_nameshows all the methods available for a particular class.

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

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

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

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