How to draw multiple random numbers from kernel estimated densities at once?

2 views (last 30 days)
Hi all,
If I have 10 kernel estimated densities and I want to draw 10 random numbers at once (one random number from one density), how to do it? I don't want to use for loop because it is slow if I want to repeat this process many times. Here is my code, but it does not work.
%first put 10 kernel densities into an array
X(1,1) = kdensity1;
X(2,1) = kdensity2;
X(3,1) = kdensity3;
X(4,1) = kdensity4;
X(5,1) = kdensity5;
X(6,1) = kdensity6;
X(7,1) = kdensity7;
X(8,1) = kdensity8;
X(9,1) = kdensity9;
X(10,1) = kdensity10;
%draw random number
rd = random(X)
%error message
Error using prob.TruncatableDistribution/random (line 87)
This method requires a scalar probability distribution.
What I want is something similar to this process.
%lambda is 10x1
%gamma is 10x1
%draw random numbers
rd=wblrnd(lambda,gamma); %I get 10 random values at once, and they are from Weibull distributions with different lambdas and gammas
Many thanks in advance
JW
  2 Comments
Image Analyst
Image Analyst on 9 Sep 2020
Why do you incorrectly think loops are slow. That's an old, obsolete myth. You can do tens of millions of iterations in less than a second. Just how fast do you need?
jiafeng wu
jiafeng wu on 9 Sep 2020
Sorry that I did not explain clearly why my calculation is slow. I have 3 loops nested together which makes my calculation slow. If there is a way to solve the question asked above, I can reduce the number of nested loops and potentially make the calculation faster.

Sign in to comment.

Accepted Answer

Jeff Miller
Jeff Miller on 9 Sep 2020
Can you reorganize your code so that you generate many random numbers at once from each density, store them in vectors, and then process iteratively through those vectors? It is hard to be more specific without knowing what you are trying to do, but it seems that you are thinking of generating random numbers in the inner-most for loop when you could instead generate them in an outer for loop. Getting n random numbers from a single call to the ksdensity random function would probably be much faster than n calls to get them one at a time.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!