1

y is a column vector with integer values denote label number (say between 1-3). Now I need to create a matrix with same number of row of y. Each row i is now a vector with the y(i) positioned element to be 1 and the others to be 0.

Example:

y = [3, 2, 2]';

x = [0,0,1;
     0,1,0;
     0,1,0];

Is there an efficient way to finish this job. I know a for loop will do:

x = zeros(size(y, 1), 3)
for i = 1:size(y, 1)
    x(i, y(i)) = 1
end
Suever
  • 64,497
  • 14
  • 82
  • 101
Paul Stein
  • 55
  • 6
  • Here's an exact duplicate : http://stackoverflow.com/questions/23078287/create-a-zeros-filled-2d-array-with-ones-at-positions-indexed-by-a-vector – Divakar Jun 14 '16 at 17:50
  • @Divakar Wow hadn't seen that dupe before. I like the `sparse` solution in there. Very clever. – Suever Jun 14 '16 at 17:52
  • Yeah, as it turns out, we had a chain of dups on this particular problem. If I remember correctly, that sparse was the most efficient. – Divakar Jun 14 '16 at 17:53

1 Answers1

3

You can easily do this with sub2ind which converts subscripts to linear indices. Your row subscripts are 1:numel(y) and your column subscripts are the values of y.

x = zeros(numel(y), max(y));
x(sub2ind(size(x), 1:numel(y), y(:).')) = 1;

Or you can simply do this with a little index math.

x = zeros(numel(y), max(y));
x(((y(:).' - 1) * numel(y)) + (1:numel(y))) = 1;
Suever
  • 64,497
  • 14
  • 82
  • 101