Randomly generate a matrix of zeros and ones with a non-uniform bias

62 ビュー (過去 30 日間)
Nurul
Nurul 2011 年 2 月 11 日
コメント済み: Jack Nelson 2020 年 5 月 13 日
Can anyone help me to generate a matrix of zeros and ones randomly without uniformly distributing like the function of "randint". Instead with the number of ones must be larger than zeros in an array.
For example, a matrix like this:
A= [ 1 1 1 1 0 1 0, 1 0 1 1 1 1 1, 1 1 0 1 1 0 0]

採用された回答

Matt Fig
Matt Fig 2011 年 2 月 11 日
Like this?
A = rand(1,21)>.3 % Increase number for less ones, decrease for more.
  2 件のコメント
Nurul
Nurul 2011 年 2 月 16 日
Hi Matt, for the time being, i'm using your solution as it could give the ones more than zeros.
Jack Nelson
Jack Nelson 2020 年 5 月 13 日
Thanks! :)

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

その他の回答 (3 件)

Jos (10584)
Jos (10584) 2011 年 2 月 11 日
The following gives you a matrix with exactly a certain number of 1's
sizeR = [3 4] ;
num1 = 8 ;
R = zeros(sizeR) % set all to zero
ix = randperm(numel(R)) % randomize the linear indices
ix = ix(1:num1) % select the first
R(ix) = 1 % set the corresponding positions to 1
By the way, if the only values in R are 0 and 1 than logical arrays may be worthwhile to explore, as they are less memory consuming than double arrays.
  7 件のコメント
Nima Mahanfar
Nima Mahanfar 2015 年 6 月 17 日
Thanks, this was very helpful. Is there a way to make these ones being adjacent elements? example for 6x3 matrix with two 1's: [1 1 0 0 0 0; 0 0 0 0 0 0; 0 0 0 0 0 0]
Nima Mahanfar
Nima Mahanfar 2015 年 6 月 17 日
Thanks, this was very helpful. Is there a way to make these ones being adjacent elements? example for 6x3 matrix with two 1's: [1 1 0 0 0 0; 0 0 0 0 0 0; 0 0 0 0 0 0]

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


Walter Roberson
Walter Roberson 2011 年 2 月 11 日
0 + (rand(7,3) > 0.4)
  1 件のコメント
Bruno Luong
Bruno Luong 2011 年 2 月 11 日
Not that matter, but in light of the recent discussion, in order to generate a 0.4 probability of zeros, the more accurate RAND() cut is:
s = 2^(-53)
cut = 0.4*(1-s)+s/2
r = rand > cut

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


Nurul
Nurul 2011 年 2 月 11 日
Thanks for your help. Its helped me a lot.
  1 件のコメント
Ned Gulley
Ned Gulley 2011 年 2 月 11 日
Nurul, the best thanks is to accept one of the answers.

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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by