Improve speed of NORMRND for a family of distributions in MATLAB

浪子不回头ぞ 提交于 2019-12-29 01:50:09

问题


So, I am looking for a way to speed up my code. I have a large vector of normal distributions (i.e. a vector of means and standard deviations) that I need to generate random numbers from. A generic 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 of:

Elapsed time is 12.281509 seconds.

I normally try to vectorize most of my computationally intensive commands, but right now I am stumped as to how I can make this run faster. I will have to perform this operation multiple times every time that the code is run, so the faster I can make it the better.

Do any of you MATLAB geniuses out there have any thoughts of how to speed this up?

Thanks! John


回答1:


Hacked into normrnd.m to get this customized code that must replicate the functionality depicited in the problem -

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

On my system, the runtime was reduced from 18.946094 seconds to 0.037229 seconds.

Hope this works out for you!



来源:https://stackoverflow.com/questions/26674683/improve-speed-of-normrnd-for-a-family-of-distributions-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!