# Using conditionals to check if LinearSolve found a solution

Is there some way to check if LinearSolve found a solution using conditionals in Mathematica 9? I need to solve a large number of linear equations, but I am only interested in the cases where there actually is a solution.

If there is no solution for the equation $Ax=b$, the output of LinearSolve will be

LinearSolve[A,b],


but I do not know how to exploit this.

Edit: I found a solution which should work with Mathematica 10:

StringFreeQ[TextString[LinearSolve[A,b]],LinearSolve]


first converts

LinearSolve[A,b]


into a string and then checks whether LinearSolve is part of that string. However, TextString only works with Mathematica 10 to which I do not have access.

• Would DeleteCases not suffice? – DumpsterDoofus Oct 20 '14 at 15:33
• can you post an example where LinearSolve[A,b] returns LinearSolve[A,b] and nothing else? – Nasser Oct 20 '14 at 16:36
• @Nasser If you take A={{0,0},{0,0}} and b={1,0}, then Mathematica will display a message that LinearSolve did not find a solution, which I guess is not considered as output, and LinearSolve[{{0,0},{0,0}},{1,0}] as "official" output. – Train352359 Oct 20 '14 at 16:55

LinearSolve will generate an error message when it fail. Hence you can catch those messages. Number of ways to do this. Here is an example.

mat = {{0, 0}, {0, 0}};
b = {1, 0};
status = True;
status = Check[LinearSolve[mat, b], False, LinearSolve::nosol]

(* False*)


So status can be checked for False. If it is not False, then it passed. So simply set status=False before the call, and after the call do something like If[Not[status]],... etc...

No need to using strings and all of that.

• Check even returns the value of the expression it evaluated if it passed and it lets you choose an arbitrary expression to return in case it did not. Thus there is no need to introduce a dummy variable for checking if you plan on working with the result of the computation anyway. Neat, thanks! – Train352359 Oct 20 '14 at 17:16

checking the Head is another way, useful in a construct like this:

 alist = {{{1, 0}, {0, 1}}, {{0, 0}, {0, 0}}};
Quiet@Select[
{#, LinearSolve[#, {1, 0}] } & /@ alist , Head@#[] == List &


{{{{1, 0}, {0, 1}}, {1, 0}}}