Programming |
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.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
end
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 |
© 1994-2005 The MathWorks, Inc.