How to generate vector of n random numbers between 0 and 1 to x decimal places?
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hello! I'd like to generate a vector of n random numbers between 0 and 1 that sum to 1 to x decimal places. Based on other community answers, I created the following function but due to rounding error, the sum of the numbers doesn't always sum to 1 (e.g. it may sum to 0.99 or 1.02). Right now, my workaround idea is to offset the difference by subtracting this value (e.g. -0.01 or +0.02) from one of the vector's elements, but I was wondering if there is a cleaner way to do this. Thanks for any help you can provide!
In this case, x = 2.
function [scenarioProbabilities] = generateScenarioProbabilities(n)
% Generates probability of realization for each scenario
for i = 1:n
scenarioProbabilities = rand(n, 1);
sumOfProbabilities = sum(scenarioProbabilities);
scenarioProbabilities = roundn(bsxfun(@rdivide, scenarioProbabilities, sumOfProbabilities),-2);
end
end
0 commentaires
Réponses (1)
Roger Stafford
le 21 Mar 2016
You might be interested in the function I wrote for the File Exchange:
http://www.mathworks.com/matlabcentral/fileexchange/9700-random-vectors-with-fixed-sum
0 commentaires
Voir également
Catégories
En savoir plus sur Random Number Generation dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!