Replace elements in a row matrix randomly

9 views (last 30 days)
I have a raw matrix (1x8), which is generated randomly each time and it consists of 1s and 0s. I want to produce 3 1s each time and 5 0s. If there are less than 3 1s I want to randomly replace 0s with 1s until the number on 1s is 3. Suppose that I don't know the location of its element.
i.e : Α = [ 1 0 0 1 0 0 0 0 ]
Then the modified matrix A could be : [ 1 0 0 1 0 0 1 0 ]
0s have to be randomly replaced when needed and not to choose that with the lower index, in the matrix, to be replaced.
Any help could be useful. Thanks in advance!
  1 Comment
Star Strider
Star Strider on 3 Feb 2015
‘Suppose that I don't know the location of its element.’
I didn’t use find in my code because I though knowing the locations of the 1s was not an option. (I deleted my Answer.)

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 3 Feb 2015
How about:
zeroidx = find(~A); %find position ot 0s
replaceidx = zeroidx(randperm(numel(zeroidx), 3-sum(A))); select random 0s to replace
A(replaceidx) = 1;
This assumes there's never more than three 1 in A, which I think is your case since you never mention replace 1 with 0.

More Answers (1)

Michael Haderlein
Michael Haderlein on 3 Feb 2015
Is your specific algorithm necessary? I mean, that you first start with a random A and then add 1s until the condition is met? I'm asking because there's a more efficient way to do it.
It's always exactly 3 1s and 5 0s, right? Then, make it all zeros and then add some 1s:
A=zeros(1,8);
r=rand(1,8);
[~,ind]=sort(r);
A(ind(1:3))=1;
If you insist on your algorithm, I'd just create a while loop (while sum(A)<3) and then randomly put one value to 1:
A=zeros(1,8);
while sum(A)<3
A(randi([1 8]))=1;
end
  2 Comments
Konstantinos
Konstantinos on 3 Feb 2015
Your second code seems to be correct for my case. But there is a chance that the 1 could replace another 1. So the number of 1s will remain 2.
Michael Haderlein
Michael Haderlein on 3 Feb 2015
That's possible, correct. But that just increases the number of loop iterations. The result will still have 3 1s. But I cannot see the benefit of this code compared to my first suggestion and to Star Strider's first code. In any case you'll get exactly 3 1s and the looping codes are most likely much more inefficient than the other ones (e.g. due to replacement of 1 by 1 = non productive iteration).

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!