How to make a confusion matrix in MATLAB

A confusion matrix is a useful tool for evaluating the performance of a classification algorithm. In MATLAB, we can create a confusion matrix using the confusionmat() function.

Syntax

C = confusionmat(target,output)

The code above will take the following parameters:

  • target is a vector of true class labels.
  • output is a vector of predicted class labels.

Example code

Here’s an example of how to use the confusionmat() function:

// Example ground truth and predicted labels
groundTruth = [1 1 0 1 0 0 1 0 1 0];
predictedLabels = [1 0 1 1 0 1 0 1 1 0];
// Create confusion matrix
C = confusionmat(groundTruth, predictedLabels)
// Visualize confusion matrix
confusionchart(C)

Explanation

In the example code above, we have ground truth labels in the groundTruth variable and predicted labels in the predictedLabels variable. We use these two variables as input to the confusionmat() function to create a confusion matrix. To visualize the confusion matrix, we can use the confusionchart() function, which creates a heatmap of the confusion matrix.

Code output

This will output the following confusion matrix:

       True   False
 True    3      3
 False   2      2

The output of the confusionmat() function is a 2x2 matrix C, where each row corresponds to the actual class and each column corresponds to the predicted class. The diagonal elements of the matrix represent the number of correctly classified samples, while the off-diagonal elements represent the number of misclassified samples.

Example with three classes

// Example ground truth and predicted labels for three classes
groundTruth = [1 2 3 1 2 3 1 2 3];
predictedLabels = [1 2 3 2 1 3 3 2 1];
// Create confusion matrix
C = confusionmat(groundTruth, predictedLabels)
// Visualize confusion matrix
labels = {'Class 1', 'Class 2', 'Class 3'};
confusionchart(C, labels)

Explanation

In this example, we have ground truth and predicted labels for three classes. We create the confusion matrix using the confusionmat() function and then visualize it using the confusionchart() function, specifying the class labels.

Code output

This will output the following confusion matrix:

 C =
     1     1     1
     1     2     0
     1     0     2

The confusion matrix is displayed as a 3x3 matrix, where the rows represent the true classes (ground truth) and the columns represent the predicted classes. For example, the value at C(1,1) represents the number of instances where the true class is 1 and it was correctly predicted as class 1 (true positive). Similarly, the value at C(2,3) represents the number of instances where the true class is 2, but it was incorrectly predicted as class 3 (false negative).

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved