| MATLAB Programming | ![]() |
www.kxcad.net Home > CAE Software Index > MATLAB Index >
| On this page… |
|---|
The Polynom Constructor Method Converter Methods for the Polynom Class Overloading Arithmetic Operators for polynom |
This example implements a MATLAB data type for polynomials by defining a new class called polynom. The polynom class represents a polynomial with a row vector containing the coefficients of powers of the variable, in decreasing order. Therefore, a polynom object p is a structure with a single field, p.c, containing the coefficients. This field is accessible only within the methods in the @polynom directory.
To create a class that is well behaved within the MATLAB environment and provides useful functionality for a polynomial data type, the polynom class implements the following methods:
A constructor method polynom.m
A polynom to double converter
A polynom to char converter
A display method
A subsref method
Overloaded +, -, and * operators
Overloaded roots, polyval, plot, and diff functions
Here is the polynom class constructor, @polynom/polynom.m.
function p = polynom(a) %POLYNOM Polynomial class constructor. % p = POLYNOM(v) creates a polynomial object from vector v, % containing the coefficients of descending powers of x. if nargin == 0 p.c = []; p = class(p,'polynom'); elseif isa(a,'polynom') p = a; else p.c = a(:).'; p = class(p,'polynom'); end
You can call the polynom constructor method with one of three different arguments:
No input argument — If you call the constructor function with no arguments, it returns a polynom object with empty fields.
Input argument is an object — If you call the constructor function with an input argument that is already a polynom object, MATLAB returns the input argument. The isa function (pronounced "is a") checks for this situation.
Input argument is a coefficient vector — If the input argument is a variable that is not a polynom object, reshape it to be a row vector and assign it to the .c field of the object's structure. The class function creates the polynom object, which is then returned by the constructor.
An example use of the polynom constructor is the statement
p = polynom([1 0 -2 -5])
This creates a polynomial with the specified coefficients.
A converter method converts an object of one class to an object of another class. Two of the most important converter methods contained in MATLAB classes are double and char. Conversion to double produces the MATLAB traditional matrix, although this may not be appropriate for some classes. Conversion to char is useful for producing printed output.
The double converter method for the polynom class is a very simple M-file, @polynom/double.m, which merely retrieves the coefficient vector.
function 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 statement
double(p)
returns
ans = 1 0 -2 -5
Having implemented the double method, you can use it to call MATLAB functions on polynom objects that require double values as inputs. For example,
size(double(p)) ans = 1 4
The converter to char is a key method because it produces a character string involving the powers of an independent variable, x. Therefore, once you have specified 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.c
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
endIf you create the polynom object p
p = polynom([1 0 -2 -5]);
and then call the char method on p
char(p)
MATLAB produces the result
ans =
x^3 - 2*x - 5The value returned by char is a string that you can pass to eval once you have defined a scalar value for x. For example,
x = 3;
eval(char(p))
ans =
16See The Polynom subsref Method for a better method to evaluate the polynomial.
Here is @polynom/display.m. This method relies on the char method to produce a string representation of the polynomial, which is then displayed on the screen. This method produces output that is the same as standard MATLAB output. That is, the variable name is displayed followed by an equal sign, then a blank line, then a new line with the value.
function display(p)
% POLYNOM/DISPLAY Command window display of a polynom
disp(' ');
disp([inputname(1),' = '])
disp(' ');
disp([' ' char(p)])
disp(' ');The statement
p = polynom([1 0 -2 -5])
creates a polynom object. Since the statement is not terminated with a semicolon, the resulting output is
p =
x^3 - 2*x - 5Suppose the design of the polynom class specifies that a subscripted reference to a polynom object causes the polynomial to be evaluated with the value of the independent 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 at x = 3 and x = 4.
p([3 4])
ans =
16 51This implementation takes advantage of the char method already defined in the polynom class to produce an expression that can then be evaluated.
function b = subsref(a,s)
% SUBSREF
switch s.type
case '()'
ind = s.subs{:};
for k = 1:length(ind)
b(k) = eval(strrep(char(a), 'x', ...
['(' num2str(ind(k)) ')']));
end
otherwise
error('Specify value for x as p(x)')
endOnce the polynomial expression has been generated by the char method, the strrep function is used to swap the passed in value for the character x. The eval function then evaluates the expression and returns the value in the output argument.
Note that if you perform an indexed reference from within other class methods, MATLAB calls the built-in subsref or subsassign. See Behavior Within Class Methods for more information.
Several arithmetic operations are meaningful on polynomials and should be implemented 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 handle addition, subtraction, and multiplication on polynom/polynom and polynom/double combinations of operands.
If either p or q is a polynom, the expression
p + q
generates a call to a function @polynom/plus.m, if it exists (unless p or q is an object of a higher precedence, as described in Object Precedence).
The 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. This ensures that expressions such as
p + 1
that involve both a polynom and a double, work correctly. The function then accesses the two coefficient vectors and, if necessary, pads one of them with zeros to make them the same length. The actual addition is simply the vector sum of the two coefficient vectors. Finally, the function calls the polynom constructor a third time to create the properly typed result.
You can implement the overloaded minus operator (-) using the same approach as 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]);
MATLAB 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 it is overloading the MATLAB matrix multiplication. Multiplication of two polynomials is simply the convolution of their coefficient vectors.
function r = mtimes(p,q) % POLYNOM/MTIMES Implement p * q for polynoms. p = polynom(p); q = polynom(q); r = polynom(conv(p.c,q.c));
Given the polynom object
p = polynom([1 0 -2 -5])
MATLAB calls these two functions @polynom/plus.m and @polynom/mtimes.m when you issue the statements
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 + 20MATLAB already has several functions for working with polynomials represented by coefficient vectors. They should be overloaded to also work with the new polynom object. In many cases, the overloading methods can simply apply the original function to the coefficient field.
The 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 statement
roots(p)
results in
ans =
2.0946
-1.0473 + 1.1359i
-1.0473 - 1.1359iThe function polyval evaluates a polynomial at a given set of points. @polynom/polyval.m 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(p,x) % POLYNOM/POLYVAL POLYVAL(p,x) evaluates p at the points x. y = 0; for a = p.c y = y.*x + a; end
The overloaded plot function uses both root and polyval. The function selects the domain of the independent variable to be slightly larger than an interval containing the roots of the polynomial. Then polyval is used to evaluate the polynomial at a few 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 on
The method @polynom/diff.m differentiates a polynomial by reducing the degree 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; % degree q = polynom(p.c(1:d).*(d:-1:1));
The function call
methods('classname')or its command form
methods classname
shows all the methods available for a particular class. For the polynom example, the output is
methods polynom Methods for class polynom:
char | |||||
diff |
Plotting the two polynom objects x and p calls most of these methods.
x = polynom([1 0]); p = polynom([1 0 -2 -5]); plot(diff(p*p + 10*p + 20*x) - 20)

| Overloading Operators and Functions | Building on Other Classes | ![]() |
© 1984-2007 The MathWorks, Inc. Terms of Use Patents Trademarks Acknowledgments