% sample.m % evaluates Pn(x1), where the user is prompted to first give the % degree of the polynomial, then the coefficients in increasing % powers of x, and finally the value of x1. % It also plots the polynomial using the function nested.m % We will use this type of program later, but for now, this program % merely demonstrates some of the bells and whistles associated with % programming in matlab. clear % this clears all variables from memory %%%%% getting user input %%%%%%% degree = input('what is the degree of the polynomial? '); n = degree + 1; % the number of coefficients for i = 1:n disp(['what is the order ' num2str(i-1) ' coefficient']); a(i) = input(''); end x1 = input('what is the value of x1? \n'); %%%%%%%%%%%%%%% evaluating Pn(x1) the long way = sol1 %%%%% sol1 = a(1); for i = 1:degree sol1 = sol1 + a(i+1) * x1^(i); end %%%%%%%%%%%%%% evaluating Pn(x1) with nested multiplication = sol2 %%%% % Make sure nested.m can be found by MATLAB sol2 = nested(a,x1); %%%%%%%% printing results to the screen %%%%%%%%%%%%%% disp(['Pn(' num2str(x1) ') using the original polynomial = '... num2str(sol1,16)]); disp(['Pn(' num2str(x1) ') using nested multiplication = ' ... num2str(sol2,16)]); %%%%%%%%%%%%%%%%% Displaying the graph %%%%%%%%%%%%%%%%% disp(['press any key to plot the polynomial']); pause % this pauses the program until a key is hit %%%% getting more user input %%%%%% xleft = input('from x = \n'); xright = input('to x = \n'); pts = input('plotting how many points? \n'); %%%%%% creating the x and y vectors %%%%%%%%% x=xleft:(xright-xleft)/pts:xright; for i = 1:pts+1 y(i) = nested(a,x(i)); % calls the function nested.m end %%%%%%%%%%%%%%%%% plotting and labelling %%%%%% plot(x,y,'ro') xlabel('x'); ylabel('Pn(x)'); title(['The graph of Pn(x) from x =' num2str(xleft), ' to ' num2str(xright)]);