Gauss Elimination with partial pivoting

20 views (last 30 days)
Prajwal Srikanth
Prajwal Srikanth on 18 Apr 2019
Hi,
I am trying to perform Gauss-Elimination with partial pivoting in MATLAB and I am unfortunately not obtaining the correct solution vector. My pivots are not getting switched correctly either. I am unsure of what the correct way of coding it in is. Please help me understand what I am doing wrong and what the correct code should look like. Thank you! Below is my code attached:
clc;
clear;
% User enters matrix
m = input('enter the number of rows '); %number of rows
% Trapping bad user inputs
while isempty(m) ||isstring(m)
m = input('\n Error! please enter again the number of rows ');
end
n = input('\n enter the number of columns '); % number of columns
while isempty(n) || isstring(n)
n = input('\n Error! please enter again the number of rows ');
end
% Initializing matrix A with m rows and n columns
A = zeros(m,n);
%Accepting user input for matrix A
for i=1:m
for j=1:n
fprintf('\n Enter the %d row and %d column ',i,j);
A(i,j) = input('\n');
end
end
% Displaying user entered matrix
fprintf('Your Matrix is \n');
disp(A);
% Accepting user input for desired vector b
b = input('Enter a vector b (must be of same dimension as matrix A) : ');
Ab = [A b];
%Process of forward elimination with partial pivoting
[max_row,idx] = max(Ab);
%partial pivoting
for l=1:n
max_row = Ab(l,:);
Ab(l,:) = Ab(idx(l),:);
Ab(idx(l),:) = max_row;
end
for k = 1:m-1
%Forward elimination
mult = A(k+1:m,k)/A(k,k); %This is a multiplier used to reduce pivot row
Ab(k+1:m,:) = Ab(k+1:m,:) - mult*Ab(k+1,:); % row reduction for matrix A
%b(k+1:m,:) = b(k+1:m,:) - mult*b(k,:); % row reduction for desired vector b
end
%initializing solution vector x
x = zeros(m,1);
% obtaining solution vector using back substitution
for k=m:-1:1
x(k) = (Ab(k,end) - Ab(k,k+1:m)*x(k+1:m))/Ab(k,k); % finding the remaining variables
end
% Displaying the reduced matrix
fprintf('The reduced matrix is \n');
disp(Ab);
% displaying solution to user
fprintf('The solution vector is \n');
disp(x);
% Using built in MATLAB functions to compute solution vector
fprintf('Now, comparing answer using built in MATLAB functions');
sol = A\b;
fprintf('The solution is \n');
disp(sol);

Answers (0)

Categories

Find more on Numerical Integration and Differential Equations in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!