how to do gaussian elimination with partial pivoting in matlab

Here's an implementation of Gaussian Elimination with Partial Pivoting in MATLAB:

main.m
function [x] = gauss_elim_pivot(A,b)
% Gaussian elimination with partial pivoting
% A is the coefficient matrix
% b is the right-hand-side vector
% x is the solution vector
% Author: Adarsh Trivedi

% Get the size of the matrix
n = size(A,1);

% Concatenate A and b into one matrix
A = [A, b];

% Loop over each column of A
for j = 1:n
    % Find the row with the largest absolute value in the jth column
    max_row = j;
    for i = j+1:n
        if abs(A(i,j)) > abs(A(max_row,j))
            max_row = i;
        end
    end
    
    % Swap the current row with the row with the largest absolute value
    if max_row ~= j
        temp = A(j,:);
        A(j,:) = A(max_row,:);
        A(max_row,:) = temp;
    end
    
    % Eliminate the jth variable from all rows below the current row
    for i = j+1:n
        factor = A(i,j) / A(j,j);
        A(i,:) = A(i,:) - factor * A(j,:);
    end
end

% Back-substitute to get the solution vector
x = zeros(n,1);
for i = n:-1:1
    x(i) = (A(i,n+1) - A(i,i+1:n)*x(i+1:n)) / A(i,i);
end
1032 chars
43 lines

Here's an example of how to use the function:

main.m
% Define the coefficient matrix A and the right-hand-side vector b
A = [1 2 -1; 2 -1 1; 2 1 1];
b = [8; 3; 5];

% Solve the system of equations using Gaussian elimination with partial pivoting
x = gauss_elim_pivot(A,b);

% Display the solution vector
disp(x);
260 chars
10 lines

Note that this implementation assumes that A is invertible. If A is singular or nearly singular, you may encounter numerical stability issues.

gistlibby LogSnag