Write a user-define function that add or subtracts two polynomials of any order. Use the function to add and subtract the following polynomil: f(x)=x^5-7​x^4+11x^3-​4x^2-5

6 次查看(过去 30 天)
  2 个评论
Dyuman Joshi
Dyuman Joshi 2023-5-14
MATLAB Answers does not entertain providing solutions to homework problems.
Show us what you have done, and ask a specific question where you are having trouble and we may be able to provide some guidance.
If you aren't sure where to start because you're not familiar with how to write MATLAB code, I suggest you start with the free MATLAB Onramp tutorial to quickly learn the essentials of MATLAB.
Torsten
Torsten 2023-5-14
In my opinion, a stupid exercise.
A symbolic solution makes no difference whether you add or subtract polynomials or two general functions.
If the result should be the usual representation of polynomials as vector of its coefficients, it should be mentionned in the exercise.

请先登录,再进行评论。

回答(1 个)

Anish Gupta
Anish Gupta 2023-5-21
Hello Ali,
As per my understanding, you want to perform arithmetic operations on two polynomials using a user-defined MATLAB function. You can do this by creating a vector of coefficients for each polynomial and doing the arithmetic operations on those vectors.
For you reference, the below example demonstrates a simple approach for performing arithmetic operations on polynomials:
p1=[1 -7 11 -4 -5 -2];
p2=[9 -10 6];
a3(p1,p2,"add");
a = "(1)x^5 + (-7)x^4 + (11)x^3 + (5)x^2 + (-15)x^1 + 4"
The function takes the coefficients of the polynomial in a vector as input and prints the final polynomial.
function p=a3(p1,p2,op)
lp1=length(p1);
lp2=length(p2);
degree=max(lp1,lp2)-1;
if(lp1>lp2)
p2=[zeros(1,lp1-lp2) p2];
elseif(lp2>lp1)
p1=[zeros(1,lp2-lp1) p1];
end
if(op=="add")
p=p1+p2;
elseif(op=="subs")
p=p1-p2;
end
a=string(p(degree+1));
for i=1:degree
a="("+string(p(degree+1-i))+")"+"x^"+string(i)+" + "+a;
end
a
end
If you want to pass the polynomials as string to the function, you'll have to parse the strings to get the coefficients in vector form. Subsequently, you can get use of the “a3” function.

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by