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

9 visualizaciones (últimos 30 días)
Sho Ikeda
Sho Ikeda el 22 de Nov. de 2020
Respondida: Shunichi Kusano el 22 de Nov. de 2020
任意の値を除いたランダム値を生成したいです。
たとえば1~10のうちから「2」以外の値を5つランダムに抽出する場合
どのようにコードを作ればよろしいでしょうか

Respuestas (1)

Shunichi Kusano
Shunichi Kusano el 22 de Nov. de 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関数をお使いください。

Categorías

Más información sobre 乱数発生器 en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!