2. Write a Matlab program that will allow the user to enter the coefficients of
ID: 666398 • Letter: 2
Question
2. Write a Matlab program that will allow the user to enter the coefficients of a polynomial and make some calculations. Selections and data entry will be done by presenting the user with a menu (using menu function) and provide her/him with the following choices:
Enter the degree and coefficients of the polynomial
Evaluate the polynomial at a user defined point
Display the roots of the polynomial
Exit
Other Requirements:
Selecting choice 2 and 3 before entering the degree and coefficients will result in an error message. The program will terminate only when Exit has been selected
Calculations will be done by functions.
o Function polynomial() will ask for the degree and the coefficients of the polynomial and would return the coefficients.
o Function polyEval() will accept a parameter, the evaluation point, and returns the value of the polynomial at that point.
o Function polyRoots() will accept the coefficients and returns the roots.
Results are displayed with 2 decimal place accuracy.
Help with coefficient entry:
%store the coefficients of the polynomial that have been entered
% in a vector. Return coefficients as a vector called p
%this vector should be global so that other functions can use it
global p;
p=[]; %creates an empty polynomial
degree=input('Please enter the degree of the polynomial: ');
j=degree; %this is used for correct message display below
degree=degree+1;
for i=1:1:degree
fprintf('Please enter the coefficient of power %d ',j);
p(i)=input(' ');
j=j-1;
end
%note the highest degree coefficient is stored in position 1
%and the next one is position 2 and so on.
Explanation / Answer
%Matlab program to evaluate and display the roots of a polynomial
clear
choice=-1:
s=0:
global p[];
while choice < 4 do
choice = menu('Select your choice','Enter the degree and coefficients of the polynomial',
'Evaluate the polynomial at a user defined point','Display the roots of the polynomial','Exit');
switch(choice)
case 1
s=1;
polynomial();
case 2
pt=input('Please enter the evaluation point: ');
if s==1
pvalue=polyEval(pt);
disp('polynomial value at evaluation point:' )
disp(pvalue)
else
break
case 3
if s==1
roots=polyRoots(p);
disp('Roots of the polynomial:' )
disp(roots)
else
break
case 4
exit
otherwise
fprintf('Invalid input ' );
break
end
end_while
end
function p[] = polynomial()
degree=input('Please enter the degree of the polynomial: ');
j=degree; %this is used for correct message display below
degree=degree+1;
for i=1:degree
p(i)=input(Please enter the coefficient of power %d ',j);
j=j-1;
end
end
function pval = polyEval(epoint)
pval=polyval(p,epoint);
end
function root = polyRoots(p)
root=roots(p);
end
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.