How can I generate a random number that is negative or positive and between two other values?

130 ビュー (過去 30 日間)
I need to write a function that generates two numbers that are between the negative and positive values of an integer. For example, if I call the function and input 7 it should generate two random numbers between -7 and +7. I can't figure out a way to use the randi function because the values I need can't be just integers.

採用された回答

Walter Roberson
Walter Roberson 2015 年 11 月 20 日
Hint: rand()-1/2 is in the range -1/2 to +1/2
  1 件のコメント
Jacob
Jacob 2023 年 10 月 11 日
if you a number x
generating random between -x and x
x = 7;
for i = 1:x*2
z(i) = (2*x)*(rand(1)-.5);
end
disp(z)
2.5026 1.8492 0.0427 -1.6578 5.2690 5.5979 -2.9920 -6.5039 6.2270 -1.6916 -3.8918 5.8560 1.9215 -6.7670

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

その他の回答 (2 件)

Rahul Gulia
Rahul Gulia 2020 年 1 月 22 日
>> randi([-2,2],3,3) will give the desired output.
Thanks for pointing out my mistake @ Walter Roberson .

Hayatullahi Adeyemo
Hayatullahi Adeyemo 2017 年 11 月 19 日
You can use visit here

カテゴリ

Help Center および File ExchangeRandom Number Generation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by