How to generate vector of n random numbers between 0 and 1 to x decimal places?

1 visualización (últimos 30 días)
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

Respuestas (1)

Roger Stafford
Roger Stafford el 21 de Mzo. de 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

Categorías

Más información sobre Random Number Generation en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by