File: ef230-2023-08/www/examples/polystring.m Download
%|Function to format a polynomial coefficient list as an equation text
% University of Tennessee : EF 230 Fall, 2009 : Will Schleter
function s=polystring(p,varargin)
% s = polystring(p,v,sf)
% p - list of polynomial coefficients
% v - variable name (defaults to 'x')
% sf - number of sig figs (defaults to 4)

% handle input
v='x'; %default variable
sf=4; %default # sig figs
if nargin>1
    v=varargin{1}; %use 2nd param as variable name
end
if nargin>2
    sf=varargin{2}; %use 3rd param as # sig figs
end

% trivial case - all coefficients are 0
if ~any(p)
    s='0';
    return;
end

s=[];
n=length(p);
for t=1:n
    if p(t)==0
        continue; % skip 0 terms
    end
    e=n-t; % current exponent

    % coefficient
    coef=num2str(abs(p(t)),sf);
    if strcmp(coef,'1') && e~=0
        coef='';
    end

    % sign
    if p(t)<0
        sign='-';
    elseif ~isempty(s)
        sign='+';
    else
        sign='';
    end

    % term
    switch e
        case 0
            term='';
        case 1
            term=v;
        otherwise
            term=[v '^' num2str(e)];
    end

    % symbol between coef and term
    if e>0 && ~isempty(coef)
        m='*';
    else
        m='';
    end

    % add pieces to existing equation
    s=[s sign coef m term];
end
return