Programming |
Overloading Arithmetic Operators for polynom
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.
Overloading the + Operator
If either p
or q
is a polynom, the expression
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
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.
Overloading the - Operator
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]);
Overloading the * Operator
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));
Using the Overloaded Operators
MATLAB calls these two functions @polynom/plus.m
and @polynom/mtimes.m
when you issue the statements
The Polynom subsref Method | Overloading Functions for the Polynom Class |
© 1994-2005 The MathWorks, Inc.