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!

Réponses (1)

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

J. Boog
J. Boog le 9 Oct 2015
Modifié(e) : J. Boog le 9 Oct 2015
The 'making the array larger' part works great! Although, the sum of B(1, 2:4) and B(1, 7:8) is not 1. Do you have a solution for this?

Connectez-vous pour commenter.

Catégories

Question posée :

le 9 Oct 2015

Modifié(e) :

le 9 Oct 2015

Community Treasure Hunt

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

Start Hunting!

Translated by