How to generate random numbers between two numbers without any specific number?

37 ビュー (過去 30 日間)
Arnab Pal
Arnab Pal 2017 年 8 月 21 日
コメント済み: Walter Roberson 2020 年 10 月 25 日
I want to generate random numbers between 2 and 33. But do not want a(i) number. a(i) can be a single number between 2 to 33.

回答 (4 件)

Walter Roberson
Walter Roberson 2019 年 3 月 25 日
valid_choices = setdiff(2:33, a(i));
random_choice = valid_choices(randi(length(valid_choices)));
  1 件のコメント
Walter Roberson
Walter Roberson 2020 年 10 月 25 日
This can be trivially extended to a list of values to avoid,
valid_choices = setdiff(2:33, a);
random_choice = valid_choices(randi(length(valid_choices)));

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


per isakson
per isakson 2017 年 8 月 21 日
編集済み: per isakson 2017 年 8 月 21 日
"[...] without any specific number?" I don't understand that. However, try
>> 2 + rand*(33-2)
ans =
26.8087
>> 2 + rand(1,3)*(33-2)
ans =
31.9115 6.8860 32.0884
In response to comment
Try
>> num = one_random_number( 2, 33, [3,4,5,6,7,8] )
num =
24.5963
>> num = one_random_number( 2, 33, 5 )
num =
22.1580
>>
where
function num = one_random_number( lower, upper, exclude )
num = exclude(1);
while any( num == exclude )
num = lower + rand*(upper-lower);
end
end
Add some error checking to the code and be prepared for comments regarding tests for equal on floating point numbers. Did you mean random whole number? If you did, replace
num = lower + rand*(upper-lower);
by
num = randi([lower,upper]);
  4 件のコメント
per isakson
per isakson 2017 年 8 月 21 日
編集済み: per isakson 2017 年 8 月 21 日
I've updated the answer
Arnab Paul
Arnab Paul 2019 年 3 月 25 日
time consuming

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


NARAYAN SHARMA
NARAYAN SHARMA 2019 年 6 月 13 日
If you want to generate random real numbers between X1 to X2 except X3 then try the code written below
X1= 0;
X2=100;
X3=10;
total_number=1000;
for i=1:total_number
Random_number=X1+ rand*(X2-X1)
while Random_number==X3
Random_number=X1+ rand*(X2-X1)
end
Real_rand_number(i,1)=Random_number;
end
If you want to generate random integers between X1 to X2 except X3 then try the code written below
X1= 0;
X2=100;
X3=10;
total_number=1000;
for i=1:total_number
Random_number=round(X1+ rand*(X2-X1))
while Random_number==X3
Random_number=round(X1+ rand*(X2-X1))
end
Real_rand_number(i,1)=Random_number;
end

Nardjim Hermann
Nardjim Hermann 2020 年 10 月 25 日
research randi,fix,round,ceil,floor functions
  1 件のコメント
Walter Roberson
Walter Roberson 2020 年 10 月 25 日
These do not in themselves answer the question. The question is not how to generate random integers: the question is how to do so while avoiding certain possibilities.

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

カテゴリ

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