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

末鹿安然 提交于 2019-11-27 16:13:41

More generally:

minInt = 5;
maxInt = 7;
numInts = 10;

r = randi([minInt, maxInt],[1,numInts])

r =

 6     7     7     7     6     5     5     5     7     5
gnovice

First, if you are wanting to generate random integer values, it's better to use the function RANDI. Then it's just a matter of shifting and scaling the random numbers accordingly. The following should give you random integers between 5 and 7 inclusive:

nums = randi(3,[1 5])+4;

EDIT: As Amro's comment and Doug's answer point out, there is a more straightforward solution whereby you can specify the range directly as the first argument to RANDI:

nums = randi([5 7],[1 5]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!