Created
March 22, 2015 13:16
-
-
Save DingWeizhe/ac182620e0711a90a0c7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function x = GaussPivot(A,b) | |
% x = GaussPivot(A,b): | |
% Gauss elimination with pivoting. | |
% input: | |
% A = coefficient matrix | |
% b = right hand side vector | |
% output: | |
% x = solution vector | |
[m,n]=size(A); | |
if m~=n, error('Matrix A must be square'); end | |
nb=n+1; | |
Aug=[A b]; | |
% forward elimination | |
for k = 1:n-1 | |
% partial pivoting | |
[big,i]=max(abs(Aug(k:n,k))); | |
ipr=i+k-1; | |
if ipr~=k | |
Aug([k,ipr],:)=Aug([ipr,k],:); | |
end | |
for i = k+1:n | |
factor=Aug(i,k)/Aug(k,k); | |
Aug(i,k:nb)=Aug(i,k:nb)-factor*Aug(k,k:nb); | |
end | |
end | |
% back substitution | |
x=zeros(n,1); | |
x(n)=Aug(n,nb)/Aug(n,n); | |
for i = n-1:-1:1 | |
x(i)=(Aug(i,nb)-Aug(i,i+1:n)*x(i+1:n))/Aug(i,i); | |
end | |
a=[0,3,-6,6,3;3,-7,8,-5,8;3,-9,12,-9,6;] | |
b=[-5,9,15] | |
x=GaussPivot(a,b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment