MATLAB: Does this Gauss Seidel method algorithm doesn’t work with 4×4 matrix

gaussgauss-seidel

I found the following algorithm for the Gauss Seidel method in this link: Gauss Seidel method – File Exchange – MATLAB Central (mathworks.com)
I decide to make minor changes to it, expecting it to work with a 4×4 matrix, but the algorithm doesn't output the answer correctly. Please can someone tell where the error is to make it run a 4×4 matrix?
Code:
A = [1 2 -1 1; -1 -2 -3 2; 2 1 -1 -5; 1 1 1 1]; % values for augmented matrix A
B = [5; 7; -1; 10]; % Coefficient values of matrix B.
X=[0;0;0;0]; % Initial approximation of solutions.
C=[0;0;0;0]; % A dummy matrix.
Err=[0;0;0;0]; % Error matrix.
P= [ A B ]; % constructing a new augmented matrix called P, using matrix A & B.
[ row col ] = size( P); % Calculating the size of augmented matrix, P
for i = 1:row % checking strictly diagonally dominant matrix
if 2*abs(A(i,i))<= sum(abs(A(i,:)))
disp('Rearrange the equations to make diagonally dominant matrix!!!')
return
end
end
merr = 1;
while merr > 0.0001 % Finding the final result.
for i=1:1:row
C(i,1)=X(i,1);
X(i,1)=(1/P(i,i))*(P(i,col)-sum(A(i,:)*X(:,1))+A(i,i)*X(i,1));
Err(i,1)= abs(C(i,1)-X(i,1));
C(i,1)=X(i,1);
end
merr=max(Err);
end
disp(' The required solution is:')
X(:,1)
Rearrange the equations to make diagonally dominant matrix!!!
The required solution is:
ans =
NaN
NaN
NaN
NaN

Best Answer

A = [1 2 -1 1; -1 -2 -3 2; 2 1 -1 -5; 1 1 1 1]
A = 4×4
1 2 -1 1 -1 -2 -3 2 2 1 -1 -5 1 1 1 1
for K = 1 : size(A,1)
if A(K,K) < sum(A(K,:)) - A(K,K)
fprintf('A(%d,%d) is not dominant!\n', K, K);
end
end
A(1,1) is not dominant! A(4,4) is not dominant!
If you look at that last row of all 1's, you can see that no matter which row you put it in, the diagonal element would be 1 and the sum of the non-diagonal entries in the row would be 3, so it is not possible to move the last row to a different row to make the overall matrix diagonally dominent.
for J = 1 : size(A,1)
sum1 = sum(A(J,:));
at_least_one = false;
for K = 1 : size(A,2)
if A(J,K) >= sum1 - A(J,K)
fprintf('A(%d,:) would be dominant if it were in row %d\n', J, K);
at_least_one = true;
end
end
if ~at_least_one
fprintf('A(%d,:) cannot be dominant in any row!\n', J);
end
end
A(1,:) would be dominant if it were in row 2 A(2,:) would be dominant if it were in row 1 A(2,:) would be dominant if it were in row 2 A(2,:) would be dominant if it were in row 4 A(3,:) would be dominant if it were in row 1 A(3,:) would be dominant if it were in row 2 A(3,:) would be dominant if it were in row 3
A(4,:) cannot be dominant in any row!
NA = A([2 1 3 4],:);
for K = 1 : size(NA,1)
if NA(K,K) < sum(NA(K,:)) - NA(K,K)
fprintf('NA(%d,%d) is not dominant!\n', K, K);
end
end
NA(4,4) is not dominant!
So exchanging rows 1 and 2 gets you closer, but you still have the problem of that 4th row, which cannot be dominant no matter which row it is moved to.
Related Question