【问题标题】:How do I generate random numbers in such range? [duplicate]如何在这样的范围内生成随机数? [复制]
【发布时间】:2020-03-02 13:36:05
【问题描述】:

我想生成一些随机数,就是为了这样的分布:

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

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

【问题讨论】:

  • 我相信链接的问题是重复的,为您的问题提供了多种解决方案。如果您认为情况并非如此,请说明原因。
  • 我认为this thread 比@LuisMendo 提供了比currently linked dupe target 更好的答案。
  • @SecretAgentMan:添加了那个骗子。

标签: matlab random


【解决方案1】:

您必须设置某种映射,将从您从 rand 获得的均匀分布的随机数映射到您想要的值,即相对于想要的分布。

在我的解决方案中,我使用rand 生成随机数,并将它们映射到整数1234 以及(分类)字符A、@987654329 @、CD。我构建了一个完整的函数来支持可变数量的输入参数来模仿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 完全兼容。如果没有,请发表评论,我会尽力解决可能的问题。

【讨论】:

  • 非常感谢!我在 MATLAB 中尝试过,错误发生在 'ch((0
  • @Bobet 我编辑了我的答案,请再试一次。这些字符现在被明确地放入一个单元格中。
猜你喜欢
  • 1970-01-01
  • 2011-03-01
  • 1970-01-01
  • 2017-11-06
  • 2011-08-27
  • 1970-01-01
  • 2021-03-08
  • 2013-12-02
相关资源
最近更新 更多