Creating random integer row array each element different upper limit and sum of elements add up to a number
조회 수: 1 (최근 30일)
이전 댓글 표시
I am looking for a intutuve code to generate 1x6 array where each element is random integer (with in specific upper limit) and sums to a given number.
For example a random array where element lower limit [ 0 0 0 0 0 0] and upper limit [ 9 12 25 6 14 7]. The sum of the random integer number adds up to 24, e.g.
[4 3 8 1 3 4 1]
댓글 수: 0
채택된 답변
Ameer Hamza
2020년 9월 24일
편집: Ameer Hamza
2020년 9월 28일
See this excellent FEX package by John: https://www.mathworks.com/matlabcentral/fileexchange/49795-randfixedlinearcombination. However, It generates fractional numbers. Following code proposes one modification. I don't know how it will change the probability distribution.
lb = [0 0 0 0 0 0];
ub = [9 12 25 6 14 7];
n = numel(lb);
s = 24;
x = round(randFixedLinearCombination(1, s, [1 1 1 1 1 1], lb, ub));
k = sum(x) - s;
if k > 0
idx = find(x >= (lb+1));
idx = idx(randperm(numel(idx), k));
x(idx) = x(idx) - 1;
else
idx = find(x <= (ub-1));
idx = idx(randperm(numel(idx), -k));
x(idx) = x(idx) + 1;
end
댓글 수: 8
Bruno Luong
2020년 9월 27일
편집: Bruno Luong
2020년 9월 27일
I think you can do better if you replace the first filtering with <= >= tests rather than strict inequality.
It still not perfect though.
Ameer Hamza
2020년 9월 28일
Yes, I guess this will fail when the bounds are very tight in accordance with the sum constraints. The point about inequality is also valid. For the given bounds, the method does not seem to fail.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!