Page 231 - MATLAB an introduction with applications
P. 231

216 ———  MATLAB: An Introduction with Applications

                   Run_pr_E4.2.m

                   A = [2 1 1 –1;1 5 –5 6; –7 3 –7 –5; 1 –5 2 7];
                   b = [10;25;5;11];
                   [x, det] = gauss(A,b)
                   x = A\b
                   gauss.m
                   function [x,det] = gauss(A,b)
                   % Solves A*x = b
                   if size(b,2) > 1; b = b’; end
                   n = length(b);
                   for k = 1:n–1
                   for i= k+1:n
                   if A(i,k) ~ = 0
                   lambda = A(i,k)/A(k,k);
                   A(i,k+1:n) = A(i,k+1:n) – lambda*A(k,k+1:n);
                   b(i)= b(i) – lambda*b(k);
                   end
                   end
                   end
                   if nargout == 2; det = prod(diag(A)); end
                   for k = n:–1:1
                   b(k) = (b(k) – A(k,k+1:n)*b(k+1:n))/A(k,k);
                   end
                   x = b;

                   MATLAB Solution [Using built-in function]:

                   >> A = [2 1 1 –1;1 5 –5 6;–7 3 –7 –5;1 –5 2 7];
                   >> B = [10;25;5;11];
                   >> x = A\B
                   x =
                      25.3587
                     –19.6143
                     –28.9058
                      –7.8027
                   >> x = inv(A) * B
                   x =
                      25.3587
   226   227   228   229   230   231   232   233   234   235   236