How to generate random numbers in Octave
In this lesson I'll explain how to generate a random number in Octave with some practical examples
What is a random number? It's a number randomly drawn from a set of numbers. It is also called a random number.
You can generate a random number using the command rand()
The rand() command extracts a random number between 0 and 1 by default
>> rand()
ans = 0.59520
To generate a real number between 0 and 10 type rand()*10
>> rand()*10
ans = 7.9405
To generate a real number between 0 and 100 type rand()*100
>> rand()*100
ans = 50.618
To generate a real number between 18 and 30 type rand()*12+18
>> rand()*12+18
ans = 27.996
If you want to generate a random integer you have two options.
You can round the result of the function rand() with the function round().
>> round(rand()*10)
ans = 9
Alternatively, you can use the command randi() by inserting the maximum value between the round brackets.
>> randi(10)
ans = 6
The randi() command extracts a random number between 1 and the maximum value you indicated (10)
To extract an integer in the range of 18 to 30, type the range in square brackets randi([18,30])
>> randi([18,30])
ans = 27
You can also create a vector of random real numbers.
For example, to define a random vector made up of three elements, type rand(3,1)
>> rand(3,1)
ans =
0.83541
0.32661
0.96998
If you want to create a random vector of random integers between 1 and 10 type randi(10,3,1)
The first value (10) is the maximum value, the second (3) and third (1) are the number of rows and columns in the array.
>> randi(10,3,1)
ans =
8
2
7
This way you can also create an array of random numbers.
For example, to define a square array of random integers between 1 and 10 with three rows and three columns, type randi(10,3,3)
>> randi(10,3,3)
ans =
5 7 4
2 1 6
1 10 7
If you want to create the same matrix using random real numbers type rand(3,3)*10
>> rand(3,3)*10
ans =
7.837730 2.168224 0.083629
6.934926 1.929531 5.050613
9.045520 2.163601 3.164065
If this Nigiara lesson helped you, keep following us.