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.
0 件のコメント
採用された回答
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 Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!