Rand function taking a long time

6 ビュー (過去 30 日間)
Christopher
Christopher 2016 年 4 月 27 日
コメント済み: Image Analyst 2016 年 4 月 27 日
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

採用された回答

Walter Roberson
Walter Roberson 2016 年 4 月 27 日
rand(10000) is the same as rand(10000,10000), not the same as rand(1,10000)
  2 件のコメント
Christopher
Christopher 2016 年 4 月 27 日
Thank you for your help just for reference the second method takes 0.060 s where as the first takes 3.401 s. I guess figuring out ways around loops really does speed up the process. Any ideas on how I can work around the other loop
for ii = 1:100
Image Analyst
Image Analyst 2016 年 4 月 27 日
It's not the for loop itself. For example, this:
tic
for ii = 1 : 100
end
toc
Takes virtually no time:
Elapsed time is 0.000024 seconds.

サインインしてコメントする。

その他の回答 (0 件)

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by