how to create a random integernumbers with conditions?

2 ビュー (過去 30 日間)
SM
SM 2020 年 7 月 16 日
コメント済み: SM 2020 年 7 月 16 日
I just want to create an array at random which size will be 1 by sum([4 3 3]). The array contains 1 at 4 times, 2 at 3 times and 3 at 3 times. The result will be
A=[1 2 1 3 2 3 1 1 2 3], ie, random.
How can I generate it in the smart way?

採用された回答

madhan ravi
madhan ravi 2020 年 7 月 16 日
ix = [4, 3, 3];
A = repelem(1:3, ix);
A(randperm(numel(A)))
  1 件のコメント
SM
SM 2020 年 7 月 16 日
Thank You, Ravi. It is perfectly alright for my problem.

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

その他の回答 (1 件)

David Hill
David Hill 2020 年 7 月 16 日
A=[4 3 3];
a=[];
for k=1:length(A)
a=[a,repmat(k,1,A(k))];
end
for k=1:5
a=a(randperm(length(a)));%you don't necessary have to do this loop, you could do it just once
end
  1 件のコメント
SM
SM 2020 年 7 月 16 日
Thank you. It is also suitable for my problem but i try to avoid using loop.

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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by