MATLAB: Change all but one value to one at random within rows

matricesrandom reassignment of ones to zeros

Suppose I have the following matrix
[ 1 0 1 1 0; 0 1 1 0 0; 1 1 1 0 0; 0 0 0 0 0 ; 0 1 0 0 0]
If a particular row contains two or more ones, I want to change all but one of them to zero
I need the choice to be a random. Thus when implemented, the matrix might become
[ 0 0 0 1 0; 0 1 0 0 0; 1 0 0 0 0; 0 0 0 0 0 ; 0 1 0 0 0]
and a subsequent time
[ 1 0 0 0 0; 0 0 1 0 0; 1 0 0 0 0; 0 0 0 0 0 ; 0 1 0 0 0]
These matrices are large (maybe 2e6 by 10) and speed is an issue. Any help greatly appreciated.

Best Answer

% locate all rows and columns with ones
[a,b] = find(x);
% randomize the order of the rows and keep the column indices aligned
ii = randperm(length(a));
a = a(ii);
b = b(ii);
% keep only the first instance of a row
[a,ii] = unique(a);
b = b(ii);
% assign the ones to our output
if islogical(x)
y = false(size(x));
else
y = zeros(size(x),'like',x);
end
ii = sub2ind(size(x),a,b);
y(ii) = 1;
Related Question