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: 3633494 • 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 fuction adds the necessary zero elements to the shorter vector.) The thrid input arguement 'operation' is a string that can be either 'add' or 'sub', for adding or subtracting the polynomials, respectively, and the output arguement is the resulting polynomial.

Use the function to add and subtract the following polynomials:
f1(x)=x^5-7x^4+11x^3-4x^2-5x-2
f2(x)=9x^2-10x+6
In your comments be sure to include a description of the function, it's inputs, and it's outputs, as well as the results from adding and subtracting the two equations listed.If the user doesn't enter 'add' or 'sub' as an option, you may simply print an error message and exit the function. There is no need to ask them to re-enter any inputs.

Explanation / Answer

function p=polyadd(p1,p2,operation)
% function for polynomial additiona dn subtractions

% Inputs :

%     P1 --> Polynomial 1 coefficients in a vector form

%     p2 --> Polynomial 2 coefficients in a vector form

%     operation --> Tell us the operation to perform

% returns a vector of the result of the specified operation

len_p1 = length(p1);
len_p2 = length(p2);

if len_p1 > len_p2
tmp =[zeros(1:len_p1-len_p2), p2];
p2 = tmp;
elseif len_p1 < len_p2
tmp =[zeros(1:len_p2-len_p1), p1];
p1 = tmp;
end;

if upper(operation) == 'ADD'
   p = p1 .+ p2;
elseif upper(operation) == 'SUB'
   p = p1 .- p2;
else
   disp('Error : Invalid Inputs');
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