Example — A Polynomial Class

Adding a Polynomial Object to the MATLAB® Language

This example implements a class to represent polynomials in the MATLAB® language. A value class is used because the behavior of a polynomial object within the MATLAB environment should follow the copy semantics of other MATLAB variables. This example also implements for this class, methods to provide enhanced display and indexing, as well as arithmetic operations and graphing.

See Comparing Handle and Value Classes for more information on value classes.

This class overloads a number of MATLAB functions, such as roots, polyval, diff, and plot so that these function can be used with the new polynomial object.

Displaying the Class Files

Open the DocPolynom class definition file in the MATLAB editor.

To use the class, create a directory named @DocPolynom and save DocPolynom.m to this directory. The parent directory of @DocPolynom must be on the MATLAB path.

Summary of the DocPolynom Class

The class definition specifies a property for data storage and defines a directory (@DocPolynom) that contains the class definition.

The following table summarizes the properties defined for the DocPolynom class.

DocPolynom Class Properties

Name

Class

Default

Description

coef

double

[]

Vector of polynomial coefficients [highest order ... lowest order]

The following table summarizes the methods for the DocPolynom class.

DocPolynom Class Methods

Name

Description

DocPolynom

Class constructor

double

Converts a DocPolynom object to a double (i.e., returns its coefficients in a vector)

char

Creates a formatted display of the DocPolynom object as powers of x and is used by the disp method

disp

Determines how MATLAB displays a DocPolynom objects on the command line

subsref

Enables you to specify a value for the independent variable as a subscript and access the coef property with dot notation

plus

Implements addition of DocPolynom objects

minus

Implements subtraction of DocPolynom objects

mtimes

Implements multiplication of DocPolynom objects

roots

Overloads the roots function to work with DocPolynom objects

polyval

Overloads the polyval function to work with DocPolynom objects

diff

Overloads the diff function to work with DocPolynom objects

plot

Overloads the plot function to work with DocPolynom objects

Using the DocPolynom Class

The following examples illustrate basic use of the DocPolynom class.

Create DocPolynom objects to represent the following polynomials. Note that the argument to the constructor function contains the polynomial coefficients and .

p1 = DocPolynom([1 0 -2 -5])
p1 =
   x^3 - 2*x - 5
p2 = DocPolynom([2 0 3 2 -7])
p2 =
   2*x^4 + 3*x^2 + 2*x - 7

The DocPolynom disp method displays the polynomial in MATLAB syntax.

Find the roots of the polynomial using the overloaded root method.

>> roots(p1)

ans =

   2.0946          
  -1.0473 + 1.1359i
  -1.0473 - 1.1359i

Add the two polynomials p1 and p2.

The MATLAB runtime calls the plus method defined for the DocPolynom class when you add two DocPolynom objects.

p1 + p2
ans =
   2*x^4 + x^3 + 3*x^2 - 12

The sections that follow describe the implementation of the methods illustrated here, as well as other methods and implementation details.

The DocPolynom Constructor Method

The following function is the DocPolynom class constructor, which is in the file @DocPolynom/DocPolynom.m:

function obj = DocPolynom(c)
% Construct a DocPolynom object using the coefficients supplied
   if isa(c,'DocPolynom')
      obj.coef = c.coef;
   else
      obj.coef = c(:).';
   end
end % DocPolynom

Constructor Calling Syntax

You can call the DocPolynom constructor method with two different arguments:

An example use of the DocPolynom constructor is the statement:

p = DocPolynom([1 0 -2 -5])
p = 
   x^3 - 2*x -5

This statement creates an instance of the DocPolynom class with the specified coefficients. Note how class methods display the equivalent polynomial using MATLAB language syntax. The DocPolynom class implements this display using the disp and char class methods.

Converting DocPolynom Objects to Other Types

The DocPolynom class defines two methods to convert DocPolynom objects to other classes:

The DocPolynom to Double Converter

The double converter method for the DocPolynom class simply returns the coefficient vector, which is a double by definition:

function c = double(obj)
% DocPolynom/Double Converter
   c = obj.coef;
end % double

For the DocPolynom object p:

p = DocPolynom([1 0 -2 -5])

the statement:

c = double(p)

returns:

c=
    1     0    -2    -5

which is of class double:

class(c)
ans = 
   double

The DocPolynom to Character Converter

The char method produces a character string that represents the polynomial displayed as powers of an independent variable, x. Therefore, after you have specified a value for x, the string returned is a syntactically correct MATLAB expression, which you can evaluate.

The disp method uses char to format the DocPolynom object for display.

This function is the char method, which is in the file @DocPolynom/DocPolynom.m.

function s = char(p) 
% Char(p) is the string representation of p.coef
if all(p.c == 0)
   s = '0';
else
   d = length(p.c) - 1;
   s = [];
   for a = p.c;
      if a ~= 0;
         if ~isempty(s)
            if a > 0
               s = [s  ' + ' ];
            else
               s = [s  ' - ' ];
               a = -a;
            end
         end
         if a ~= 1 | d == 0
            s = [s num2str(a)];
            if d > 0
               s = [s '*'];
            end
         end
         if d >= 2
            s = [s 'x^' int2str(d)];
         elseif d == 1
            s = [s 'x'];
         end
      end
      d = d - 1;
   end
end % char

Evaluating the Output

If you create the DocPolynom object p:

p = DocPolynom([1 0 -2 -5]);

and then call the char method on p:

char(p)

the result is:

ans =
    x^3 - 2*x - 5

The value returned by char is a string that you can pass to eval after you have defined a scalar value for x. For example:

x = 3;

eval(char(p))
ans = 
    16

The DocPolynom subsref Method describes a better way to evaluate the polynomial.

The DocPolynom disp Method

The MATLAB disp function enables you to display a character string or the contents of a variable. However, since the disp function has no knowledge of DocPolynom objects, you need to provide an overloaded version in the class definition to handle the case where MATLAB needs to display a DocPolynom object.

This method relies on the char method to produce a string representation of the polynomial, which is then displayed on the screen. The overloaded disp method produces output that is the same as MATLAB output for a built-in class:

function disp(obj)
   % disp function for objects
   disp(['     ' char(obj)])
end % disp

When MATLAB® Calls the disp Method

The statement:

p = DocPolynom([1 0 -2 -5])

creates a DocPolynom object. Since the statement is not terminated with a semicolon, the resulting output is displayed on the command line:

p =
    x^3 - 2*x - 5

The DocPolynom subsref Method

Normally, subscripted assignment is automatically defined by MATLAB. However, in this particular case, the design of the DocPolynom class specifies that a subscripted reference to a DocPolynom object causes the polynomial to be evaluated with the value of the independent variable equal to the subscript. That is, given the following polynomial:

evaluates f(x), where x is the value of the subscript.

For example, for a DocPolynom object p:

p = DocPolynom([1 0 -2 -5])
p =
    x^3 - 2*x - 5

the following subscripted expression evaluates the value of the polynomial at x = 3 and x = 4 and returns a vector of resulting values:

p([3 4])
ans =
    16   51

subsref Implementation Details

The DocPolynom subsref method provides two features:

For subscripted references using parentheses:

For references using dot notation, subsref simply returns the coefficients or an error, if the property name is incorrect.

See the subsref function reference page for more information on implementing subsref methods.

Defining Arithmetic Operators for DocPolynom

Several arithmetic operations are meaningful on polynomials and should be implemented for the DocPolynom class. See Implementing Operators for Your Class for information on overloading other operations that could be useful with this class, such as division, horizontal concatenation, etc.

This section shows how to implement the following methods:

Method and Syntax

Operator Implemented

plus(a,b)

Binary addition

minus(a,b)

Binary subtraction

mtimes(a,b)

Matrix multiplication

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 DocPolynom class to handle addition, subtraction, and multiplication on DocPolynom/DocPolynom and DocPolynom/double combinations of operands.

Defining the + Operator

If either p or q is a DocPolynom object, the expression

p + q

generates a call to a function @DocPolynom/plus, unless the other object is of a class of higher precedence. Object Precedence in Expressions Using Operators provides more information.

The following function redefines the plus (+) operator for the DocPolynom class:

function r = plus(obj1,obj2)
% Plus Implement obj1 + obj2 for DocPolynom 
   obj1 = DocPolynom(obj1);
   obj2 = DocPolynom(obj2);
   k = length(obj2.coef) - length(obj1.coef);
   r = DocPolynom([zeros(1,k) obj1.coef]+[zeros(1,-k) obj2.coef]);
end % plus

Here is how the function works:

Defining the - Operator

You can implement the minus operator (-) using the same approach as the plus (+) operator.

The MATLAB runtime calls the DocPolynom minus method to compute p - q, where p, q, or both are DocPolynom objects:

function r = minus(obj1,obj2)
% MINUS Implement obj1 - obj2 for DocPolynom
   obj1 = DocPolynom(obj1);
   obj2 = DocPolynom(obj2);
   k = length(obj2.coef) - length(obj1.coef);
   r = DocPolynom([zeros(1,k) obj1.coef]-[zeros(1,-k) obj2.coef]);
end % minus

Defining the * Operator

The MATLAB runtime calls the DocPolynom mtimes method to compute the product p*q. The mtimes method is used to overload matrix multiplication since the multiplication of two polynomials is simply the convolution (conv) of their coefficient vectors:

function r = mtimes(obj1,obj2)
% MTIMES Implement obj1 * obj2 for DocPolynoms
   obj1 = DocPolynom(obj1);
   obj2 = DocPolynom(obj2);
   r = DocPolynom(conv(obj1.coef,obj2.coef));
end % mtimes

Using the Arithmetic Operators

Given the DocPolynom object:

p = DocPolynom([1 0 -2 -5])

The following two arithmetic operations call the DocPolynom plus and mtimes methods:

q = p+1
r = p*q

to produce

q = 
    x^3 - 2*x - 4

r =
    x^6 - 4*x^4 - 9*x^3 + 4*x^2 + 18*x + 20

Overloading MATLAB® Functions for the DocPolynom Class

The MATLAB language already has several functions for working with polynomials that are represented by coefficient vectors. You can overload these functions to work with the new DocPolynom class.

In the case of DocPolynom objects, the overloaded methods can simply apply the original MATLAB function to the coefficients (i.e., the values returned by the coef property).

This section shows how to implement the following MATLAB functions.

MATLAB Function

Purpose

root(obj)

Calculates polynomial roots

polyval(obj,x)

Evaluates polynomial at specified points

diff(obj)

Finds difference and approximate derivative

plot(obj)

Creates a plot of the polynomial function

Defining the roots Function for the DocPolynom Class

The DocPolynom roots method finds the roots of DocPolynom objects by passing the coefficients to the overloaded roots function:

function r = roots(obj)
% roots(obj) returns a vector containing the roots of obj
   r = roots(obj.coef);
end % roots

If p is the following DocPolynom object:

p = DocPolynom([1 0 -2 -5]);

then the statement:

roots(p)

gives the following answer:

ans =
    2.0946
    -1.0473 + 1.1359i
    -1.0473 - 1.1359i

Defining the polyval Function for the DocPolynom Class

The MATLAB polyval function evaluates a polynomial at a given set of points. The DocPolynom polyval method uses nested multiplication, or Horner's method, to reduce the number of multiplication operations used to compute the various powers of x:

function y = polyval(obj,x)
% polyval(obj,x) evaluates obj at the points x
y = 0;
   for a = obj.coef
      y = y.*x + a;
   end
end % polyval

Defining the diff Function for the DocPolynom Class

The MATLAB diff function finds the derivative of the polynomial. The DocPolynom diff method differentiates a polynomial by reducing the degree by 1 and multiplying each coefficient by its original degree:

function q = diff(obj)
% diff(obj) is the derivative of the DocPolynom obj
   c = obj.coef;
   d = length(c) - 1;  % degree
   q = DocPolynom(obj.coef(1:d).*(d:-1:1));
end % diff

Defining the plot Function for the DocPolynom Class

The MATLAB plot function creates line graphs. The overloaded plot function selects the domain of the independent variable to be slightly larger than an interval containing all real roots. Then the polyval method is used to evaluate the polynomial at a few hundred points in the domain:

function plot(obj)
% plot(obj) plots the DocPolynom obj
   r = max(abs(roots(obj)));
   x = (-1.1:0.01:1.1)*r;
   y = polyval(obj,x);
   plot(x,y);
   title(['y = ' char(obj)])
   xlabel('X')
   ylabel('Y','Rotation',0)
   grid on
end % plot

Plotting the two DocPolynom objects x and p calls most of these methods:

x = DocPolynom([1 0]);
p = DocPolynom([1 0 -2 -5]);
plot(diff(p*p + 10*p + 20*x) - 20)

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS