MATLAB: How to replace multiple indices of a matrix with a specific value

MATLABmatrix manipulation

I have a zeros matrix "Y" with dimensions 10×5000:
Y = zeros(10,5000);
And an indices vector "y" with length 1×5000 that indicates, for each column of matrix Y, which row should have a value of 1 while keeping all other rows for that column at 0.
For instance, if the first element of y is 3, that means that the first column of Y should be:
Y(:,1) = [0;0;1;0;0;0;0;0;0;0];
In other words, the first element of vector "y" dictates what row of the first column in matrix Y should be set to 1.
Given that I have this index vector, is there a way I can efficiently set the elements of Y to 1 without using a for loop? Something like Y(y) = 1

Best Answer

I would probably first try to use linear indexing. The function to use here is sub2ind. I'd try something like this.
lInd = sub2ind(size(Y),y,1:length(y))
You can then use the linear index to change the corresponding values in Y to 1.
Y(lInd)=1;
If I test this with a much shorter example, this is the result
Y=zeros(10,4);
y=[3 1 6 9];
lInd = sub2ind(size(Y),y,1:length(y))
Y(lInd)=1
Y =
0 1 0 0
0 0 0 0
1 0 0 0
0 0 0 0
0 0 0 0
0 0 1 0
0 0 0 0
0 0 0 0
0 0 0 1
0 0 0 0