Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab, Integer vector to binary matrix without loop [duplicate]

Tags:

matrix

matlab

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?

like image 940
Zeta Two Avatar asked Nov 14 '11 03:11

Zeta Two


2 Answers

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;
like image 94
Jonas Avatar answered Oct 13 '22 12:10

Jonas


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
like image 40
Sam Roberts Avatar answered Oct 13 '22 13:10

Sam Roberts