任意の値を除いたランダム値を生成したい

14 vues (au cours des 30 derniers jours)
Sho Ikeda
Sho Ikeda le 22 Nov 2020
任意の値を除いたランダム値を生成したいです。
たとえば1~10のうちから「2」以外の値を5つランダムに抽出する場合
どのようにコードを作ればよろしいでしょうか

Réponses (1)

Shunichi Kusano
Shunichi Kusano le 22 Nov 2020
idx = randi(9,[100,1]); % これはインデックス 1-10の中で2だけ除くので、マックスは9
histogram(idx) % 確認のため
targets = [1 3 4 5 6 7 8 9 10]; % 生成したい数1-10のなかで2だけを除く
randIdx = targets(idx);
histogram(randIdx) % 確認のため
こんなかんじでできるかと思います。
もし、targetsがもっと長いベクトルの場合(例えば1-100までの間で50だけ除きたい、など)、上記のように手打ちで入力するのは面倒なので、setdiff関数をお使いください。

Catégories

En savoir plus sur 乱数発生器 dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!