Skip to content

Instantly share code, notes, and snippets.

@zygmuntz
Created October 11, 2013 18:31
Show Gist options
  • Save zygmuntz/6939718 to your computer and use it in GitHub Desktop.
Save zygmuntz/6939718 to your computer and use it in GitHub Desktop.
One way of doing one-hot encoding in Matlab
% y is a vector of labels
y_one_hot = zeros( size( y, 1 ), n_classes );
% assuming class labels start from one
for i = 1:n_classes
rows = y == i;
y_one_hot( rows, i ) = 1;
end
@4u9u5tsong
Copy link

y_one_hot = ind2vec(y')'; // matlab has this built-in function

@JamesOwers
Copy link

Allowing all values in y (above doesn't work if any y is zero or negative):

[~, loc] = ismember(y, unique(y));
y_one_hot = ind2vec(loc')';

This is nice as it also works for cell strings:

ystr = cellstr(char('hey', 'hey', 'gurl', 'hey'));
[~, loc] = ismember(ystr, unique(ystr));
y_one_hot = ind2vec(loc')';
array2table(full(y_one_hot), 'VariableNames', unique(ystr))

@kanginthaya
Copy link

y_one_hot = ind2vec(y')'; // matlab has this built-in function

y_one_hot = full(ind2vec(y',num_classes)) is a clean way to do this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment