How to generate vector of n random numbers between 0 and 1 to x decimal places?
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Roger Stafford
2016-3-21
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Random Number Generation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!