Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
function x=Gauss_jordan(A,b) %GAUSS_JORDAN % % calling % % % % inputs: % % % % % output: % % % % solve the linear system Ax = b using Gauss Jordan Method sequences: x = Gauss_jordan ( A, b ) Gauss_jordan ( A, b ) A b x coefficient matrix for linear system (matrix must be square) right-hand side vector solution vector (i.e., vector for which Ax = b)
[n,nn]=size(A);
%A is n by n Matrix
% % checking that the matrix A is squared % if ( n ~= nn ) disp ( 'gauss_jordan error: Square coefficient matrix required' ); return; end; % % checking that the length of b matrix is the same as the coeff matrix % nb = length ( b ); if ( n ~= nb ) disp ( 'gauss_Jordan error: Size of b-vector not compatible with matrix dimension' ) return; end; % %checking that the matrix A is non-singular % % % first: checking that every row of Matrix A is a non-zero row % for i= 1:n if(A(i,:)==0) disp('Gauss_jordan error: A is a singular matrix since it consists of a zero row'); return end end
% % Second: checking that every column of Matrix A is a non-zero column % for i= 1 : n if(A(:,i)==0) disp('Gauss_jordan error: A is a singular matrix since it consists of a zero column') return end end % % third: checking that there is no any equal rows in the matrix A % for i= 1 :n for j= 1:n if(A(i,:)==A(j,:)& i ~=j) disp('Gauss_jordan error: A is a singular matrix since it consists two equal rows') return end end end % % fourth: checking that there is no any equal columns in the matrix A % for i=1:n for j=1:n if(A(:,i)==A(:,j)& i~=j) disp('Gauss_jordan error: A is a singular matrix since it consists two equal columns') return end end end
% %Declare a variable to count the number of multiplications\divisions %operations % multi = 0; % %Declare a variable to count the number of Additions\subtractions %operations % addi =0 ; % % %
% Augmented matrix
for i= 1:n % look for where it's not zero and switch if necessary if(c(i,i)==0) t=min(find(c(i+1:n,i)~=0)+i); if(isempty(t)) disp('NO unique solution exists'); return end; temp=c(i,:); % swap rows if necessary c(i,:)=c(t,:); c(t,:)=temp; end;
for k=1:n if(k~=i) m(k,i)=-c(k,i)/c(i,i) multi= multi +1; % div\mult counter c(k,:)=c(k,:)+m(k,i)*c(i,:) multi= multi+n-i+1; % div\mult counter addi= addi +n-i+1; % add\sub counter end; end; end; if(c(n,n)==0) disp('NO unique solution exists'); return end; % % %
end; % % the number of arithmetic operations % multi %it display the number of multiplications and divisions %operations used in the program addi %it displays the number of addition and subtractions %operation in the program