Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a user-defined function that adds or subtracts two polynomials of any orde

ID: 3927586 • Letter: W

Question

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.

Explanation / Answer


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

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote