MATLAB: Creating a matrix of ones and zeros with location of ones based on array value

indexMATLAB

I need to acheive the following without a loop (for speed):
I have a vertical array where the value of each row tells me which column in a matrix of zeros should be replaced with a one.
For example, if I input:
y = [2; 3];
Then I want MATLAB to produce output:
Y = [0,1,0; 0, 0, 1];
I can acheive the desired output with the following for loop:
Y = zeros(2,3);
for j = 1:3
Y(:,j) = (y==j);
end
In reality, my matrices are much larger and I want to avoid using for loops for speed. Is there anyway I can do this without a for loop?

Best Answer

One possible way is:
Y = zeros(length(y), max(y));
Y(sub2ind(size(Y), (1:length(y))', y)) = 1;