Advertisement
Guest User

gaussSiedelPivot

a guest
Sep 22nd, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 2.12 KB | None | 0 0
  1. clear all;
  2. clc;
  3.  
  4. % Tolerance
  5. tolerance = 5;
  6. Es = 0.5*10^(2-tolerance);
  7.  
  8. breakFlag = 0;
  9.  
  10. % Aug matrix
  11. A = [ 3 7 13 76
  12.       1 5 3 28
  13.       12 3 -5 1];
  14.  
  15. needsPivoting = 0;
  16.  
  17. % Aug Matrix split
  18. [m,n] = size(A);
  19. B = A(:, n).';
  20. A(:, n) = [];
  21.  
  22. clear m;
  23. clear n;
  24.  
  25. [rows, columns] = size(A);
  26.  
  27.  
  28. % CONVERGENCE
  29. for i=1:rows
  30.     sum = 0;
  31.     for j=1:columns
  32.         if(i~=j)
  33.             sum = sum + abs( A(i, j) );
  34.         end
  35.     end
  36.     if( abs( A(i, i) ) < sum )
  37.         needsPivoting = 1;
  38.         break;
  39.     end
  40. end
  41.  
  42. % PIVOTING
  43. if( needsPivoting )
  44.     for i=1:(rows-1)
  45.         for z=2:rows
  46.             sum = 0;
  47.             for j=1:columns
  48.                 if(i~=j)
  49.                     sum = sum + abs( A(i, j) );
  50.                 end
  51.             end
  52.             if( abs( A(i, i) ) < sum )
  53.                 tempRowA = A(i, :);
  54.                 tempRowB = B(i);
  55.                 A(i, :) = A(z, :);
  56.                 B(i) = B(z);
  57.                 A(z, :) = tempRowA;
  58.                 B(z) = tempRowB;
  59.             end
  60.         end
  61.     end
  62. end
  63.  
  64. % Gauss Siedel
  65.  
  66. x = zeros(columns, 1);
  67. n = length(x);
  68. iteration = 1;
  69.  
  70.  
  71. while(1)
  72.     for i=1:n
  73.         temp = 0;
  74.         if( iteration==1 )
  75.            for j=1:n
  76.               if(i~=j)
  77.                   temp = temp + A(i, j)*x(j, iteration);
  78.               end
  79.            end
  80.            x(i, iteration) = (B(i) - temp)/A(i, i);
  81.         else
  82.            for j=1:n
  83.               if(i~=j)
  84.                   temp = temp + A(i, j)*x(j, iteration-1);
  85.               end
  86.            end
  87.            x(i, iteration) = (B(i) - temp)/A(i, i);
  88.            
  89.         end
  90.        
  91.     end
  92.  
  93.  
  94.     for i=1:n
  95.         if( iteration>2 )
  96.             errors(i) = (abs(x(i, iteration) - x(i, iteration-1))/x(i, iteration))*100;
  97.             Ea(iteration-2) = max(errors);
  98.             if( Ea(iteration-2) <= Es )
  99.                 breakFlag = 1;
  100.                 break;
  101.             end
  102.         end
  103.     end
  104.     if(breakFlag == 1)
  105.         break;
  106.     end
  107.     iteration = iteration + 1;
  108. end
  109.  
  110. [m, n] = size(x);
  111.  
  112. display(x(:, n));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement