MATLAB: How to do one-hot encoding in MATLAB

01correspondingencodinghotMATLABnumberone

Best Answer

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: