2

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.

Before calling solve, I check to see if the determinant is not 0:

  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");
}

I then fputs 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.

I get an output like this

Execution halted
Error in solve.default(A[, , 1], b) : 
  Lapack routine dgesv: system is exactly singular: U[2,2] = 0
Calls: solve -> 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 -> solve.default
Execution halted
//this continue again till I CTRL + C

How am I not catching the singular matrices?

maddie
  • 1,854
  • 4
  • 30
  • 66

0 Answers0