Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate boolean matrix by predicate on row and column

I have the following vector:

y = [1; 3; 2; 3; 1];

All its values are between 1 and n (in this case, 3) and denote different options.

I want to create a matrix of size size(y, 1) x n whose rows correpond to y values:

1 0 0 % because y(1) = 1
0 0 1 % because y(2) = 3
0 1 0 % because y(3) = 2
0 0 1
1 0 0

One way to do this would be

Y = zeros(size(y, 1), num_labels);
for i = 1:m
    Y(i, y(i)) = 1;
end

Is there a better way to do this, maybe in a single expression?
Basically, what I need is to generate a matrix with boolean predicate (i, j) => j == y(i).

like image 281
Dan Abramov Avatar asked Nov 30 '22 23:11

Dan Abramov


2 Answers

You can try this if a is a column vector

a =  [1; 3; 2; 3; 1];

bsxfun(@eq, a, [1:max(a)]) 

and this if it is a row vector

a =  [1; 3; 2; 3; 1]';

bsxfun(@eq, a', [1:max(a)]) 
like image 189
H.Muster Avatar answered Dec 04 '22 13:12

H.Muster


If you have access to Statistics Toolbox, the command dummyvar does exactly what you need.

>> y = [1; 3; 2; 3; 1];
>> dummyvar(y)
ans =
     1     0     0
     0     0     1
     0     1     0
     0     0     1
     1     0     0
like image 40
Sam Roberts Avatar answered Dec 04 '22 13:12

Sam Roberts