在Matlab中使用偏差分配有符号整数

时间:2018-06-04 13:52:25

标签: matlab random

以下示例代码在-1,+1

大小的数组中随机分配N的值
N=100;    
D = sign(rand(1,N)-0.5).*ones(1,N);

如何控制数字分布中的偏差水平?

让我们举例说,只有20%的数组会有+1,其余的-1

2 个答案:

答案 0 :(得分:1)

如何在50%(0.5)的数字为负数的情况下进行分配?

N=100;    
D = sign(rand(1,N)-0.5).*ones(1,N);

如何在20%(0.2)的数字为负数的情况下进行分配?

N=100;    
D = sign(rand(1,N)-0.2).*ones(1,N);

如何在80%(0.8)的数字为负数的情况下进行分配?

答案 1 :(得分:1)

如下所示

VAL = [-1 1]   % 2 values
P = .8          % probabbility of selecting first value
Ndraw = 100      % number of draws
R = rand(Ndraw,1) < P 
SEL = VAL(2 - R) % use as index into VAL

    SEL =

  Columns 1 through 19

     1    -1    -1     1    -1    -1     1    -1    -1    -1    -1    -1    -1    -1    -1    -1    -1    -1    -1

  Columns 20 through 38

    -1     1     1    -1    -1    -1     1    -1     1    -1    -1    -1    -1    -1    -1    -1    -1    -1    -1

  Columns 39 through 57

    -1    -1    -1    -1    -1    -1    -1    -1     1    -1     1    -1     1     1     1    -1    -1    -1    -1

  Columns 58 through 76

    -1    -1    -1    -1     1    -1    -1    -1    -1    -1     1    -1    -1    -1    -1    -1    -1     1     1

  Columns 77 through 95

    -1    -1     1    -1    -1     1    -1    -1    -1    -1     1    -1    -1    -1    -1     1    -1     1    -1

  Columns 96 through 100

    -1     1    -1    -1    -1