Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab/Octave 1-of-K representation

I have a y of size 5000,1 (matrix), which contains integers between 1 and 10. I want to expand those indices into a 1-of-10 vector. I.e., y contains 1,2,3... and I want it to "expand" to:

1 0 0 0 0 0 0 0 0 0 
0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0 

What is the best way to do that?

I tried:

Y = zeros(5000,10); Y(y) = 1; 

but it didn't work.

It works for vectors though:

if y = [2 5 7], and Y = zeros(1,10), then Y(y) = [0 1 0 0 1 0 1 0 0 0].

like image 874
Frank Avatar asked Nov 08 '11 17:11

Frank


2 Answers

Consider the following:

y = randi([1 10],[5 1]);       %# vector of 5 numbers in the range [1,10]
yy = bsxfun(@eq, y, 1:10)';    %# 1-of-10 encoding

Example:

>> y'
ans =
     8     8     4     7     2
>> yy
yy =
     0     0     0     0     0
     0     0     0     0     1
     0     0     0     0     0
     0     0     1     0     0
     0     0     0     0     0
     0     0     0     0     0
     0     0     0     1     0
     1     1     0     0     0
     0     0     0     0     0
     0     0     0     0     0
like image 64
Amro Avatar answered Sep 20 '22 12:09

Amro


n=5
Y = ceil(10*rand(n,1))
Yexp = zeros(n,10);
Yexp(sub2ind(size(Yexp),1:n,Y')) = 1

Also, consider using sparse, as in: Creating Indicator Matrix.

like image 24
cyborg Avatar answered Sep 21 '22 12:09

cyborg