Random but equal distribution of numbers 1 and 2

10 ビュー (過去 30 日間)
Happy Bear
Happy Bear 2020 年 1 月 30 日
コメント済み: Happy Bear 2020 年 2 月 1 日
Hello,
I need to get some kind of matrix or array with the numbers 1 and 2 randomly distributed, but I need the number of "ones" to be the same as the number of "twos".
Therefore, I applied the randsrc function, with 50% probability for number 1 and 50% probability for number 2.
However, when I run this, sometimes I do get what I want ([1,2,2,1] or [2,1,2,1], e.g.) but many times it is wrong (e.g., [1,1,1,2] or [2,2,2,2]).
The size doesn't necessarily need to be 1x4, I'm doing that for now but it will be 1x50 once I get it to work.
Anyone knows why this is not working, what am I doing wrong or has any other idea for how to do this?
a = randsrc(1,4,[1 2;0.5 0.5]);

採用された回答

Steven Lord
Steven Lord 2020 年 1 月 30 日
Do you need exactly equal numbers of 1's and 2's or just a vector where each element has an equal probability of being 1 or 2?
If the latter, you could use randi or randsrc.
If the former, start off with a vector with an equal number of 1's and 2's and shuffle it with randperm.
n = 10;
v = [ones(n, 1); 2*ones(n, 1)];
vshuffle = v(randperm(2*n));
% Display them side by side
[v, vshuffle]
  1 件のコメント
Happy Bear
Happy Bear 2020 年 2 月 1 日
Thank you so much, that's exactly it.

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

その他の回答 (1 件)

Mohammad Sami
Mohammad Sami 2020 年 1 月 30 日
You can try this
l = 50
a = rand(l,1);
a = (a > median(a)) + 1;
  3 件のコメント
Mohammad Sami
Mohammad Sami 2020 年 1 月 30 日
Use Steven's solution. it would be safer.
Happy Bear
Happy Bear 2020 年 2 月 1 日
Okay, got it, thank you.

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

カテゴリ

Help Center および File ExchangeRandom Number Generation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by