Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Computational Methods Homework-8

-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

b) (taken from command window)


input:
p = getPolyVal([1 -1 -4], [-2:4])
output:
p = 2 -2 -4 -4 -2

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 = getPolyVal([1 -1 -4], x)

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 =

2.8000 2.6000 2.4000 2.2000 2.0000

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)

You might also like