% vres = polyadd(v1,v2)
% Performs polynomial addition, and returns the result. All polynomials
% are expressed as vectors with the following format:
% The first element describes the lowest order of the terms in the
% polynomial, while the rest of the elements give the coefficients
% of the terms starting with the lowest order term.
%
% e.g. v = [3 2 4 1] corresponds to 2*x^3+4*x^4+x^5
%
% George Ginis, May 2001
function vres = polyadd(v1,v2);
% polynomial length (must be equal for both v1 and v2)
len = length(v1);
if (length(v1) ~= length(v2))
disp('Vectors in polyadd have unequal length!');
exit;
end
d1 = v1(1); % lowest order of polynomial 1
d2 = v2(1); % lowest order of polynomial 2
p1 = v1(2:len); % coefficients of polynomial 1
p2 = v2(2:len); % coefficients of polynomial 2
if (d1 == d2) % polynomials have the same degree
vres(1) = d1;
vres(2:len) = p1+p2;
elseif (d1 > d2) % first polynomial has higher degree
diff = d1-d2;
p1new=zeros(1,len-1);
p1new(1+diff:len-1) = p1(1:len-diff-1); % perform "shift" of p2
vres(1) = d2;
vres(2:len) = p1new+p2;
else % (d1 < d2) second polynomial has higher degree
diff = d2-d1;
p2new=zeros(1,len-1);
p2new(1+diff:len-1) = p2(1:len-diff-1); % perform "shift" of p1
vres(1) = d1;
vres(2:len) = p1+p2new;
end