Skip to content

Instantly share code, notes, and snippets.

@asw456
Last active December 20, 2015 11:09
Show Gist options
  • Save asw456/6121145 to your computer and use it in GitHub Desktop.
Save asw456/6121145 to your computer and use it in GitHub Desktop.
scriptLab4
function [convf,k,results,xn] = mygaussseidel(A,b,x,niter,tol)
[nrow,~] = size(A);
convf = 0;
results(1,:) = x';
xn = x;
for k = 1:niter
for i = 1:nrow
sigma = 0;
for j = 1:nrow
if (i~=j)
sigma = sigma + A(i,j)*xn(j);
end
end
xn(i) = (b(i)-sigma)/A(i,i);
end
if (norm(x-xn,Inf) / norm(xn,Inf)) < tol
convf = 1;
results(k+1,:) = xn';
break
end
x = xn;
results(k+1,:) = xn';
end
end
function [convf,k,results,xn] = myjacobi(A,b,x,niter,tol)
[nrow,~] = size(A);
convf = 0;
results(1,:) = x';
xn = zeros(nrow,1);
for k = 1:niter
for i = 1:nrow
sigma = 0;
for j = 1:nrow
if (i~=j)
sigma = sigma + A(i,j)*x(j);
end
end
xn(i) = (b(i)-sigma)/A(i,i);
end
if (norm(x-xn,Inf) / norm(xn,Inf)) < tol
convf = 1;
results(k+1,:) = xn';
break
end
x = xn;
results(k+1,:) = xn';
end
end
clear all
clc
A = [ 4 1 1 ; 1 2 3 ; 2 -1 -3];
%A = [ 4 -2 1 ; 3 -6 1 ; -4 1 6];
%A = [ 1 -2 1 ; 3 1 1 ; -4 1 1];
b = [5 ; 5 ; -3];
x = [0 ; 0 ; 0];
niter = 100;
tol = 1e-6;
[convf,i,resultsj,xn] = myjacobi(A,b,x,niter,tol);
i
convf
resultsj(end,:)'
A\b
b
A*resultsj(end,:)'
[convf,i,resultsgs,xn] = mygaussseidel(A,b,x,niter,tol);
i
convf
resultsgs(end,:)'
A\b
b
A*resultsgs(end,:)'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment