Write a userdefined function that adds or subtracts two poly
Write a user-defined function that adds or subtracts two polynomials of any order. Name the function p = polyadd(p1, p2, operation). The first two input arguments p1 and p2 are the vectors of the coefficients of the two polynomials. If the two polynomials are not of the same order the function adds the necessary zero elements to the shorter vector. The third input argument operation is a string that can be either \'add\' or \'sub\', for adding or subtracting the polynomials, respectively and the output argument is the resulting polynomial. Use the function to add and subtract the following polynomials: f_1(x) = x^5 - 7x^4 + 11x^3 - 4x^2 - 5x - 2 and f_2(x) = 9x^2 - 10x + 6.
Solution
function p = polyadd(p1, p2, operation)
%This function performs the operation on the two polynomials and returns
%the resulting polynomial.
% first we need to pad the shorter polynomial
if length(p1)>length(p2)
while length(p1)>length(p2)
p2=[0 p2];
end
elseif length(p2)>length(p1)
while length(p2)>length(p1)
p1=[0 p1];
end
end
%now both vectors are the same length. if the operation is \'sub\', we
%subtract them, if its \'add\' we add them
if strcmp(operation, \'sub\')
p=p1-p2;
elseif strcmp(operation, \'add\')
p=p1+p2;
else
p=[];
disp(\'not a valid operation!\');
end
end
