Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Q2) Gaussian elimination

function x=Guass_elim(A,b) %GAUSS_ELIM % solve the linear system Ax = b using Gaussian elimination with backward substitution %A is n by n

[n,nn]=size(A); % % %

Gaussian elimination

q = 0; %a variable for counting the number of mult/div operations in the guass elim ad=0 % a variable for counting the number of add\sub operations in the guass elim % % checking that the matrix is squared % if ( n ~= nn ) disp ( 'gauss_elim 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_elim error: Size of b-vector not compatible with matrix dimension' ) return; end;

% % checking that the matrix have no zeros rows % for o= 1:n if(A(o,:)==0) disp('singular matrix with a zeros row'); return end end %

% checking that the the matrix have no zeros column % for z= 1 : n if(A(:,z)==0) disp('singular matrix with a zeros column') return end end % % checking that the matrix have no equal rows % for i= 1 :n for j= 1:n if(A(i,:)==A(j,:)& i ~=j) disp('two rows equal singular') return end end end % % checking that the matrix have no equal columns % for i=1:n for j=1:n if(A(:,i)==A(:,j)& i~=j) disp('two columns equal singular') return end end end

c=[A b]; % Augmented matrix for i= 1:n-1 %checking that the diagonal elements are not equal zeros % if any of them equal zero swap rows 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 c(i,:)=c(t,:); c(t,:)=temp; end;

for k=i+1:n m(k,i)=-c(k,i)/c(i,i) m(k,i)

q= q+1 % div\mult counter c(k,:)=c(k,:)+m(k,i)*c(i,:) q= q+n-i+1 % div\mult counter ad= ad+n-i+1 % add\sub counter end; end; q %div\mult counter ad %add\sub counter % % %

back substitution

bad=0; %back sub addition counter x(n,1)=c(n,n+1)/c(n,n); m = 1; %back sub multiplication counter for i=n-1:-1:1 x(i,1)=(c(i,n+1)-c(i,i+1:n)*x(i+1:n,1))/c(i,i); m=m+1+n-i bad=bad+n-i m

end; addsub=ad+bad %the addition of the ad\sub counter for guass elim and the add\sub counter for back sub counter divmul = m+ q % the addition of the div\mul counter for guass elim and the div\mul counter for back sub counter

You might also like