%FormatPoly.m %Math 128B Spring 2005 %Hmwk2 - Utility Function (Feb. 1, 2005) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function strPoly = FormatPoly(p) %given a row vector 'p' whose entries are the % coefficients of a polynomial (last entry is constant term) % returns formatted text (e.g. [3 2 1] -> '3x^2 + 2x + 1') dim = size(p); n = dim(2); strPoly = ' '; for i=1:n-1 c = p(i); pow = n - i; if (c==0) continue; elseif ((c > 0) & (i > 1)) strPoly = [strPoly ' + ']; elseif (c < 0) strPoly = [strPoly ' - ']; end c = abs(c); if (pow > 1) strPoly = [strPoly num2str(c) 'x^' num2str(pow) ' ']; elseif (pow==1) strPoly = [strPoly num2str(c) 'x' ' ']; end end c = p(n); if (c) if (c > 0) strPoly = [strPoly ' + ']; else strPoly = [strPoly ' - ']; end strPoly = [strPoly num2str(abs(c))]; end return