如何生成在此范围内的随机数?

时间:2019-11-06 05:55:32

标签: matlab random

我想生成一些随机数,用于这种分布:

  • 其中10%位于A类(T = 6),
  • 其中40%位于B类(T = 8),
  • 其中40%位于C类(T = 10),
  • 其中10%属于D类(T = 12)。

我刚刚开始学习MATLAB,尝试过rand(x)randn(x),但似乎他们俩都做不到?

1 个答案:

答案 0 :(得分:1)

您必须设置从rand得到的均匀分布的随机数到所需值(即相对于所需分布)的某种映射。

在我的解决方案中,我使用rand生成随机数,并将它们映射到整数1234以及(分类)字符ABCD。我构建了一个完整的函数来支持可变数量的输入参数,以模仿rand的行为。

这是myRand函数的代码:

function [rn, in, ch] = myRand(varargin)

  % No input arguments.
  if (numel(varargin) == 0)  
    rn = rand();

  % One input argument; might be a scalar or an array.
  elseif (numel(varargin) == 1)
    a = varargin{1};
    if (!isnumeric(a))
      error('myRand: argument must be numeric');
    end
    rn = rand(a);

  % More than one input argument; must be scalars.
  elseif (numel(varargin) > 1)
    if (!all(cellfun(@(x)isnumeric(x), varargin)))
      error('myRand: arguments must be numeric');  
    end
    if (!all(cellfun(@(x)isscalar(x), varargin)))
      error('myRand: arguments must be scalar');  
    end
    rn = rand(varargin{:});

  end

  in = zeros(size(rn));
  in((0 <= rn) & (rn < 0.1)) = 1;
  in((0.1 <= rn) & (rn < 0.5)) = 2;
  in((0.5 <= rn) & (rn < 0.9)) = 3;
  in((0.9 <= rn) & (rn < 1)) = 4;

  ch = cell(size(rn));  
  ch((0 <= rn) & (rn < 0.1)) = { 'A' };
  ch((0.1 <= rn) & (rn < 0.5)) = { 'B' };
  ch((0.5 <= rn) & (rn < 0.9)) = { 'C' };
  ch((0.9 <= rn) & (rn < 1)) = { 'D' };

end

而且,这是一些带有相应输出的测试代码:

% Single random number with integer and category
[rn, in, ch] = myRand()

% Multiple random numbers with integers and categories (array input)
[rn, in, ch] = myRand([2, 3])

% Multiple random numbers with integers and categories (multiple scalars input)
[rn, in, ch] = myRand(2, 3)


rn =  0.19904
in =  2
ch =
{
  [1,1] = B
}

rn =
   0.206294   0.420426   0.835194
   0.793874   0.593371   0.034055

in =
   2   2   3
   3   3   1

ch =
{
  [1,1] = B
  [2,1] = C
  [1,2] = B
  [2,2] = C
  [1,3] = C
  [2,3] = A
}

rn =
   0.96223   0.87840   0.49925
   0.54890   0.88436   0.92096

in =
   4   3   2
   3   3   4

ch =
{
  [1,1] = D
  [2,1] = C
  [1,2] = C
  [2,2] = C
  [1,3] = B
  [2,3] = D
}

希望有帮助!

免责声明:我使用Octave 5.1.0测试了代码,但是我很确定,它应该与MATLAB完全兼容。如果没有,请发表评论,我将尝试解决可能的问题。