Replace elements in a row matrix randomly

2 次查看(过去 30 天)
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 个评论
Star Strider
Star Strider 2015-2-3
‘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.)

请先登录,再进行评论。

采纳的回答

Guillaume
Guillaume 2015-2-3
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.

更多回答(1 个)

Michael Haderlein
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 个评论
Konstantinos
Konstantinos 2015-2-3
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
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).

请先登录,再进行评论。

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by