How to pick random numbers with fixed sum from a certain array?
이전 댓글 표시
Hello,
I have a vector A = [1 3 1 1 2] and random_vector = 0:0,1:1.
I want to change this into for example: B = [1 0,2 0,3 0,5 1 1 0,9 0,1].
The length of 'B' is the sum of 'A'. The values B(1, 2:4) have sum 1. The values of B(1, 7:8) have sum 1 as well. If in 'A' a value is for example 3, 'A' adds 2 extra columns and takes random values of 'random_vector' with sum 1. How can I do this properly?
Thanks!
댓글 수: 1
답변 (1개)
Thorsten
2015년 10월 9일
A = [1 3 1 1 2];
r = 0:0.1:1;
r = r(randperm(numel(r)));
B = [];
ir = 1;
for i = 1:numel(A)
if A(i) == 1
B(end+1) = 1;
else
B(end+1:end+A(i)) = r(ir:ir+A(i)-1);
ir = ir+A(i);
end
end
카테고리
도움말 센터 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!