Rand function taking a long time

조회 수: 9 (최근 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