フィルターのクリア

Replace elements in a row matrix randomly

2 ビュー (過去 30 日間)
Konstantinos
Konstantinos 2015 年 2 月 3 日
コメント済み: Star Strider 2015 年 2 月 3 日
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 件のコメント
Konstantinos
Konstantinos 2015 年 2 月 3 日
Thanks a lot!

サインインしてコメントする。

その他の回答 (1 件)

Michael Haderlein
Michael Haderlein 2015 年 2 月 3 日
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
Michael Haderlein 2015 年 2 月 3 日
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 Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by