how to generate a random array list with fixed sum ?

this code distributes fixed number in an array list, for exemple we have sum = 10, and the size of the array list is 3
the code generates this distribution [ 8 1 1] or other distribution...how can I modify this code to obtain a distribution that each value must be between 1 and sum/2 to obtain something like that [3 3 4]
S = 20;
n = 5;
m = 1;
while true
P = ones(S+1,n);
for in = n-1:-1:1
P(:,in) = cumsum(P(:,in+1));
end
R = zeros(m,n);
for im = 1:m
s = S;
for in = 1:n
R(im,in) = sum(P(s+1,in)*rand<=P(1:s,in));
s = s-R(im,in);
end
end
x = find(R<=0);
if x~=0
continue
else
break
end
end
indMaxArry = ceil(n/2);
R = circshift(sort(R),[0,indMaxArry])

6 件のコメント

John D'Errico
John D'Errico 2020 年 4 月 19 日
Rather that trying to decipher what your this undocumented mess of code does, it would really help if you also explain what you want?
Image Analyst
Image Analyst 2020 年 4 月 19 日
"...have values between 1 and s/2 ..." <==== Did you overlook the second example in the documentation for rand()? The one that said "Random Numbers Within Specified Interval"?
tlig zied
tlig zied 2020 年 4 月 19 日
at the beginning I use this code, but when we have, for example p=165 and c=80 it takes more time to generate the array
p=5;
c=3;
p1=randi([1 p],1,c);
while(sum(p1)~=p*2)
p1=randi([1 p],1,c);
end
John D'Errico
John D'Errico 2020 年 4 月 20 日
Do you want random INTEGERS with a fixed sum, or random floating point numbers?
In the cae of random floating point numbers, you could use one of two good tools on the file exchange, however, random integers with a fixed sum would be more difficult.
tlig zied
tlig zied 2020 年 4 月 21 日
yes I want random INTEGERS

サインインしてコメントする。

回答 (1 件)

Matt J
Matt J 2020 年 4 月 20 日

0 投票

2 件のコメント

tlig zied
tlig zied 2020 年 4 月 21 日
I can't use it because of this constarint n*a <= s <= n*b
Matt J
Matt J 2020 年 4 月 21 日
You haven't told us what any of those symbols mean, but the FEX submission does support bounds on the array elements.

サインインしてコメントする。

質問済み:

2020 年 4 月 19 日

コメント済み:

2020 年 4 月 21 日

Community Treasure Hunt

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

Start Hunting!

Translated by