I have a vector with N elements, all integers 1-M. I want to convert this to a NxM matrix with each row containing only zeros except for the i:th element set to one, i being the integer in the vector.
For example: [1 1 3] => [1 0 0; 1 0 0; 0 0 1]
I currently do this in a loop, like this:
y_vec = zeros(m, num_labels);
for i = 1:m
y_vec(i, y(i)) = 1;
end
Is there a way to do this without a loop?
Yes, there is:
y = [1 1 3];
m = length(y);
num_labels = max(y);
%# initialize y_vec
y_vec = zeros(m,num_labels);
%# create a linear index from {row,y}
idx = sub2ind(size(y_vec),1:m,y);
%# set the proper elements of y_vec to 1
y_vec(idx) = 1;
If you have access to Statistics Toolbox, the command dummyvar
does exactly this.
>> dummyvar([1 1 3])
ans =
1 0 0
1 0 0
0 0 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With