필터 지우기
필터 지우기

Change all but one value to one at random within rows

조회 수: 3 (최근 30일)
J T
J T 2016년 11월 8일
댓글: J T 2016년 11월 8일
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에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by