Using rand in matlab to get numbers between limits

Possible duplicate:
Is there a way in Matlab using a pseudo random number generator to generate numbers in a specific range?

I want to get 20 random integers from -10 to 10, and I thought about using the rand function in matlab.

I thought about myltiplying for ten, and then found a way to get only those that are between -10 and 10 and use iteration for each of the other numbers that are outside [-10,10] to get a new number within.

Is there a better, faster way?

+3
source share
2 answers

Use

randomIntegers = randi([-10,10],[20,1]) 

to generate a random number vector from -10 to 10.

+7
source

Although the Jonas solution is really nice, randi not part of some of the earlier versions of MATLAB. I believe all versions have rand . A solution using rand would be:

 randomIntergers = floor(a + (b-a+1) .* rand(20,1)); 

where [a, b] is the range of values ​​that you want to distribute.

If you use round(a + (ba)) , you will get an uneven effect on the values ​​of "a" and "b". This can be confirmed using the hist() function. This is due to the fact that the domain that is displayed in "a" and "b" is two times smaller for all other members of the range.

+2
source

Source: https://habr.com/ru/post/1402671/


All Articles