random number generation for known sum

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

 Respuesta aceptada

Azzi Abdelmalek
Azzi Abdelmalek el 27 de Ag. de 2013
n=60;
m=1:n;
a=m(sort(randperm(60,15)));
b=diff(a);
b(end+1)=60-sum(b)
sum(b)

13 comentarios

thanks Azzi, i get an error
Error in ==> Untitled at 3
a=m(sort(randperm(60,15)));
You must be using an older MATLAB that does not have that enhancement to randperm(). Try
t = randperm(n);
a=m(sort(t(1:15));
harley
harley el 27 de Ag. de 2013
thanks
Arnab Pal
Arnab Pal el 4 de Nov. de 2018
I want to generate the same, but I need Non-integer numbers. Is it possible?
Bruno Luong
Bruno Luong el 4 de Nov. de 2018
Editada: Bruno Luong el 4 de Nov. de 2018
@Arnab
sumtarget = 60;
n = 5;
x = diff([0,sort(randperm(sumtarget+n-1,n-1)),sumtarget+n])-1
Arnab Pal
Arnab Pal el 4 de Nov. de 2018
Editada: Arnab Pal el 4 de Nov. de 2018
Sir, It is generating the integer numbers only.
Bruno Luong
Bruno Luong el 4 de Nov. de 2018
Ah sorry some how I read non-negative.
For random non-negative floating numbers, you need using Roger Stafford FEX
Tejas
Tejas el 13 de Jul. de 2020
Is there an easy way to control the maximum value each number in 'b' can have? Say, each value in 'b' must be less than or equal to 7, and still the 15 numbers in 'b' should add up to 60.
Walter Roberson
Walter Roberson el 13 de Jul. de 2020
Roger's FEX contribution, the a and b parameters are lower bound and upper bound. You can use zeros for the lower bound if that is appropriate for your situation.
Tejas
Tejas el 13 de Jul. de 2020
Editada: Tejas el 13 de Jul. de 2020
I want the numbers to be integers, as in the original question. Roger's FEX contribution seems to work with real numbers.
Bruno Luong
Bruno Luong el 13 de Jul. de 2020
Editada: Bruno Luong el 13 de Jul. de 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 el 14 de Jul. de 2020
Integering the solution from Roger's function works very well for me. I do not require the numbers to be perfectly uniform. Thanks!

Iniciar sesión para comentar.

Etiquetas

Preguntada:

el 27 de Ag. de 2013

Comentada:

el 14 de Jul. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by