Change all but one value to one at random within rows
1 view (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Robert
on 8 Nov 2016
% 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;
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!