Mat Lab Program
Mat Lab Program
(Sahiwal Campus)
1
Question No 1:
Write a Matlab code for fixed point method.
Answer:-
Fixed Point Method Program
Function file;-
%Function
f(x)=exp(-x)-x;
%Program:-
%Fixed Point Method Program.
%Find the root of f(x)=exp(-x)-x using fixed point iteration
%initial value: x=0, error should be less than 0.1
%solution:
%f(x)=exp(-x)-x=0
%x=exp(-x)
clear;
clc;
format('long','g')
i=1;
x(i)=0;
error(i)=9999;
while error(i)>=0.1
x(i+1)=exp(-x(i));
error(i+1)=abs((((x(i+1)-x(i))/(x(i+1)))*100));
i=i+1;
end
disp([x',error'])
2
Output:-
root error(%)
0 9999
1 100
0.367879441171442 171.828182845905
0.692200627555346 46.8536394613384
0.500473500563637 38.3091465933331
0.606243535085597 17.4467896811512
0.545395785975027 11.1566225253813
0.579612335503379 5.90335081440867
0.560115461361089 3.48086697962453
0.571143115080177 1.93080393125982
0.56487934739105 1.10886824205157
0.568428725029061 0.624419119183282
0.566414733146883 0.355568413799569
0.567556637328283 0.201196516135472
3
0.566908911921495 0.114255640221412
0.56727623217557 0.0647515677971472
Question No 2:
Write a Matlab code for Determinant of a Matrix.
Answer:-
Determant of Matrix Program:-
clear;
clc;
4
A=[2 5 7; 3 4 8; 2 5 3]
det(A)
Output:-
2 5 7
A= 3 4 8
2 5 3
5
Ans =28
Question No 3:
Write a Matlab code for Secant Method.
Answer:-
Secant Method Program:-
%Secant Method Program
clear;
clc;
syms x
f=(x^3)-20;
x0=0;
x1=5.5;
error=0.001;
6
for i=2:15
fx0=subs(f,x,x0);
fx1=subs(f,x,x1);
x2=vpa(x1-((x1-x0)/(fx1-fx0))*fx1)
err=vpa(abs((x2-x1)/x2))
if (err<error)
break
end
x0=x1;
root=x2;
x1=x2;
end
Output:-
7
x2 =
0.66115702479338842975206611570248
err =
7.31875
x2 =
1.2354281160188864252450474374428
err =
0.46483569847516641010499770771778
x2 =
7.7508716974883529949466276491132
err =
0.8406078484799041061098315405628
x2 =
1.4899225232520066121941998168577
err =
4.2021978166829583172898262053983
x2 =
1.7159740510333512222235712548459
err =
0.13173365159293491655531622847515
x2 =
3.6518628368921513947810899483912
err =
0.53010993904313821578945643709419
x2 =
2.37890420488482948458703721538
err =
0.53510293915721166733394380902142
x2 =
2.6150566013834004391859132931052
err =
0.090304889146048743760879604352086
x2 =
2.7281458236084431430701097566456
8
err =
0.04145277765081586167153633854614
x2 =
2.7139043922353059629642286395664
err =
0.0052475803546665225181205066351974
x2 =
2.714415029359987153728388595774
err =
0.00018812050447627763970636062744116
>>