%section 8.2 computer problem #7

A = [9,-3;-2,8];
b = [6;-4];
n = length(b);
N = 10;             %number of iterations
format long;

x_0 = [0;0];        %initial guess

%first we do Jacobi iteration

Q = zeros(n,n);
for i=1:n
    Q(i,i) = A(i,i);  %Q = diagonal matrix with same diagonal entries as A
end

x = x_0;
for i=1:N
    y = (Q-A)*x + b;
    for j=1:n
        x(j) = y(j)/Q(j,j);   %solve Qx = y
    end
end

disp('Jacobi solution is...')
x

%now we do Gauss-Seidel iteration

I = eye(n);

x = x_0;
for i=1:N
    for i=1:n
        x(i) = b(i);
        for j=1:i-1
            x(i) = x(i)-A(i,j)*x(j);
        end
        for j=i+1:n
            x(i) = x(i)-A(i,j)*x(j);
        end
        x(i) = x(i)/A(i,i);
    end
end

disp('Gauss-Seidel solution is...')
x

%note that Gauss-Seidel solution has 10 correct digits, 
%while Jacob solution has only 5 correct digits!