Rand function taking a long time

6 Ansichten (letzte 30 Tage)
Christopher
Christopher am 27 Apr. 2016
Kommentiert: Image Analyst am 27 Apr. 2016
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

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 27 Apr. 2016
rand(10000) is the same as rand(10000,10000), not the same as rand(1,10000)
  2 Kommentare
Christopher
Christopher am 27 Apr. 2016
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 am 27 Apr. 2016
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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by