Products & Services Solutions Academia Support User Community Company

Learn more about MATLAB   

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, access the coef property with dot notation, and call methods 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 

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.

Removing Irrelevant Coefficients

MATLAB software represents polynomials as row vectors containing coefficients ordered by descending powers. Zeros in the coefficient vector represent terms that drop out of the polynomial. Leading zeros, therefore, can be ignored when forming the polynomial.

Some DocPolynom class methods use the length of the coefficient vector to determine the degree of the polynomial. It is useful, therefore, to remove leading zeros from the coefficient vector so that its length represents the true value.

The DocPolynom class stores the coefficient vector in a property that uses a set method to remove leading zeros from the specified coefficients before setting the property value.

function obj = set.coef(obj,val)
   % coef set method
   ind = find(val(:).'~=0);
   if ~isempty(ind);
      obj.coef = val(ind(1):end);
   else
      obj.coef = val;
   end
end

See Property Set Methods for more information on controlling property values.

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 

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 char method uses a cell array to collect the string components that make up the displayed polynomial.

The disp method uses char to format the DocPolynom object for display. Class users are not likely to call the char or disp methods directly, but these methods enable the DocPolynom class to behave like other data classes in MATLAB.

Here is the char method.

function str = char(obj)
   % Created a formated display of the polynom
   % as powers of x
   if all(obj.coef == 0)
      s = '0';
   else
      d = length(obj.coef)-1;
      s = cell(1,d);
      ind = 1;
      for a = obj.coef;
         if a ~= 0;
            if ind ~= 1
               if a > 0
                  s(ind) = {' + '};
                  ind = ind + 1;
               else
                  s(ind) = {' - '};
                  a = -a;
                 ind = ind + 1;
               end
            end
            if a ~= 1 || d == 0
               if a == -1
                  s(ind) = {'-'};
                  ind = ind + 1;
               else
                  s(ind) = {num2str(a)};
                  ind = ind + 1;
                  if d > 0
                    s(ind) = {'*'};
                    ind = ind + 1;
                  end
               end
            end
            if d >= 2
               s(ind) = {['x^' int2str(d)]};
               ind = ind + 1;
            elseif d == 1
               s(ind) = {'x'};
               ind = ind + 1;
            end
         end
         d = d - 1;
      end
   end
   str = [s{:}];
end

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

To provide a more useful display of DocPolynom objects, this class overloads disp in the class definition.

This disp method relies on the char method to produce a string representation of the polynomial, which it then displays on the screen.

function disp(obj)
   % DISP Display object in MATLAB syntax
   c = char(obj); % char returns a cell array
   if iscell(c)
      disp(['     ' c{:}])
   else
      disp(c) % all coefficients are zero
   end
end 

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

See Displaying Objects in the Command Window for information about defining the display of objects.

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 an evaluation of the polynomial with the value of the independent variable equal to the subscript.

For example, given the following polynomial:

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

Creating 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

Special Behavior Requires Specializing subsref

The DocPolynom class redefines the default subscripted reference behavior by implementing a subsref method. Once you define a subsref method, MATLAB software calls this method for objects of this class whenever a subscripted reference occurs. You must, therefore, define all the behaviors you want your class to exhibit in the local method.

The DocPolynom subsref method implements the following behaviors:

subsref Implementation Details

See subsref for general information on implementing this method.

When you need to implement a subsref method to support calling methods with arguments using dot notation, both the type and subs structure fields contain multiple elements.

For example, consider a call to the class polyval method:

>> p = DocPolynom([1 0 -2 -5])
p = 
     x^3 - 2*x - 5
>> p.polyval([3 5 7])
ans =
    16   110   324

This method requires an input argument of values at which to evaluate the polynomial and returns the value of f(x) at these values. subsref performs the method call through the statements:

if length(s)>1
   b = a.(s(1).subs)(s(2).subs{:}); % method with arguments
else
   b = a.(s.subs); % method without input arguments
end

Where the contents of the structure s, which is passed to subsref contains:

s(1).type is '.'

s(2).type is '()'

s(1).subs is 'polyval'

s(2).subs is [3 5 7]

When you implement a subsref method for a class, you must implement all subscripted reference explicitly, as show in the following code listing.

function b = subsref(a,s)
   % Implement a special subscripted assignment
   switch s(1).type
   case '()'
      ind = s.subs{:};
      b = a.polyval(ind);
   case '.'
      switch s(1).subs
      case 'coef'
         b = a.coef;
      case 'plot'
         a.plot;
      otherwise
         if length(s)>1
            b = a.(s(1).subs)(s(2).subs{:});
         else
            b = a.(s.subs);
         end
      end
   otherwise
      error('Specify value for x as obj(x)')
   end
end

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 

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 

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 

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 

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 simply extracts the coefficients from the coef property and then calls the MATLAB version to compute the various powers of x:

function y = polyval(obj,x)
   % polyval(obj,x) evaluates obj at the points x
   y = polyval(obj.coef,x);
end

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 

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 

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)

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

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