1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| function x=ppGE(A,b)
%
% Solves Ax=b by Gaussian elimination with partial pivoting.
%
% Input:
% Nonsingular square matrix A of order n
% Vector b of order n
%
% Output:
% Solution vector x
%
% Check to make sure that the matrix A is square, and establish order n
%
tol=1e-15;
[m,n] = size(A);
if m ~=n
error('The matrix is not square.')
end
%
% Perform Gaussian elimination
%
for k=1:n-1
% find max pivot p and its index r relative to diagonal in column k
[p,r] = max(abs(A(k:n,k)));
% check pivot size
if abs(p) <= tol;
fprintf('pivot = %f\n', p);
error('pivot below tolerance');
end
% index of row with maximal element
q=k+r-1;
% interchange rows k and q of A and b
A([k,q],:) = A([q,k],:);
b([k,q]) = b([q,k]);
for i=k+1:n
m=A(i,k)/A(k,k);
for j=k+1:n
A(i,j)=A(i,j)-m*A(k,j);
end
b(i) = b(i)-m*b(k);
end
end
%
% Apply backwards substitution to get solution x
%
for i=n:-1:1
sum=0;
for j=i+1:n
sum = sum + A(i,j)*x(j);
end
x(i) = (b(i)-sum)/A(i,i);
end |
Partager