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


but I do not know how to exploit this.

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


first converts


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.

  • $\begingroup$ Would DeleteCases not suffice? $\endgroup$ Oct 20, 2014 at 15:33
  • $\begingroup$ can you post an example where LinearSolve[A,b] returns LinearSolve[A,b] and nothing else? $\endgroup$
    – Nasser
    Oct 20, 2014 at 16:36
  • $\begingroup$ @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. $\endgroup$ Oct 20, 2014 at 16:55

2 Answers 2


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.

reference: http://reference.wolfram.com/language/ref/Check.html

  • 1
    $\begingroup$ 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! $\endgroup$ Oct 20, 2014 at 17:16

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

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

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


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.