fixing code to have diagonal (1's) having the first matrix start with a zero
2 views (last 30 days)
Show older comments
% Gauss Jordan Elimination for a system of equations
% Matrix form of the problem: [A]{x} = {b}
% [A] matrix of coefficients
% {x} column vector of unknowns
% {b} column vector of forcing parameters or constants
%% Clear
clear
clc
% Set format to display
format short
% Define matrix [A]
% Pivoting.... a bad example
A = [0 2 1; 1 1 2; 2 1 1];
b = [4; 6; 7];
% Augment the matrix [A] into [Ag]
Ag = [A b];
disp('Initial augmented matrix: ')
disp(Ag);
%% Main GJ loop
m = size(Ag,1); % Number of rows
for ii = 1:m
% Normalize the pivot row | get pivot element and pivot row
p_row = Ag(ii,:);
p_el = Ag(ii,ii);
n_row = p_row/p_el; % Normalization of the pivot row
Ag(ii,:) = n_row; % Reassigning normalized row into Ag
% Perform the row operations
for jj = 1:m
if ii ~= jj
Ag(jj,:) = round(n_row*(-1*Ag(jj,ii)) + Ag(jj,:),4);
end
end
% Display the current matrix Ag
disp('Current Ag: ');
disp(Ag)
pause(3)
end
this is the code i have but how can i fix it to implement the Gauss Jordan elimination process, implement pivoting (i.e. swapping the order of rows in the augmented matrix Ag) in order for the method not to crash due to the potential for division by zero.
0 Comments
Answers (1)
Adrián Szemenyei
on 21 Nov 2020
Edited: Adrián Szemenyei
on 21 Nov 2020
If I understand the question correctly you just have to do this: if the pivot is zero, check the elements under the pivot, change the rows.
Note that you do not actually need to go through all the elements one-by-one (using 2 for loops).
In matlab you can do arithmetics on matrices and on arrays.
Like this:
Ag = [A b];
m=size(Ag,1);
for i=1:m
if Ag(i,i)==0 %if the pivot is zero
tmp=find(Ag(:,i)~=0);
tmp=tmp(tmp>i);
if isempty(tmp)
disp('singular');
break;
end
tmp=tmp(1); %I choose the first but you can choose one randomly using the randperm fnc as an index
Ag([i,tmp],:)=Ag([tmp,i],:);%swap rows
end
Ag(i,:)=Ag(i,:) ./ Ag(i,i);%ones in the diagonal
Ag(i+1:m,:)=Ag(i+1:m,:) - ( Ag(i+1:m,i) .* Ag(i,:) ) ;
Ag(1:i-1,:)=Ag(1:i-1,:) - ( Ag(1:i-1,i) .* Ag(i,:) ) ;
end
You might want to save which rows you swapped...
0 Comments
See Also
Categories
Find more on Numerical Integration and Differential Equations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!