mat.pdf

Function myGauss:

function [x,B]=myGauss(A,bb) % function to perform gauss eliminination %FORWARD ELIMINATION n=length(bb); m=zeros(n,1); x=zeros(n,1); B=eye(n,n); for k =1:n-1; %compute the kth column of M m(k+1:n) = A(k+1:n,k)/A(k,k); %compute %An=Mn*An-1; %bn=Mn*bn-1; for i=k+1:n A(i, k+1:n) = A(i,k+1:n)-m(i)*A(k,k+1:n);

end bb(k+1:n)=bb(k+1:n)-bb(k)*m(k+1:n); end U= triu(A); %BACKWARD ELIMINATION x(n)=bb(n)/A(n,n); for k =n-1:-1:1; bb(1:k)=bb(1:k)-x(k+1)* U(1:k,k+1); x(k)=bb(k)/U(k,k); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%55 % Find dimensions of input matrix a=A; [r,c] = size(a);

% If input matrix is not square, stop function if r ~= c disp('Only Square Matrices, please') b = []; return end

% Target identity matrix to be transformed into the output % inverse matrix b = eye(r);

%The following code actually performs the matrix inversion by working % on each element of the input for j = 1 : r for i = j : r if a(i,j) ~= 0 for k = 1 : r s = a(j,k); a(j,k) = a(i,k); a(i,k) = s; s = b(j,k); b(j,k) = b(i,k); b(i,k) = s; end t = 1/a(j,j); for k = 1 : r

a(j,k) = t * a(j,k); b(j,k) = t * b(j,k); end for L = 1 : r if L ~= j t = -a(L,j); for k = 1 : r a(L,k) = a(L,k) + t * a(j,k); b(L,k) = b(L,k) + t * b(j,k); end end end end break end % Display warning if a row full of zeros is found if a(i,j) == 0 disp('Warning: Singular Matrix') b = 'error'; return end end % Show the evolution of the input matrix, so that we can % confirm that it became an identity matrix. B=b; End

Script file:

close all clear all clc A=[8 0 0 10 -3 7; 0 3 8 -5 -1 6; 3 12 -4 8 5 -2; 3 1 0 0 0 4; 0 0 4 -6 0 2; 3 0 5 1 0 -6] b=[17;21;46;13;6;5]; [x inv]=myGauss(A,b)

Command window:

A =

8 0 0 10 -3 7

0 3 8 -5 -1 6

3 12 -4 8 5 -2

3 1 0 0 0 4

0 0 4 -6 0 2

3 0 5 1 0 -6

x =

2.0000

3.0000

1.0000

-0.0000

2.0000

1.0000

inv =

0.0792 -0.0444 0.0012 0.1189 0.1762 0.0020

0.0142 0.1856 0.0379 -0.0118 0.0425 -0.0641

0.0149 0.0297 -0.0012 -0.0744 0.0852 0.0359

0.0209 0.0063 0.0070 -0.1032 -0.0685 0.0403

-0.1220 -0.0085 -0.0003 0.0291 -0.3371 0.2965

-0.0298 0.0381 -0.0115 0.0239 -0.2480 0.0672