MATLAB: Select and remove/replace values in matrix

repetitive

My question is to check each row for the same numbers (in this case 1 or 0, we leave the 0s unchanged in the matrix), and replace any 1 in the row with 0 except the last value of 1
Y = [0 1 1 0 1 0;
0 0 0 1 0 1;
1 0 1 0 1 0; ]
The end result I should get is
X = [0 0 0 0 1 0;
0 0 0 0 0 1;
0 0 0 0 1 0;]
Another similar question would be to remover the first/second (sometimes even third) number in the row leaving the last 2 numbers unchanged.
Y = [1 2 4 0 0 0;
2 5 0 0 0 0;
3 4 5 6 0 0;]
The end result I should get is
X = [0 2 4 0 0 0;
2 5 0 0 0 0;
0 0 5 6 0 0;]

Best Answer

One way:
nelems = 2; %number of elements to keep
X = (cumsum(Y>0, 2, 'reverse') < nelems+1) .* Y