Documentation |
On this page… |
---|
Summary of the DocPolynom Class The DocPolynom Constructor Method Removing Irrelevant Coefficients |
This example implements a class to represent polynomials in the MATLAB^{®} language. The design requirements are:
Value class behavior—a polynomial object should behave like MATLAB numeric variables when copied and passed to functions.
Specialized display and indexing
Arithmetic operations
Double converter simplifying the use of polynomial object with existing MATLAB functions that accept numeric inputs.
Open the DocPolynom class definition file in the MATLAB editor.Open the DocPolynom class definition file in the MATLAB editor.
To use the class, create a folder named @DocPolynom and save DocPolynom.m to this folder. The parent folder of @DocPolynom must be on the MATLAB path.
The class definition specifies a property for data storage and defines a folder (@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 |
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
Find the roots of the polynomial by passing the coefficients to the roots function.
roots(p1.coef) ans = 2.0946 -1.0473 + 1.1359i -1.0473 - 1.1359i
Add the two polynomials p1 and p2.
MATLAB 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 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
It is possible to all the DocPolynom constructor with two different arguments:
Input argument is a DocPolynom object — If you call the constructor function with an input argument that is already a DocPolynom object, the constructor returns a new DocPolynom object with the same coefficients as the input argument. The isa function checks for this input.
Input argument is a coefficient vector — If the input argument is not a DocPolynom object, the constructor attempts to reshape the values into a vector and assign them to the coef property.
The coef property set method restricts property values to doubles. See Removing Irrelevant Coefficients for a description of the property set method.
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 the display of the object shows the equivalent polynomial using MATLAB language syntax. The DocPolynom class implements this display using the disp and char class methods.
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 if ~isa(val,'double') error('Coefficients must be of class double') end ind = find(val(:).'~=0); if ~isempty(ind); obj.coef = val(ind(1):end); else obj.coef = val; end end
The DocPolynom class defines two methods to convert DocPolynom objects to other classes:
double — Converts to the double numeric type so functions can perform mathematical operations on the coefficients.
char — Converts to string used to format output for display in the command window
The double converter method for the DocPolynom class simply returns the coefficient vector:
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 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'; str = s; return 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
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
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
The statement:
p = DocPolynom([1 0 -2 -5])
creates a DocPolynom object. Because the statement is not terminated with a semicolon, the resulting output is displayed on the command line:
p = x^3 - 2*x - 5
Normally, subscripted assignment is defined automatically 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:
Create 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 the resulting values:
p([3 4]) ans = 16 51
The DocPolynom class redefines the default subscripted reference behavior by implementing a subsref method.
If a class defines 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:
The ability to pass a value for the independent variable as a subscripted reference (i.e., p(3) evaluates the polynomial at x = 3)
Dot notation for accessing the coef property
Dot notation for access to class methods, which accept and return differing numbers of input and output arguments
See the subsref function for general information on implementing this method.
When you 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 polyval function:
p = DocPolynom([1 0 -2 -5]) p = x^3 - 2*x - 5 polyval(p.coef,[3 5 7]) ans = 16 110 324
The polyval function 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:
case '()' ind = s.subs{:}; b = polyval(a.coef,ind);
The subsref method implements all subscripted reference explicitly, as show in the following code listing.
function b = subsref(a,s) switch s(1).type case '()' ind = s.subs{:}; b = polyval(a.coef,ind); case '.' switch s(1).subs case 'coef' b = a.coef; case 'disp' disp(a) 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 % subsref
Several arithmetic operations are meaningful on polynomials and are implemented for the DocPolynom class.
This section shows how to implement the following methods:
Method and Syntax | Operator Implemented |
---|---|
Addition | |
Subtraction | |
Matrix multiplication |
When overloading arithmetic operators, keep in mind what data types you want to operate on. 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.
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.
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:
Ensure that both input arguments are DocPolynom objects so that expressions such as
p + 1
that involve both a DocPolynom and a double, work correctly.
Access the two coefficient vectors and, if necessary, pad one of them with zeros to make both the same length. The actual addition is simply the vector sum of the two coefficient vectors.
Call the DocPolynom constructor to create a properly typed result.
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
MATLAB calls the DocPolynom mtimes method to compute the product p*q. The mtimes method implements 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
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