Programming Previous page   Next Page

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.

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.

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.

Using the Overloaded Operators

Given the polynom object

MATLAB calls these two functions @polynom/plus.m and @polynom/mtimes.m when you issue the statements

to produce


Previous page  The Polynom subsref Method Overloading Functions for the Polynom Class Next page

© 1994-2005 The MathWorks, Inc.