function [x,A] = lusolve_nopivoting(A,b) % x = lusolve_nopivoting(A,b) solve the linear system Ax=b using Gaussian elimination % without pivoting. % % [x,LU] = lusolve_nopivoting(A,b) in addition returns a matrix LU which contains % the LU-decomposition of A. % % INPUT: A (Coefficient matrix, assumed invertible, and solvable without row % interchanges.) % b (Right hand side.) % % OUTPUT: x (Solution vector.) % A (The resulting matrix from the forward elimination procedure.) %% initialization and preparation % check if the dimensions of the problem somehow match and return an error % message if not n = length(b); dimA = size(A); if(length(dimA) > 2 || dimA(1)~= n || dimA(2) ~= n) error('The dimensions of A and b do not match.') end % initialize the solution x as zero vector of the correct size x = zeros(size(b)); %% forward elimination for k=1:n-1 % compute the multipliers and store them in the matrix A A(k+1:end,k) = A(k+1:end,k)/A(k,k); % subtract multiples of line k from the next lines A(k+1:end,k+1:end) = A(k+1:end,k+1:end)-A(k+1:end,k)*A(k,k+1:end); end %% back substitution % process the right hand side in the same way as the matrix A for k=1:n-1 b(k+1:end) = b(k+1:end)-A(k+1:end,k)*b(k); end % finally compute the solution of the equation for i=n:-1:1 x(i) = (b(i)-A(i,i+1:end)*x(i+1:end))/A(i,i); end