Select Page

How to Solve R Error in solve.default() Lapack routine dgesv: system is exactly singular

by | Programming, R, Tips

This error occurs when you try to use the solve() function, but the matrix you handle is a singular matrix. Singular matrices do not have an inverse.

The only way to solve this error is to create a matrix that is not singular.

This tutorial will go through the error and solve it with code examples.


Let’s look at an example to reproduce to error. First, we will create a 3×3 matrix using the matrix() function:

mat <- matrix(c(1, 1, 1, 1, 1, 1, 1, 1, 1), ncol=3, nrow=3)

     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    1    1
[3,]    1    1    1

Let’s try to get the inverse of the matrix by using the solve function.

solve(mat)Error in solve.default(mat) : 
  Lapack routine dgesv: system is exactly singular: U[2,2] = 0

The error occurs because mat is a singular matrix. It is not possible to invert a singular matrix. LAPACK is a Linear Algebra package used underneath solve(). DGESV computes the solution to a real system of linear equations A * X = B.

What is a Singular Matrix?

A singular matrix is a square matrix (same number of rows and columns) if its determinant is 0. The inverse of a matrix A is found using the formula A-1 = (adj A) / (det A), where det A is the determinant of A. If det A = 0 then 0 is in the denominator to calculate A-1. Therefore A-1 is not defined when det A = 0.

We can check the determinant of a matrix using the det() function:


We can see that the determinant of the matrix is zero, which is why we encountered the error.


We can solve the error by choosing a matrix that is not singular. The two ways to check if a matrix is singular are if it is a square matrix and its determinant is 0. Let’s look at the revised code:

mat <- matrix(c(1, 3, 3, 4, 12, 6, 7, 2, 9), ncol=3, nrow=3)

Let’s run the code to see the updated matrix:

     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    3   12    2
[3,]    3    6    9

Let’s check the determinant of the matrix:

[1] -114

We have a defined determinant for the matrix. Therefore we can find its inverse using the solve() function as follows.

          [,1]        [,2]       [,3]
[1,] -0.8421053 -0.05263158  0.6666667
[2,]  0.1842105  0.10526316 -0.1666667
[3,]  0.1578947 -0.05263158  0.0000000


Congratulations on reading to the end of this tutorial!

For further reading on R-related errors, go to the articles: 

Go to the online courses page on R to learn more about coding in R for data science and machine learning.

Have fun and happy researching!