Efficient allocation of random numbers(U(0,1)) into categories

1 回表示 (過去 30 日間)
DoVile Last Name:
DoVile Last Name: 2012 年 9 月 29 日
I am trying to create a function which takes two arguments as input, one a vector of values drawn from a uniform distribution and the other input a number of values between 0 ad 1. It should then index the values from the first input with a number corresponding to its category in the second input.
For example Input1 = [0.2 0.5 0.90 0.995] input2 = [0 0.81 0.99 1] Output = [0 0 1 2]
At present i am using a double for loop with an if statement
for i=1:length(randoms)
for r = 1:(length(ShockProbabilities)-1)
if randoms(i) >= (ShockProbabilities(r)) && randoms(i) < (ShockProbabilities(r+1)); randoms(i)=(r-1); end
end
end
Could any one suggest how i might speed this up ? i am sure there is a way and i dont like using 2 for loops and an if statement. I am just curious, i dont really need it as such
Thanks :)

採用された回答

Matt Fig
Matt Fig 2012 年 9 月 29 日
編集済み: Matt Fig 2012 年 9 月 29 日
How about the HISTC function?
Also, in your code there is no reference to either input1 or input2, so I cannot run it...
  3 件のコメント
Matt Fig
Matt Fig 2012 年 9 月 29 日
編集済み: Matt Fig 2012 年 9 月 29 日
Try this:
[J,K] = histc(randoms,ShockProbabilities);
K = K-1
By the way, to make your code faster you could put a break after the randoms(i) reassignment since it is presumed that only one fit will be found per element. As it is you continue to check even after you find where randoms(i) goes! You could also only run the inner loop from the last r found to the end-1 because randoms is sorted. These two hints would speed things up considerably for large arrays. Still, I doubt you will beat HISTC.
DoVile Last Name:
DoVile Last Name: 2012 年 9 月 29 日
Great i got it working, and the break tip was a real eye opener for me! in the actual program i will be using quasirandom numbers instead of the ones from the example so they wont be sorted, also i kind of want a more robust function.
Thanks Matt :)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMonte Carlo Analysis についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by