| Programming and Data Types | ![]() |
Converter Methods for the Polynom Class
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 Polynom to Double Converter
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;
The Polynom to Char Converter
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.
function s = char(p) % POLYNOM/CHAR% CHAR(p) is the string representation of p.cif all(p.c == 0)s = '0';elsed = length(p.c) - 1;s = [];for a = p.c;if a ~= 0;if ~isempty(s)if a > 0s = [s ' + '];elses = [s ' - '];a = -a;endendif a ~= 1 | d == 0s = [s num2str(a)];if d > 0s = [s '*'];endendif d >= 2s = [s 'x^' int2str(d)];elseif d == 1s = [s 'x'];endendd = d - 1;endend
Evaluating the Output
If you create the polynom object p
and then call the char method on p
The value returned by char is a string that you can pass to eval once you have defined a scalar value for x. For example,
See The Polynom subsref Method for a better method to evaluate the polynomial.
| The Polynom Constructor Method | The Polynom display Method | ![]() |