How do I select a single, random, non-zero array from a matrix?

I have a matrix consisting of an equal amount of ones and zeros, randomly distributed. I want a random one to change into a zero, and a random zero to change into a one, so in the end I always end up with the same amount of ones and zeros.
How do I accomplish this? Thanks in advance,
Chris

 채택된 답변

the cyclist
the cyclist 2015년 12월 20일
There are almost certainly ways to make this more efficient, but here is a conceptually straightforward way to do this:
% Starting matrix
M = [ 0 1 0;
1 0 1;
0 1 0;
1 0 1];
numberElements = numel(M);
% You can run the following as many times as you want,
% to change a pair of 0/1.
indexToOnes = find(M);
indexToZeros = setxor(indexToOnes,1:numberElements);
indexChangeToZero = indexToOnes(randi(numel(indexToOnes)));
indexChangeToOne = indexToZeros(randi(numel(indexToZeros)));
M(indexChangeToZero) = 0;
M(indexChangeToOne) = 1;

추가 답변 (1개)

John D'Errico
John D'Errico 2015년 12월 20일
A = rand(5,5) > 0.5
A =
1 0 0 0 0
1 0 0 1 1
0 1 1 1 0
1 1 1 0 1
0 0 1 0 0
takejustone = @(x) x(ceil(numel(x)*rand(1)));
i1 = takejustone(find(A));
i0 = takejustone(find(~A));
A([i1,i0]) = ~A([i1,i0])
A =
1 0 0 0 0
1 1 0 1 1
0 1 1 0 0
1 1 1 0 1
0 0 1 0 0
So i swapped the (2,2) element from a 1 into a 0, and the (3,4) element went from a 0 into a 1.

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

질문:

2015년 12월 20일

댓글:

2015년 12월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by