Asked by MathWorks Support Team
on 1 May 2017

I want to make a plot similar to the confusion matrix created in the Classification Learner app. This can make a confusion matrix for a multi-class or non-binary classification problem. In addition, it can plot things such as a True Positive or False Negative rates.

How can I do this?

Answer by MathWorks Support Team
on 5 Jul 2017

Accepted Answer

Similar to the binary or two-class problem, this can be done using the "plotconfusion" function. By default, this command will also plot the True Positive, False Negative, Positive Predictive, and False Discovery rates in they grey-colored boxes. Please refer to the following example:

targetsVector = [1 2 1 1 3 2]; % True classes

outputsVector = [1 3 1 2 3 1]; % Predicted classes

% Convert this data to a [numClasses x 6] matrix

targets = zeros(3,6);

outputs = zeros(3,6);

targetsIdx = sub2ind(size(targets), targetsVector, 1:6);

outputsIdx = sub2ind(size(outputs), outputsVector, 1:6);

targets(targetsIdx) = 1;

outputs(outputsIdx) = 1;

% Plot the confusion matrix for a 3-class problem

plotconfusion(targets,outputs)

The class labels can be customized by setting that 'XTickLabel' and 'YTickLabel' properties of the axis:

h = gca;

h.XTickLabel = {'Class A','Class B','Class C',''};

h.YTickLabel = {'Class A','Class B','Class C',''};

h.YTickLabelRotation = 90;

Answer by David Franco
on 23 Jan 2018

Edited by MathWorks Support Team
on 16 Mar 2018

Implementation code:

Confusion Matrix

function [] = confusion_matrix(T,Y)

M = size(unique(T),2);

N = size(T,2);

targets = zeros(M,N);

outputs = zeros(M,N);

targetsIdx = sub2ind(size(targets), T, 1:N);

outputsIdx = sub2ind(size(outputs), Y, 1:N);

targets(targetsIdx) = 1;

outputs(outputsIdx) = 1;

% Plot the confusion matrix

plotconfusion(targets,outputs)

Anmol Pardeshi
on 30 Nov 2018

MA-Winlab
on 17 Apr 2019

what are T and Y?

is plotconfusion(targets,outputs) part of the function?

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 3 Comments

## tejasvee (view profile)

Direct link to this comment:https://www.mathworks.com/matlabcentral/answers/338244-how-can-i-plot-a-confusion-matrix-for-a-multi-class-or-non-binary-classification-problem#comment_462256

## Ivan Abraham (view profile)

Direct link to this comment:https://www.mathworks.com/matlabcentral/answers/338244-how-can-i-plot-a-confusion-matrix-for-a-multi-class-or-non-binary-classification-problem#comment_463323

## Michael Abboud (view profile)

Direct link to this comment:https://www.mathworks.com/matlabcentral/answers/338244-how-can-i-plot-a-confusion-matrix-for-a-multi-class-or-non-binary-classification-problem#comment_467069

Sign in to comment.