-1

how can I create a vector with a specific # of values that are drawn from a decided range? repeats are welcomed as long as they occur randomly.

for example a vector of 5 values all of which are integers between 1 and 80

ps I am working with the 2019 edition of Matlab

2 Answers2

0

You can use rand function; rand gives a random value between 0 and 1, but for a range, you may use the following formula.

lowest_val = -10
range = 20 % [-10, 10]
rand_vec = lowest_val + (range)*rand(10,1) % here the range is [-10, 10]

(20)*rand(10,1) will give a random value between 0 and 20, add -10 to it, the range becomes -10 to 10.

For your case, you may use

lowest_val = 1
range = 79 % [1, 80]
rand_vec = lowest_val + (range)*rand(10,1)

(80)*rand(10,1) will give a random value between 0 and 79, add 1 to it, the range becomes 1 to 80

You may use randperm if you don't want repetitions.

paul-shuvo
  • 1,874
  • 4
  • 33
  • 37
0

Depends whether they have to be integers or can be 'real' (floating point) numbers. Also, do you want the values 1 and 80 to be included?

In any case, there is this matlab help very useful.

As usually when working with random numbers you need to initialize the random generator.

rng(0,'twister');

This is used for you to be able to reproduce your results, so beware if you always use the same seed (0 in this case) you will always get the same results. the typical trick to randomize that is to use the current time as seed,

rng(posixtime(datetime('now')),'twister');

Given that you said you wanted an array of 5 numbers,

N = 5;

rand(N,M) returns a matrix of NxM uniformly distributed numbers in the interval (0,1), then you need the following transformation to bring them to your interval (a,b) ((1,80) in your case)

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

output:

>> a = 1;
b = 80;
r = (b-a).*rand(N,1) + a

r =

   65.5670
   69.6269
    7.6704
   32.5828
   21.5298

If you were looking for integers in the interval [1,80] (note that now the interval includes the values 1 and 80), then this would do it,

r = randi(80,N,1);

output:

>> r = randi(80,N,1)

r =

    65
    35
    73
    15
    22
myradio
  • 1,703
  • 1
  • 15
  • 25