Rand function taking a long time
显示 更早的评论
So I have this code below for demonstration a Poisson Distribution. Using an if loop
if rand < (1/AmountRnd)
is much faster than generating a random array
y=rand(10000);
Does anyone know why this is? I have poster both copies of my full code below. Faster Loop Method:
%Set Amount of random numbers to generate
AmountRnd=10000;
%Set length of distribution
Lpos=30;
%Create X array
X=1:1:Lpos;
%Initialize Poisson array
Poisson = zeros(1,Lpos);
%Loop
for ii = 1:100
%Initialise Count
Count = 1;
%Create loop for as many random number are set
for jj = 1:AmountRnd
%Count amount of times rand is less than given amount
if rand < (1/AmountRnd)
Count = Count + 1;
end
end
%Create Poisson array using values from each count
Poisson(Count) = Poisson(Count) + 1;
end
%Graph Histogram of distribution
stairs(Poisson);
Slower Method:
%Set Amount of random numbers to generate
AmountRnd=10000;
Lpos=30;
X=1:1:Lpos;
Poisson = zeros(1,Lpos);
%Loop
for j=1:100
%Initialise Count
Count = 1;
y=rand(10000);
Poisson(Count) = sum(y(1:10000)<(1/10000)) + Poisson(Count) + 1;
end
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Poisson Distribution 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!