Professional Documents
Culture Documents
Computational Methods Homework-8: - Amber Shafi
Computational Methods Homework-8: - Amber Shafi
-Amber Shafi
Question 1
a)
function p = getPolyVal(coeffs, x)
% my_poly_value(coeffs, x)
% Evaluate the polynomial defined by the coefficients
% at a particular x-value
% Inputs:
% coeffs Numeric array of coefficients
% x
Required x value
% Output:
% p
Result of evaluation.
x_length= length(x);
p=zeros(1,x_length);
for i= 1:x_length
%error check to ensure coefficient values have been assigned
if isempty(coeffs);
error ('please enter coefficient values')
elseif length(coeffs) > 1
p(i) = x(i) * getPolyVal(coeffs(1:end-1), x(i)) + coeffs(end);
else
p(i) = coeffs(1);
end
end
c) The code written for part b already contains a for loop over x that allows the user to enter
an array of values as shown below (from command window)
x= [-1 0 1 2]
x = -1
p = -2 -4 -4 -2
It can be seen that the values for p are same as calculated in part b for x= -1:2
Question 2
a)
x= [0 1 2 3 4]
y= [3 1 4 3 1]
p = polyfit (x, y, 1)
p = -0.2000 2.8000
b) polyval(p, x)
ans =
plot(x,y,'ob', x,ans,'og')
plot(x,y,'ob', x,ans,':g')
)
c) graph plotted without linspace.
code for smoothing the graph:
x=[0,1,2,3,4];
y=[3,1,4,3,1];
x_lin=linspace(0,4);
n=1;
p=polyfit(x,y,n);
f=getPolyVal(x_lin,p);
plot(x,y,'ob')
hold on
plot(x_lin,f,'r')
ylim([0 4.5])
hold on
n=2;
p2=polyfit(x,y,n);
f2=getPolyVal(x_lin,p2);
plot(x_lin,f2,'g')
ylim([0 5])
The following additions to the code can make the graph more presentable:
xlabel('x')
ylabel('f(x)')
legend('data points','n=1','n=2')
title('polynomial approximation')
e) The fitted degree polynomial fits the data points better than the other 3 polynomoials
f) they lie outside the data range therefore are called extrapolated estimates. Commands
shown in part c.
Question 3)