Bammmmm…

That’s 87 lines of code for ya, and 49 unlisted (different problem).
This is for anyone that has to solve a numerical system using Jacobi’s Method, Gauss-Seidel, and SOR with an optimal parameter in Matlab without using those convenient call functions (like the engineers get to do):

clear all
close all
clc
hold all
grid on
box on
xlabel(‘X’)
ylabel(‘enorm’)
A = [2 -1; -1 2];
b = [1; 1];
x = zeros(size(b)); %Initial guess is x(0)=0
%
%Assign D
D=eye(size(A));
[D(logical(eye(size(A))))]=[diag(A)]
%
%Assign L
L = tril(A);
L(logical(eye(size(A))))=zeros
%
%Assign U
U = triu(A);
U(logical(eye(size(A))))=zeros
%
%Jacobi’s Method
T = L+U
Y = inv(D);
X = Y*(-T*x+b);
e = X – x;
enorm = norm(e, Inf);
k=0;

while(enorm>=10^-7)
x = X;
X = Y*(-T*X+b);
e = X – x;
enorm = norm(e, Inf);
k = k+1;
semilogy(X, enorm,’o’)
end
disp(‘Jacobi Method iteration count:’)
disp(k)
%
%
%Gauss-Seidel
T = L+D;
x = zeros(size(b)); %Initial guess is x(0)=0
Y = inv(T);
X = Y*(-U*x+b);
e = X – x;
enorm = norm(e, Inf);
k=0;

while(enorm>=10^-7)
x = X;
X = Y*(-U*X+b);
e = X – x;
enorm = norm(e, Inf);
k = k+1;
semilogy(X,enorm,’x’)
end
disp(‘Gauss-Seidel iteration count:’)
disp(k)
%
%SOR
w = 2/(1+sqrt(7/8));
x = zeros(size(b));
T = (w*L + D);
Y = inv(T);
X = Y*(((1-w).*D – w.*U)*x +w.*b);
e = X – x;
enorm = norm(e, Inf);
k=0;

while(enorm>=10^-7)
x = X;
X = Y*(((1-w).*D – w.*U)*X +w.*b);
e = X – x;
enorm = norm(e, Inf);
k = k+1;
semilogy(X,enorm,’*’)
end
disp(‘SOR iteration count:’)
disp(k)

Is that a comparative semilogy plot of all the solutions’ infinity error norms? Eeeeeyup.

Oh and professor:
I told you I could do it in one night.

Update: Yeah the tags are just to be an ass.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s