MATLAB: How to create a random row vector whose sum of elements and number of elements is at the desire

total sum

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?

Best Answer

n = 5;
m = 20;
a = rand(n,1);
out = round(a/sum(a)*m);
out(1) = out(1) - sum(out) + m;