How to pick random numbers with fixed sum from a certain array?
Afficher commentaires plus anciens
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 commentaire
Réponses (1)
Thorsten
le 9 Oct 2015
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
1 commentaire
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!