Using MATLAB (779505), страница 95
Текст из файла (страница 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.
















