任意の値を除いたランダム値を生成したい
13 views (last 30 days)
Show older comments
任意の値を除いたランダム値を生成したいです。
たとえば1~10のうちから「2」以外の値を5つランダムに抽出する場合
どのようにコードを作ればよろしいでしょうか
0 Comments
Answers (1)
Shunichi Kusano
on 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関数をお使いください。
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!