Create a zero-filled 2D array with ones at positions indexed by a vector
问题 I'm trying to vectorize the following MATLAB operation: Given a column vector with indexes, I want a matrix with the same number of rows of the column and a fixed number of columns. The matrix is initialized with zeroes and contains ones in the locations specified by the indexes. Here is an example of the script I've already written: y = [1; 3; 2; 1; 3]; m = size(y, 1); % For loop yvec = zeros(m, 3); for i=1:m yvec(i, y(i)) = 1; end The desired result is: yvec = 1 0 0 0 0 1 0 1 0 1 0 0 0 0 1