Using rand in matlab to produce numbers between li

2019-01-20 13:11发布

Possible Duplicate:
Is there a way in Matlab using the pseudo number generator to generate numbers within a specific range?

I want to get 20 random integer numbers between -10 and 10 and I thought of using the rand function in matlab.

I thought of myltiplying by ten and then finding a way to get only the ones between -10 and 10 and use an iteration for each of the other numbers that is outside the limits [-10,10] to get a new number inside the limits.

Is there a better, faster way?

2条回答
神经病院院长
2楼-- · 2019-01-20 13:53

Use

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

to generate a vector of random integers between -10 and 10.

查看更多
萌系小妹纸
3楼-- · 2019-01-20 13:56

Although Jonas' solution is really nice, randi isn't in some of the early 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 you want a distribution over.

If you are use round(a + (b-a)) you will have a nonuniform effect on the values of 'a' and 'b'. This can be confirmed using the hist() function. This is because the domain that maps into 'a' and 'b' is half the size for all other members of the range.

查看更多
登录 后发表回答