【问题标题】:What is the difference between randi(x,y,1) and randsample(x,y,true)?randi(x,y,1) 和 randsample(x,y,true) 有什么区别?
【发布时间】:2017-11-14 17:15:40
【问题描述】:

我通常使用randsample,但是我遇到了randi,我想知道有什么不同。

例如,这些似乎都是从 [1,10] 中选择随机数并返回一个 10 x 1 向量:

n = randi(10,10,1);
n2 = randsample(10,10,true);

这两行代码有什么区别?

【问题讨论】:

  • 他们给出相同的结果。大概randi会快一点
  • 为什么兰迪可能更快?
  • 因为randsample是用Matlab写的,而randi是内置函数
  • randsample 在其中使用 randi 以及其他内容
  • 如果 Levenshtein 距离是“差异”的有效度量,则为 11

标签: matlab function random built-in


【解决方案1】:

让我们考虑两个来源:

  1. randsample 的文档,我们在其中看到:

    y = randsample(s,...) 使用流s 生成随机数。 sRandStream 类的成员。默认为 MATLAB® 默认随机数流。

  2. randsampleCopyright 1993-2010 The MathWorks, Inc.)的源代码我们发现当第三个输入为true时的情况如下:

    % Sample with replacement
    case {true, 'true', 1}
        if n == 0
            if k == 0
                y = zeros(0,1);
            else
                error(message('stats:randsample:EmptyPopulation'));
            end
        elseif isempty(w)
            if defaultStream
                y = randi(n,k,1);
            else
                y = randi(s,n,k,1);
            end
    
        else
            % Irrelevant case as it concerns weighting which randi doesn't support.
        end
    ...
    

所以从上面我们了解到:

  • 在某些情况下,randsample 的输入只是重定向到 randi
  • 边缘情况的行为略有不同,例如 randi(0,0,1)(错误)与 randsample(0,0,true)(输出空数组)。

一般randsample 有更多的功能:它能够处理一个非默认的RandStream,以及权重。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2021-06-07
    相关资源
    最近更新 更多