Professional Documents
Culture Documents
MATLAB Code For Jacobi-: For For If End End End For For If End If End
MATLAB Code For Jacobi-: For For If End End End For For If End If End
clc;
clear all;
clearvars;
N = 20;
n = N^2;
count=1;
for i = 1:n
for j =1:n
if(i==j)
D(i,j) = 4;
end
end
end % generated D matrix with all diagonal elements 4 (given)
S=zeros(4,4); % Generating a 4x4 zero matrix S to get A
for t=1:N:(n)-N
for i=t:t+N-1
if(i<t+N-1)
S(i,i+1)=-1;
end
if(i>t)
S(i,i-1)=-1;
end
S(i,i+N)=-1;
S(i+N,i)=-1;
end
end % Making the value "-1" to all the elements above
% and below diagonal elements (as given in Question)
while (dum==0)
x = (D_inv)*(B-S*x0); %Mathematical expression for Jacobii
error = x - x0; %Generating error= new value- previous value
error_t = error'; %creating transpose of error matrix
sum(count) = sqrt(error_t*error); %Norm of error matrix by taking inner product with transpose
x0 = x; % Putting newly generated solution matrix to prev value for next iteration
if (sum(count) < 10^-5) % if error matrix stored in sum is 10^-5
dum = 1; %again enter inside while loop
else
dum = 0; %come outside while loop
end
count = count + 1; %increase count value
end
figure(1);
plot(sum);
clc;
clear all;
clearvars;
N = 20;
n = N^2;
count = 1;
for i = 1:n
for j =1:n
if(i==j)
D(i,j) = 4;
end
end
end % generated D matrix with all diagonal elements 4 (given)
S=zeros(4,4); % Generating a 4x4 zero matrix S to get A
for t=1:N:(n)-N
for i=t:t+N-1
if(i<t+N-1)
S(i,i+1)=-1;
end
if(i>t)
S(i,i-1)=-1;
end
S(i,i+N)=-1;
S(i+N,i)=-1;
end
end % Making the value "-1" to all the elements above
% and below diagonal elements (as given in Question)