天天看點

MATLAB unifrnd 與 rand函數的差別MATLAB unifrnd 與 rand函數的差別

MATLAB unifrnd 與 rand函數的差別

最近在生成随機數的時候看到這兩個函數,通過查找資料發現二者的關系:

相同點:

  • 二者都是利用rand函數進行随機值計算。
  • 二者都是均勻分布。

不同點:

  • unifrnd是統計工具箱中的函數,是對rand的包裝。
不是Matlab自帶函數無法使用JIT加速。
  • rand函數可以指定随機數的資料類型。

執行個體:

在區間[5,10]上生成400個均勻分布的随機數 :

h1=unifrnd(5,10,1,400);
 h2=5+5*rand(1,400); % same pdf
           

二者生成的結果是相同的。

下面是unifrnd源代碼,可以看出該函數可以通過指定參數進行計算。

function r = unifrnd(a,b,varargin)
%UNIFRND Random arrays from continuous uniform distribution.
%   R = UNIFRND(A,B) returns an array of random numbers chosen from the
%   continuous uniform distribution on the interval from A to B.  The size
%   of R is the common size of A and B if both are arrays.  If either
%   parameter is a scalar, the size of R is the size of the other
%   parameter.
%
%   R = UNIFRND(A,B,M,N,...) or R = UNIFRND(A,B,[M,N,...]) returns an
%   M-by-N-by-... array.
%
%   See also UNIFCDF, UNIFINV, UNIFPDF, UNIFSTAT, UNIDRND, RANDOM.

%   UNIFRND uses a linear transformation of standard uniform random values.

%   Copyright 1993-2018 The MathWorks, Inc. 

% Avoid    a+(b-a)*rand   in case   a-b > realmax
%
a2 = a/2;
b2 = b/2;
mu = a2+b2;
sig = b2-a2;

r = mu + sig .* (2*rand(sizeOut,'like',mu)-1);

% Fill in elements corresponding to illegal parameter values
if ~isscalar(a) || ~isscalar(b)
    r(a > b) = NaN;
elseif a > b
    r(:) = NaN;
end
           

繼續閱讀