File: ef230-2023-08/www/examples/polystring2.m Download
function txt=polystring2(p,iv)
% format polynomial equation as a string
% p : coefficients
% iv : name of independent variable, defaults to x
% txt : string containing the equation
%
% this version omits terms with coefficient=0

if nargin<2
    iv='x'; % default variable name
end

lenp = length(p);
txt = ''; % string to build

minval = 1e-6; % anything less than this is 0

% loop thru coefficients
for i=1:lenp
    e = lenp-i; % exponent
    if abs(p(i))<minval
        continue; % skip if close or equal to 0
    end
    % get the sign
    if p(i)<0
        sign='-';
    else
        sign='+';
    end

    % add the sign if negative or in between values
    if sign=='-' || length(txt)>0
        txt = [txt sign];
    end

    val=abs(p(i)); % the coefficient

    % add the coefficient if not 1
    if val~=1
        txt = [txt num2str(val,3)];
    end

    % display the variable if not on constant term
    if e>0
        txt = [txt iv];
    end

    % display the exponent if not 0 or 1
    if e>1
         txt = [txt '^' num2str(e)];
    end
end

end % polystring2