Generate a random number in a certain range in MATLAB

ε祈祈猫儿з 提交于 2020-01-09 02:15:49

问题


How can I generate a random number in MATLAB between 13 and 20?


回答1:


If you are looking for Uniformly distributed pseudorandom integers use:

randi([13, 20])



回答2:


http://www.mathworks.com/help/techdoc/ref/rand.html

n = 13 + (rand(1) * 7);



回答3:


r = 13 + 7.*rand(100,1);

Where 100,1 is the size of the desidered vector




回答4:


ocw.mit.edu is a great resource that has helped me a bunch. randi is the best option, but if your into number fun try using the floor function with rand to get what you want.

I drew a number line and came up with

floor(rand*8) + 13



回答5:


You can also use:

round(mod(rand.*max,max-1))+min



回答6:


Generate values from the uniform distribution on the interval [a, b].

      r = a + (b-a).*rand(100,1);



回答7:


Best solution is randint , but this function produce integer numbers.

You can use rand with rounding function

  r = round(a + (b-a).*rand(m,n));

This produces Real random number between a and b , size of output matrix is m*n




回答8:


if you are looking to generate all the number within a specific rang randomly then you can try

r = randi([a b],1,d)

a = start point

b = end point

d = how many number you want to generate but keep in mind that d should be less than or equal to b-a




回答9:


If you need a floating random number between 13 and 20

(20-13).*rand(1) + 13

If you need an integer random number between 13 and 20

floor((21-13).*rand(1) + 13)

Note: Fix problem mentioned in comment "This excludes 20" by replacing 20 with 21



来源:https://stackoverflow.com/questions/5077800/generate-a-random-number-in-a-certain-range-in-matlab

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