MATLAB code 4th sem numerical analysis
MATLAB code 4th sem numerical analysis
Q1. A student wrongfully wrote 35.3468 instead of 35.4386. Find out Error, Relative Error and
Percentage Error of the given problem by using MATLB program.
MATLAB Code:
clc
clearall
xc=35.4386;
xi=35.3468;
error=abs(xc-xi);
relerror=error/xc;
pererror=relerror*100;
OUTPUT:
xc = 35.4386
xi = 35.3468
error = 0.0918
relerror = 0.0026
pererror = 0.2590
Q2. Write a program to find a root of the equation cos x−x e X =0 using Newton-Raphson
Method and perform 5 iterations.
MATLAB Code:
clc
clearall
f=@(x)(cos(x)-x*exp(x));
df=@(x)(- exp(x) - sin(x) - x*exp(x));
a=0;
x=a;
for i=1:1:5
x1=x-f(x)/df(x);
x=x1
end
sol=x
OUTPUT:
x = 1
x = 0.653079403526177
x = 0.531343367606581
x = 0.517909913135675
x = 0.517757383164834
sol = 0.517757383164834
3. Write a program to obtain the polynomial form of the given data and find the value of the
polynomial at 2.5 using Lagrange’s interpolation.
x 1 2 3
f (x) 2 11 34
MATLAB Code:
clc
clearall
formatlong
x=input('Enter list of abscissas:')
y=input('Enter list of ordinates:')
p0=input('Enter value of p0:')
n=length(x);
L=zeros(n,n);
for i=1:n
v=1;
for j=1:n
if i~=j
v=conv(v,poly(x(j)))/(x(i)-x(j))
end
end
L(i,:)=v*y(i);
end
L
p=sum(L)
F=flip(p)
disp('your polynomial is:')
for k=n:-1:2
fprintf('+(%.2fx^%d)',F(k),k-1)
end
fprintf('+(%.2f)\n',F(1))
A=polyval(p,p0)
fprintf('approximate value at given data point is:%.4f',A)
OUTPUT:
Enter list of abscissas:[1 2 3]
x =
1 2 3
y =
2 11 34
p0 =
2.500000000000000
v =
-1 2
v =
v =
1 -1
v =
-1 4 -3
v =
0.500000000000000 -0.500000000000000
v =
L =
1 -5 6
-11 44 -33
17 -51 34
p =
7 -12 7
F =
7 -12 7
A =
20.750000000000000
Q4. Write a MATLAB program to obtain the forward difference polynomial P(x) and obtain
P(0.25) from the given data.
x 0.1 0.2 0.3 0.4 0.5
f (x) 1.4 1.56 1.76 2 2.8
INPUT
clc
clearall
formatlong
x=input('Enter list of abscissas:')
y=input('Enter list of ordinates:')
n=length(x);
h=x(2)-x(1);
F=zeros(n,n);
F(:,1)=y;
for j=2:n
for i=j:n
F(i,j)=F(i,j-1)-F(i-1,j-1);
end
end
F
C=F(n,n);
for k=n-1:-1:1
p=poly(x(1))/h;
p(2)=p(2)-(k-1);
C=conv(C,p)/k;
m=length(C);
C(m)=C(m)+F(k,k);
end
C
pvalue=p(0.25)
OUTPUT
x =
y =
F =
1.400 0 0 0 0
1.560 0.160 0 0 0
1.760 0.200 0.0400 0 0
2.000 0.2400 0.04000 0 0
2.280 0.280 0.040 0 0
C =
pvalue =
1.655