Azzera filtri
Azzera filtri

random number generation for known sum

4 visualizzazioni (ultimi 30 giorni)
harley
harley il 27 Ago 2013
Commentato: Tejas il 14 Lug 2020
i what do generate some 15 random numbers that sum for each separate value of say, 60 , 70, 40, 65. How would i go abouts this?
sum = [60 70 40 65];
n=15;
b = [ ];
for i = 1:1:n,
a = randi([1,??]);
b = [b a];
end

Risposta accettata

Azzi Abdelmalek
Azzi Abdelmalek il 27 Ago 2013
n=60;
m=1:n;
a=m(sort(randperm(60,15)));
b=diff(a);
b(end+1)=60-sum(b)
sum(b)
  13 Commenti
Bruno Luong
Bruno Luong il 13 Lug 2020
Modificato: Bruno Luong il 13 Lug 2020
The easiest way is perhaps using Roger FEX function, then do some sort of "integering" the float solution
sumatarget = 60
n = 15;
ub = 7;
x = floor([0; cumsum(randfixedsum(n,1,sumatarget,0,ub))]);
x(end) = sumatarget; % prevent floating point error
r = diff(x)
The distribution might be not perfectly uniform but possibly close enough and suitable for what ever you want to do with it.
Tejas
Tejas il 14 Lug 2020
Integering the solution from Roger's function works very well for me. I do not require the numbers to be perfectly uniform. Thanks!

Accedi per commentare.

Più risposte (1)

Walter Roberson
Walter Roberson il 27 Ago 2013

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by