You are on page 1of 23

MATLAB CODE.

1. Power method.

%% Power method
% Dominant eigenvalue and its eigenvector
% Manoj K. Yadav
%%
A=input('Enter a square matrix :\n');
x0=input('Enter initial guess : \n');
tol=10^(-5);

x0=x0/norm(x0,inf);
x1=A*x0;
x1=x1/norm(x1,inf);
R_Q=(x1'*A*x1)/(x1'*x1); % Rayleigh Quotient
iter=0;

while (norm(A*x1-R_Q*x1,inf)>=tol && iter<=1000)


x0=x1;
x1=A*x1;
x1=x1/norm(x1,inf);
R_Q=(x1'*A*x1)/(x1'*x1);
iter=iter+1;
disp([x0 x1]); disp(R_Q);
end

disp('No. of iterations')
disp(iter)
2. Inversion_ power method.

%% Inverse Power method


% Manoj K. Yadav
%%
A=input('Enter a square matrix :\n');
x0=input('Enter initial guess : \n');

tol=10^(-4);
x0=x0/norm(x0,inf);
x1=A\x0;
x1=x1/norm(x1,inf);
R_Q=(x1'*x1)/(x1'*(A\x1));
iter=0;

while (norm(A*x1-R_Q*x1,inf)>=tol && iter<=1000)


x0=x1;
x1=A\x0;
x1=x1/norm(x1,inf);
R_Q=(x1'*x1)/(x1'*(A\x1));
iter=iter+1;
disp([x0 x1]); disp(R_Q);
end

disp('No. of iterations')
disp(iter)

3. Least squares method.

%% Least squares method


% Chebyshev polynomials {1,x,2*x^2-1}
% p(x)=a+b*x+c*(2*x^2-1)
% x=[0.1; 0.2; 0.3; 0.4; 0.5; 0.6]
% y=[0.76; 0.58; 0.44; 0.35; 0.28; 0.2]
% Manoj K. Yadav
%%
x=input('Enter input vector:\n');
y=input('Enter output vector:\n');

n=length(x);
z=linspace(min(x),max(x));

A_2=[n,sum(x),2*sum(x.*x)-n;sum(x),sum(x.*x),2*sum(x.^3)-
sum(x);sum(x.*x),sum(x.^3),2*sum(x.^4)-sum(x.*x)];
B_2=[sum(y);sum(x.*y);sum((x.^2).*y)];
c2=A_2\B_2;
p2=@(x)(c2(1)+c2(2)*x+c2(3)*(2*x.*x-1));

plot(x,y,'o-')
hold on
plot(z,p2(z),'c')
xlabel('x=[0.1; 0.2; 0.3; 0.4; 0.5; 0.6]')
ylabel('y=[0.76; 0.58; 0.44; 0.35; 0.28; 0.2]')
legend('data points','Least squares model')
hold off

4. Lagrange.

clc
clear
x=[0; 1; 2; 4; 5; 6];
f=[1; 14; 15; 5; 6; 19];
n=length(x);
%y=3; % The value at which interpolation has to be carried out
y=0:0.1:6;
l=zeros(n,1);
p=zeros(length(y),1);

for k=1:length(y)
for i=1:n
prod=1;
for j=1:n
if i~=j
prod=prod*(y(k)-x(j))/(x(i)-x(j));
end
end
l(i)=prod;
end
p(k)=sum(l.*f);
end

scatter(x,f,'k','filled');
hold on
plot(y,p,'r');
title('Lagrange interpolation')
xlabel('x')
ylabel('f')
legend('exact data','interpolated')

5. Divided difference.

clc
clear
x=[0; 1; 2; 4; 5; 6];
f=[1; 14; 15; 5; 6; 19];
n=length(x);
%y=3; % The value at which interpolation has to be carried out

y=0:0.1:6;
dd=zeros(n-1,n-1); % Divided Difference matrix
p=zeros(length(y),1);

for i=1:n-1
dd(i,1)=(f(i+1)-f(i))/(x(i+1)-x(i));
end
for j=2:n-1
for i=1:n-j
dd(i,j)=(dd(i+1,j-1)-dd(i,j-1))/(x(i+j)-x(i));
end
end
disp(dd);

for l=1:length(y)
p(l)=f(1);
for k=1:n-1
prod=1;
for j=1:k
prod=prod*(y(l)-x(j));
end
p(l)=p(l)+prod*dd(1,k);
end
end

scatter(x,f,'k','filled');
hold on
plot(y,p,'b');
title('Newton Divided Difference')
xlabel('x')
ylabel('f')
legend('exact data','DD interpolated')

6. Trapezoidal rule.

%% Trapezoidal and Simpson's 1/3 rule


% Manoj K. Yadav
%%
format long
f=@(x)sin(x);
x_0=input('Enter lower limit: \n');
x_n=input('Enter upper limit: \n');
n=input('Number of sub-intervals: \n');

h=(x_n-x_0)/n;
x=x_0:h:x_n;
S_1=f(x(1))+f(x(n+1));
S_2=0; S_3=0; S_4=0;

for i=2:n
S_2=S_2+f(x(i));
end
I_T=(h/2)*(S_1+2*S_2); % Composite Trapezoidal Rule

for i=2:2:n
S_3=S_3+f(x(i));
end
for i=3:2:n
S_4=S_4+f(x(i));
end
I_S=(h/3)*(S_1+4*S_3+2*S_4); % Composite Simpson's 1/3rd
Rule
I=integral(f,x_0,x_n); % Integral by MATLAB built-in function

7. Gaussian Quadrature.

% Gaussian Quadrature

format long
% N=input('Enter a natural number: \n');
f=input('Enter the integrand function: \n');
a=input('Enter lower limit of integration: \n');
b=input('Enter upper limit of integration: \n');

% 2-point Gaussian Quadrature


w_2=[1., 1.]; % weights
x_2=[-1./sqrt(3), 1./sqrt(3)]; % Nodes
y_2=0.5*(b-a)*x_2 + 0.5*(a+b);
I_2G=0.5*(b-a)*w_2*f(y_2)';
disp(I_2G)

% 3-point Gaussian Quadrature


w_3=[5./9, 8./9, 5./9]; % weights
x_3=[-sqrt(3./5.), 0, sqrt(3./5.)]; % Nodes
y_3=0.5*(b-a)*x_3 + 0.5*(a+b);
I_3G=0.5*(b-a)*w_3*f(y_3)';
disp(I_3G)

I=integral(f,a,b);
disp(I)
8. Backward Euler method.

% Backward Euler method


% b = the point up to which you obtain the results
% x0 = initial condition of x
% y0 = initial condition of y
% step size
clc
clear all
f= @(t,y) (y+t^2-2)/(t+1);
exact=@(t) (t.^2+2*t+2)-2.*(t+1).*log(t+1);
x0=0.; h=0.05; b=3;
x = x0:h:b;
y(1) = exact(x0); % y(x0)=y0;

for i=1:(length(x)-1)
y(i+1) =((x(i+1)+1)*y(i)+ h*(x(i+1)^2-2))/(x(i+1)+1-h);
end

subplot(1,2,1)
plot(x,exact(x),'r-');
hold on
plot(x,y,'k*');
hold off
xlabel('x');
ylabel('y');
legend('Exact solotion','Backward Euler')

subplot(1,2,2)
plot(x,abs(y-exact(x)),'r-');
xlabel('x');
ylabel('Error');
9. Euler.

% Euler
% b = the point up to which you obtain the results
% x0 = initial condition of x
% y0 = initial condition of y
% step size
clc
clear all
f= @(t,y) (y+t^2-2)/(t+1);
exact=@(t) (t.^2+2*t+2)-2.*(t+1).*log(t+1);
x0=0; h=0.1; b=3;
x = x0:h:b;
y(1) = 2; % y(x0)=y0;

for i=1:(length(x)-1)

y(i+1) = y(i) + h*f(x(i),y(i));

end

subplot(1,2,1)
plot(x,exact(x),'r-');
hold on
plot(x,y,'k*');
hold off
xlabel('x');
ylabel('y');
legend('Exact solotion','Euler')

subplot(1,2,2)
plot(x,abs(y-exact(x)),'r-');
xlabel('x');
ylabel('Error');

10. RK2.

% Runge Kutta Method 2nd Order


% b = the point up to which you obtain the results
% x0 = initial condition of x
% y0 = initial condition of y
% step size
clc
clear all
f= @(t,y) (y+t^2-2)/(t+1);
exact=@(t) (t.^2+2*t+2)-2.*(t+1).*log(t+1);
x0=0; h=0.1; b=3;
x = x0:h:b;
y(1) = 2; % y(x0)=y0;

for i=1:(length(x)-1)
k1 = h*f(x(i),y(i));
k2 = h*f(x(i)+h,y(i)+k1);
y(i+1) = y(i) + (1/2)*(k1+k2);
end

subplot(1,2,1)
plot(x,exact(x),'r-');
hold on
plot(x,y,'k*');
hold off
xlabel('x');
ylabel('y');
legend('Exact solotion','RK2')
subplot(1,2,2)
plot(x,abs(y-exact(x)),'r-');
xlabel('x');
ylabel('Error');

11. SECANT.

g=@(x)cos(x)-(x*exp(x));
a=1;
b=2;
c=3;
while(abs(a-b)>0.0001)

x=((a*g(b))-(b*g(a)))/(g(b)-g(a));
a=b;
b=x;

c=c+1;
end

a,b
12. REGULAFALSI.

clc
\g/cxzb=@ (x)cos(x)-(x*exp(x));
a=0;
b=1;
c=2;
x=a-((b-a)/(g(b)-g(a)))*g(a);

while abs(g(x))>0.0000001
if(g(a)*g(b)<0)
x=a-(((b-a)/(g(b)-g(a)))*g(a));
if(g(a)*g(x)<0)
b=x;
else
a=x;
end
end

c=c+1;
end

13. NEWTON.

f_x=@(x)(cos(x)-x*exp(x));
df_x=@(x)-sin(x)-exp(x)-x*exp(x);
x_0=0;
maxiter=50;
tolx=10^-4;
x=x_0;
xold=x_0;
for i=1:maxiter
x=x-f_x(x)/df_x(x);
err=abs(x-xold);
xold=x;
if (err<tolx)
break;
end
end
disp(xold);
disp(i);

14. JACOBIAN

x = 0.8;
y = 1.2;
F = @(x,y) (y*cos(x*y)+1);
G = @(x,y) (sin(x*y)+x-y);
Fx = @(x,y)(-y^2*sin(x*y));
Fy = @(x,y) (cos(x*y)-x*y*sin(x*y));
Gx = @(x,y)(y*cos(x*y)+1);
Gy= @(x,y) (x*cos(x*y)-1);
count=0;
e=10^-5;

J=[Fx(x,y),Fy(x,y);Gx(x,y),Gy(x,y)];

while abs(F(x,y))>e &&abs(G(x,y))>e

A=[x;y]-(inv(J))*[F(x,y);G(x,y)];
x=A(1);y=A(2);

count=count+1;
end
disp(A)
disp(count)

15. GAUSSELIMINATION.

A = [-1,1,0,-3 ; 1,0,3,1 ; 0,1,-1,-1 ; 3,0,1,2];


B = [4;0;3;1];
A = [A,B];
X = [0;0;0;0];

n = size(A);
for i = 1:(n-1)
for j = (i+1):n
A(j,:) = A(j,:) - (A(j,i)*A(i,:))/A(i,i);
end
end

disp(A);
B = A( :,5);
A = A( :,1:4);
for i = n:-1:1
sum = 0;
for j = (i+1):n
sum = sum + A(i,j)*X(j);
end
X(i) = (1/A(i,i))*(B(i)-sum);
end
disp (X);

16. FIXED.

g_x=@(x)cos(x)+1/3;
x_1=0.62;
i=0;
x=x_1;
while 1

x=g_x(x);
if (abs(x-g_x(x))<10^(-5))
break;
end
i=i+1;
end
disp(x);
disp(i);

17. DOLITTLE.

clear all;
A=[1 1 1;4 3 -1;3 5 3];
[n,m]=size(A);
B=[1 ;6 ;4];
L=[1 0 0;0 1 0;0 0 1];
U=[1 0 0;0 1 0;0 0 1];
A=A.'
for j=1:n
for i=1:n
t=0;
for k=1:j-1
t=t+(L(i,k)*U(k,j));
end
if i>=j
L(i,j)=A(i,j)-t;
else
U(i,j)=((A(i,j)-t)*(L(i,i))^-1);
end
end
end
A=A.'
Y=L
L=U.'
U=Y.'
Y=(L^-1)*B;
X=(U^-1)*Y;

18. DEFIX.

g_x=@(x)sqrt(1-sin(x));
x_0=0.86;
i=0;
x=x_0;
while 1
x=g_x(x);
if (abs(x-g_x(x))<10^(-3)
break;
end
i=i+1;
end
disp(x);
disp(i);

19. BISECT.

f_x=@(x)(cos(x)-x*exp(x));
n=0;
x_0=0;
x_1=1;
x_temp=(x_0+x_1)/2;
while (abs(f_x(x_temp)))>(10^-3)
if (f_x(x_0)*f_x(x_temp))<0
x_1=x_temp;
x_temp=(x_0+x_1)/2;
else
x_0=x_temp;
x_temp=(x_0+x_1)/2;
end
n=n+1;
end

disp(x_temp);
disp(n);

20. LEAST SQUARES METHOD.


%% Least squares method
% Model :ny=a*exp(x^2)+b*x^3
% Manoj K. Yadav
%%
x=input('Enter input vector:\n');
y=input('Enter output vector:\n');

n=length(x);
z=linspace(min(x),max(x));
A_1=[sum(exp(2*x.*x)) sum((x.^3).*exp(x.*x));sum((x.^3).*exp(x.*x))
sum(x.^6)];
B_1=[sum(y.*exp(x.*x));sum(y.*(x.^3))];
c1=A_1\B_1;

p1=@(x)(c1(1)*exp(x.*2)+c1(2)*x.^3);

hold on
plot(x,y,'o-')
plot(z,p1(z),'r')
hold off

21. TAYLORS METHOD OF ORDER 2.


% Taylor method of order 2
% b = the point up to which you obtain the results
% x0 = initial condition of x
% y0 = initial condition of y
% step size
clc
clear all
f= @(t,y) (y+t^2-2)/(t+1);
Df=@(t,y) (2*t)/(t + 1); %(t^2+2*t+2-y)/((t+1)^2)+(y+t^2-2)/(t+1);
exact=@(t) (t.^2+2*t+2)-2.*(t+1).*log(t+1);
x0=0; h=0.1; b=3;
x = x0:h:b;
y(1) = 2; % y(x0)=y0;

for i=1:(length(x)-1)
y(i+1) = y(i) +h*f(x(i),y(i))+(h^2/2)*Df(x(i),y(i));
end

subplot(1,2,1)
plot(x,exact(x),'r-');
hold on
plot(x,y,'k*');
hold off
xlabel('x');
ylabel('y');
legend('Exact solotion','Taylor-Order2')

subplot(1,2,2)
plot(x,abs(y-exact(x)),'r-');
xlabel('x');
ylabel('Error');

22. STABILITY RK4.

clc
clear all
% Specify x range and number of points
x0 = -3;
x1 = 3;
Nx = 301;
% Specify y range and number of points
y0 = -3;
y1 = 3;
Ny = 301;
% Construct mesh
xv = linspace(x0,x1,Nx);
yv = linspace(y0,y1,Ny);
[x,y] = meshgrid(xv,yv);
% Calculate z
z = x + i*y;
%Euler growth factor
%g = 1 + z;
%Rk2 growth factor
%g = 1 + z+ 0.5*z.^2;
%Rk4 growth factor
g = 1 + z+ 0.5*z.^2+(1/6)*z.^3+(1/24)*z.^4;
% Calculate magnitude of g
gmag = abs(g);
% Plot contours of gmag
contour(x,y,gmag,[1 1],'k-');
axis([x0,x1,y0,y1]);
axis('square');
xlabel('Real \lambda\Delta t');
ylabel('Imag \lambda\Delta t');
title('RK Methods')
grid on;

23. RK4.
% Runge Kutta Method 4th Order
% b = the point up to which you obtain the results
% x0 = initial condition of x
% y0 = initial condition of y
% step size
clc
clear all
f= @(t,y) (y+t^2-2)/(t+1);
exact=@(t) (t.^2+2*t+2)-2.*(t+1).*log(t+1);
x0=0; h=0.1; b=3;
x = x0:h:b;
y(1) = 2; % y(x0)=y0;

for i=1:(length(x)-1)

k1 = h*f(x(i),y(i));
k2 = h*f(x(i)+0.5*h,y(i)+0.5*k1);
k3 = h*f((x(i)+0.5*h),(y(i)+0.5*k2));
k4 = h*f((x(i)+h),(y(i)+k3));

y(i+1) = y(i) + (1/6)*(k1+2*k2+2*k3+k4);

end

subplot(1,2,1)
plot(x,exact(x),'r-');
hold on
plot(x,y,'k*');
hold on

[t Y]=ode45('fun1',[0 3],2);
plot(t,Y,'b.');
hold off
xlabel('x');
ylabel('y');
legend('Exact solotion','RK4','ODE45')
subplot(1,2,2)
plot(x,abs(y-exact(x)),'r-');
xlabel('x');
ylabel('Error');

THE END.

You might also like