1) - Lagrange Polynomial Interpolation: N 3
1) - Lagrange Polynomial Interpolation: N 3
n =5
n= 7
n =9
n=5
n =7
n =9
Codes
1). Lagrange
clc
% Lagrange
n = input('enter the number of intermediate points, n :');
%
%
%
%
%
%
%
plot(x,e,'.')
hold on
x
F
e
% increment the p to increment x
p =p+1;
if x<=1
x = -1+(2/999)*(p-1);
else
break
end
end
i = 1:1:n
F(i,1) = Y(i);
x = -1;
t =1;
while x<=1
t =t+1;
if x<=1
x = -1+(2/999)*(t-1);
else
break
end
end
Q = X;
H = Y;
b = zeros(n,1);
M = zeros(n,1);
% defining a matrix A containing coefficients of Array
% of double derivative value
A = zeros(n,n);
A(1,1)= 1;
A(n,n) = 1;
for i = 2:1:n-1
% A is a tridiagonal system
A(i,i-1)= (X(i)-X(i-1))/6;
A(i,i)= (X(i+1)- X(i-1))/3;
A(i,i+1)= (X(i+1)-X(i));
end
A;
% generating the RHS vector b
for i = 2:1:n-1
i;
b(i,1)= ((Y(i+1,1)- Y(i,1))/(X(i+1,1)-X(i,1))) - ((Y(i,1)- Y(i-1,1))/(X(i,1)X(i-1,1)));
end
b;
% Applying gaussian eleimination
to solve for M
a = size(A,1);
for i=1:1:a-1
[col index] = max(abs(A(i:a,i)));
col;
index = index+i-1;
if A(i,i)<col
C = A(i,:);
A(i,:)= A([index],:);
A([index],:)=C;
tem = b(i,:);
b(i,:) = b([index],:);
b([index],:) = tem;
end
for j = i+1:1:a
m(j) = A(j,i)/A(i,i);
A(j,:) = A(j,:) - A(i,:)*m(j);
b(j,:)= b(j,:)- b(i,:)*m(j);
end
end
K = zeros(a,1);
K(a)= b(a)/A(a,a);
for i= a-1:-1:1
s= b(i);
for j=i+1:1:a
s=s-A(i,j)*K(j);
end
K(i)=s/A(i,i);
end
M = zeros(n,1);
M = K
% Using the obtained M to get the values at various intervals
% in the defined function
k =1;
h=-1;
for x = -1:0.002:1
if(h<=x)
h=h+(2/(n-1));
k=k+1;
if(h==1)
break
end
end
s = ((((Q(k)-x)^3)*M(k-1) +((x - Q(k-1))^3)*(M(k)))/(6*(Q(k)- Q(k-1)))) +
(((Q(k)-x)*H(k-1) + (x-Q(k-1))*(H(k)))/(Q(k)- Q(k-1))) - (1/6)*(Q(k)-Q(k1))*((Q(k)-x)*M(k-1)+ (x-Q(k-1))*M(k));
e(k) = (exp(x))- s;
g = exp(x);
plot(x,g)
hold on
plot(x,s,'.')
hold on
plot(x,e(k))
hold on
hold on
end
disp('maximum error')
error = max(abs(e))
% root mean square error
E = e*e';
rms = (sqrt(E))/2
A = zeros(n,n);
X = zeros(n,1);
b = zeros(n,1);
% generating the coefficient matrix A
for i =1:1:n
for j =1:1:n
A(i,j) = 1/((i-1)+(j-1)+1);
end
end
A
% generating the rhs vector b, by intergration
syms x;
for i =1:1:n
b(i,1) = int((x^(i-1))*exp(x),x,-1,1);
end
% solving for alphas by gauss elimination
for i=1:1:n-1
[col index] = max(abs(A(i:n,i)));
col;
index = index+i-1;
if A(i,i)<col
C = A(i,:);
A(i,:)= A([index],:);
A([index],:)=C;
tem = b(i,:);
b(i,:) = b([index],:);
b([index],:) = tem;
end
for j = i+1:1:n
m(j) = A(j,i)/A(i,i);
A(j,:) = A(j,:) - A(i,:)*m(j);
b(j,:)= b(j,:)- b(i,:)*m(j);
end
end
X = zeros(n,1);
X(n)= b(n)/A(n,n);
for i= n-1:-1:1
s= b(i);
for j=i+1:1:n
s=s-A(i,j)*X(j);
end
X(i)=s/A(i,i);
end
X;
% error
fy =0;
for y = -1:0.01:1;
for i =1:1:n
end
fy
end
fy =fy+(X(i)*y^(i-1));