How to create a random row vector whose sum of elements and number of elements is at my desire?
Mostrar comentarios más antiguos
For example I want a row vector(1,5) and its total sum should be 20. Is there any function which randomly returns a 1*5 vector with 20 as its sum of elements?
2 comentarios
Jos (10584)
el 30 de Nov. de 2013
Do the elements need to be integers?
Vivek
el 30 de Nov. de 2013
Respuesta aceptada
Más respuestas (2)
Roger Stafford
el 30 de Nov. de 2013
Editada: Roger Stafford
el 30 de Nov. de 2013
If only positive integers are allowed (>0) then do:
m = 20; % Choose the desired sum
n = 5; % Choose the number of integers
v = diff([0,sort(randperm(m-1,n-1)),m]);
If zeros are permitted, then do:
m = 20; % Choose the desired sum
n = 5; % Choose the number of integers
v = diff([0,sort(randperm(m+n-1,n-1)),m+n])-ones(1,n);;
Note: These algorithms randomly select among all possible solutions with uniform probability.
Note 2: If you have the older version of 'randperm' that has only one input argument, you can substitute
p = randperm(n);
p = p(1:k);
for
p = randperm(n,k);
Note 3; There is no limitation such as n<=15 on the size of n in randperm(n). It is very different from perm.
3 comentarios
Andrei Bobrov
el 30 de Nov. de 2013
+1
Roger Stafford
el 1 de Dic. de 2013
I neglected to point out, Vivek, that the total number of possible solutions to your problem is implicit in these two expressions. If zeros are not permitted, the total is (m-1)!/(n-1)!/(m-n)!, namely the number of possible combinations of n-1 things chosen out of m-1 things. With zeros permitted it is (m+n-1)!/(n-1)!/m!, the number of combinations of n-1 things out of m+n-1 things. The probabilities are equal for all possibilities simply because the combinations produced by doing the two-argument 'randperm' followed by a 'sort' should all be of equal probability (provided Mathworks' random number generator is working properly.)
Vivek
el 2 de Dic. de 2013
Azzi Abdelmalek
el 30 de Nov. de 2013
Editada: Azzi Abdelmalek
el 30 de Nov. de 2013
Edit
n=20;
m=21;
p=fix(m/n);
v=randi(p,1,n);
a=m-sum(v);
x=zeros(n,ceil(a/n));
x(1:a)=1;
v=v+sum(x',1)
3 comentarios
Vivek
el 30 de Nov. de 2013
Azzi Abdelmalek
el 30 de Nov. de 2013
v=randi(4,1,5)
a=20-sum(v)
x=zeros(5,ceil(a/5));
x(1:a)=1
v=v+sum(x',1)
Vivek
el 2 de Dic. de 2013
Categorías
Más información sobre Operators and Elementary Operations en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!