Boost NORMRND speed for family of distributions in MATLAB

So I am looking for a way to speed up my code. I have a large vector of normal distributions (i.e. Vector of means and standard deviations) from which I need to generate random numbers. A general example of my code looks like this:

tic

N=1e6;
mu = rand(N,1);
sigma = rand(N,1);

temp = zeros(length(mu),1);

for i = 1:length(mu)
     temp(i) = normrnd(mu(i),sigma(i));
end

toc

      

This code in its current form has an elapsed time:

Elapsed time is 12.281509 seconds.

      

I usually try to vectorize most of my computationally intensive commands, but now I'm stumped as to how I can make this run faster. I will perform this operation several times each time the code runs, so the faster I can get it done the better.

Does any of the MATLAB geniuses have any thoughts on how to speed this up?

Thank! John

+1


source to share


1 answer


Hacked in normrnd.m

to get this custom code, which should replicate the functionality described in the issue -

N=1e6;
mu = rand(N,1);
sigma = rand(N,1);
temp = randn(size(sigma)).*sigma + mu;

      



On my system, the execution time dropped from 18.946094 seconds

to 0.037229 seconds

.

Hope this works for you!

+2


source







All Articles