Skip to content

Instantly share code, notes, and snippets.

@zaman
Created April 12, 2012 11:43
Show Gist options
  • Save zaman/2366724 to your computer and use it in GitHub Desktop.
Save zaman/2366724 to your computer and use it in GitHub Desktop.
function [x,iter] = gaussseidel(A,b,tol,max)
% Usage: [x,iter] = gaussseidel(A,b,tol,max)
% Uses Jacobi iteration to solve Ax = b
% Input variables:
% A = matrix
% b = rhs
% tol = l2 tolerance on residue
% max = maximum allowable number of iterations
% Output variables:
% x = solution
% iter = number of iterations
[n,m] = size(A); % Find size of matrix
x = 0*b; % Initial guess
k = 0; % Initialize iteration counter
error = norm(A*x-b,2); % Initial error
while error > tol & k <= max
k = k+1;
for i = 1:n
x(i) = (b(i) - A(i,1:i-1)*x(1:i-1) - ... % Use new values of x
A(i,i+1:n)*x(i+1:n))/A(i,i);
end
error = norm(A*x-b,2);
end
iter = k;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment