Create a zero-filled 2D array with ones at positions indexed by a vector
Yet another approach:
yvec = full(sparse(1:numel(y),y,1));
Two approaches you can use here.
Approach 1:
y = [1; 3; 2; 1; 3];
yvec = zeros(numel(y),3);
yvec(sub2ind(size(yvec),1:numel(y),y'))=1
Approach 2 (One-liner):
yvec = bsxfun(@eq, 1:3,y)
You could do this with accumarray
:
yvec = accumarray([(1:numel(y)).' y], 1);