How to create a random row vector whose sum of elements and number of elements is at my desire?
Show older comments
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?
Accepted Answer
More Answers (2)
Roger Stafford
on 30 Nov 2013
Edited: Roger Stafford
on 30 Nov 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 Comments
Andrei Bobrov
on 30 Nov 2013
+1
Roger Stafford
on 1 Dec 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
on 2 Dec 2013
Azzi Abdelmalek
on 30 Nov 2013
Edited: Azzi Abdelmalek
on 30 Nov 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 Comments
Vivek
on 30 Nov 2013
Azzi Abdelmalek
on 30 Nov 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
on 2 Dec 2013
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!