Advertisement
swick

Untitled

Oct 22nd, 2019
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. function [ x ] = gauss_elim( A, b )
  2. %%gauss_elim uses Gauss elimination with partial pivoting to solve Ax = b
  3. %%Inputs: A - A matrix
  4. % b - b vector
  5. %%Outputs: x - solution to Ax = b
  6. %%Author: Gavin St. John, University of Florida
  7.  
  8. %append
  9. U = horzcat(A,b);
  10.  
  11. %iterate through each column which needs to be 0'd -> create upper
  12. %triangular matrix
  13. for ii = 1:size(U,1)-1
  14. % figure out which
  15. [~,m] = max(abs(U(ii:end,ii)));
  16. m = m+(ii-1);
  17. U([ii m],:) = U([m ii],:);
  18. % construct a matrix to subtract from U (UppterTriangularModifier)
  19.  
  20. vec = repelem(U(:,ii),1,length(U)); % creates the basis for the matrix
  21. axx = U(ii,ii); % current pivot value
  22. R = repmat(U(ii,:),size(U,1),1); % matrix of rows of current column
  23.  
  24. utmod = (vec./axx).*R; % puts it all together
  25. utmod(1:ii,:) = 0; % makes all rows above current pivot entry 0 so we don't affect stuff we've already operated on
  26. if ii > 1, utmod(:,ii-1) = 0; end % after the first itreration make columns up to the current pivot entry 0
  27. U = U - utmod; % best part
  28. end
  29.  
  30. bf = U(:,end); % split appended matrix back up
  31. Af = U(:,1:end-1);
  32. x = Af\bf; % solve backward substitution
  33.  
  34. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement