sample (with replacement) random integers all range included

2 ビュー (過去 30 日間)
K G
K G 2015 年 10 月 24 日
編集済み: Andrei Bobrov 2015 年 10 月 24 日
hello,
I want to create a vector X of n uniformly random integers from a range [0 m] without missing any of the numbers between 0 and m.
for example:
n=10 m=3
I want X to contain 10 integers with values 0, 1, 2, 3 and I want all of them to appear at least one time.
i.e. the following vector is not allowed: [3 3 0 1 1 0 3 1 1 0] because it doesn't contain the number "2" at least one time
Is there a matlab function doing that? or I have to create one?
Thanks.

回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2015 年 10 月 24 日
編集済み: Andrei Bobrov 2015 年 10 月 24 日
out = randi([0,m],n,1);
t = 0:m;
N = histcounts(out,[t,m]);
l0 = N==0;
if any(l0)
[~,ii] = max(N);
jj = find(out == t(ii));
out(jj(1:nnz(l0))) = t(l0);
end

カテゴリ

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