function [x,flag] = myslash_check(A,b); % MYSLASH Solves a square system of equations A x = b using MYLU. % equivalent for square matrices: % >> x = myslash(A,b) % >> x = A \ b % _check version returns flag for divide by zero; doesn't divide by zero flag = false; if size(A,1)~=size(A,2), error('only works on square matrices'), end m = size(A,1); if (size(b,1)~=m)|(size(b,2)~=1), error('b must be column vector w same dim as A'), end [p,A] = mylu(A); % now solve LU x = P b; forward substitution for L y = b y = zeros(m,1); y(1) = b(p(1)); for k=2:m y(k) = b(p(k)) - A(p(k),1:k-1) * y(1:k-1,1); % y=L^{-1} P b end % back substitution for U x = y x = y; if A(p(m),m) == 0, flag = true; return, end x(m) = y(m) / A(p(m),m); % x is col vector w correct x(m) for j=m-1:-1:1 if A(p(j),j) == 0, flag = true; return, end x(j) = (y(j) - A(p(j),j+1:m) * x(j+1:m)) / A(p(j),j); end