How can I do one-hot encoding in MATLAB?

I would like to perform one-hot encoding on the vector [1 7 10 9 8 6]' with 10 classes (numbers 1 to 10). The resulting 6x10 matrix should have a 1x10 vector in place of each number, with "1" at the position corresponding to the number and "0" at all other positions.

 Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 13 de Sept. de 2024
Editada: MathWorks Support Team el 13 de Sept. de 2024
This can be done by using a logical operator '==' as follows:
>> vec = [1 7 10 9 8 6]'; % Create the vector>> A = (vec==1:10) % Find the column that corresponds to each vector entry
A = 6×10 logical array 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0
You can learn more about the operator here:

Más respuestas (1)

Jon Cherrie
Jon Cherrie el 13 de Feb. de 2026
The function onhotencode will do this for you, e.g.,
x = [1 7 10 9 8 6]' ;
classes = 1:10;
y = onehotencode(x,2,"double",ClassNames=classes)
You can use onehotdecode for the reverse operation, which will also work on probability vectors, not just vectors of 1s and 0s

Categorías

Más información sobre Deep Learning Toolbox en Centro de ayuda y File Exchange.

Productos

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by