title: Lapack routine dgesv: system is exactly singular: U[2,2] = 0
body: <p>I am trying to use R's solve() function to find the solution to a system of linear equations. The coefficients matrix is 2X2. My code below is written into an R file that I execute after it finished being written. </p>
  
  <p>Before calling <code>solve</code>, I check to see if the determinant is not 0:</p>
  
  <pre><code>  int prod1 = x * y_2;
    int prod2 = x_2 * y;
    int determinant = prod1 - prod2;
    if (determinant != 0) {
        strcat(Q, "A = array(c(");
        strcat(Q, numx);
        strcat(Q, ", ");
        strcat(Q, numx_2);
        strcat(Q, ", ");
        strcat(Q, numy);
        strcat(Q, ", ");
        strcat(Q, numy_2);
        strcat(Q, "), dim = c(2,2,1))\n");
        strcat(Q, "b = c(");
        strcat(Q, numz);
        strcat(Q, ", ");
        strcat(Q, numz_2);
        strcat(Q, ")\n");
        strcat(Q, "solve(A[,,1],b)\n");
  }
  </code></pre>
  
  <p>I then <code>fputs</code> Q into a R file that my program then opens and compute the commands. However, my if statement doesn't seem to be correctly catching the singular matrices. </p>
  
  <p>I get an output like this</p>
  
  <pre><code>Execution halted
  Error in solve.default(A[, , 1], b) : 
    Lapack routine dgesv: system is exactly singular: U[2,2] = 0
  Calls: solve -&gt; solve.default
  //repeat above line for another 60 lines//
      the value of determinant: 1
  the value of determinant: 1
  the value of determinant: 1the value of determinant: 1
  the value of determinant: 1the value of determinant: 1
  the value of determinant: 1the value of determinant: 1
  the value of determinant: 1the value of determinant: 1
  the value of determinant: 2the value of determinant: 2
  the value of determinant: 2the value of determinant: 2 
  //this continues for another 20 lines
  Error in solve.default(A[, , 1], b) : 
    Lapack routine dgesv: system is exactly singular: U[2,2] = 0
  Calls: solve -&gt; solve.default
  Execution halted
  //this continue again till I CTRL + C
  </code></pre>
  
  <p>How am I not catching the singular matrices?</p>