Change all but one value to one at random within rows

1 次查看(过去 30 天)
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.

采纳的回答

Robert
Robert 2016-11-8
% 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;

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by