Determinant of a 3x3 matrix

We can find the determinant of any matrix through Laplace Expansion. We will be using this method to find the determinant of 3 X 3 and higher order matrices. We also used this method to find the determinant of 2 X 2 matrices; we just expanded the method by hand for that function to avoid looping:

Determinant of a 3x3 matrix

To follow the formula, we loop through the first row of the matrix and multiply each element with the respective element of the cofactor matrix. Then, we sum up the result of each multiplication. The resulting sum is the determinant of the matrix.

Using the first row is an arbitrary choice. You can do this equation on any row of the matrix and get the same result.

Getting ready

In order to implement this in code, first find the cofactor of the input matrix. Once we have a cofactor matrix, sum the result of looping through the first row and multiply each element by the same element in the cofactor matrix.

How to do it…

Follow these steps to implement a function which returns the determinant of a 3 X 3 matrix:

  1. Add the declaration of the 3 X 3 determinant function to matrices.h:
    float Determinant(const mat3& mat);
  2. Implement the 3 X 3 determinant function in matrices.cpp:
    float Determinant(const mat3& mat) {
        float result = 0.0f;
        mat3 cofactor = Cofactor(mat);
        for (int j = 0; j < 3; ++j) {
           int index = 3 * 0 + j;
           result += mat.asArray[index] * cofactor[0][j];
        }
        return result;
    }

How it works…

Let's explore how Laplace Expansion works by following it through on the matrix M:

How it works…

For every element in the first row, we eliminate the row and column of the element. This will leave us with a 2 X 2 matrix for each element:

How it works…

We then multiply each element by the cofactor of the resulting 2 X 2 matrix. The cofactor is the determinant of the 2 X 2 matrix, multiplied by How it works…, where i is the row of the element and j is the column of the element. Summing up the results of these multiplications yields the determinant of the matrix:

How it works…

We can simplify the preceding equation to the final 3 X 3 determinant formula:

How it works…