Borrar filtros
Borrar filtros

choosing from numbers whose sum is X

1 visualización (últimos 30 días)
Matlabbey
Matlabbey el 11 de Sept. de 2012
hi all,
suppose i generate 1000 random numbers and want to pick five out of that 1000 so that the sum of the five numbers is 100. if there is no way so the sum equal to 100 then i will just re run it. it doesnt have to work always...thank you!!

Respuesta aceptada

Matt Fig
Matt Fig el 11 de Sept. de 2012
Editada: Matt Fig el 11 de Sept. de 2012
I suppose you mean integers, but you don't say....
N = round(randn(1,1000));
S = 0;
maxiter = 2e6;
cnt = 1;
while S~=5 & cnt<maxiter
R = ceil(rand(1,5)*1000);
S = sum(N(R));
cnt = cnt + 1;
end
Now we have the numbers, so look at them:
nums = N(R)
sum(nums)
  3 comentarios
Matt Fig
Matt Fig el 11 de Sept. de 2012
Editada: Matt Fig el 11 de Sept. de 2012
What do you mean, no fixed sum? I generated 100 random numbers and chose 5 whos sum is 5. If you need to change it to the sum being 100, then just use:
while S~=100
You might also like a different distribution. So:
N = round(randn(1,1000)*20);
N = randi(100,1,1000); % etc...
Matlabbey
Matlabbey el 11 de Sept. de 2012
sorry, you're right!! thank you!!

Iniciar sesión para comentar.

Más respuestas (1)

Sean de Wolski
Sean de Wolski el 11 de Sept. de 2012
Editada: Sean de Wolski el 11 de Sept. de 2012

Categorías

Más información sobre Creating and Concatenating Matrices 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