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 件のコメント

Thorsten
Thorsten 2015 年 10 月 9 日
編集済み: Thorsten 2015 年 10 月 9 日
Matlab uses . (not ,) as decimal mark.

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

回答 (1 件)

Thorsten
Thorsten 2015 年 10 月 9 日

0 投票

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 件のコメント

J. Boog
J. Boog 2015 年 10 月 9 日
編集済み: J. Boog 2015 年 10 月 9 日
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?

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

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

質問済み:

2015 年 10 月 9 日

編集済み:

2015 年 10 月 9 日

Community Treasure Hunt

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

Start Hunting!

Translated by