lettura simple

How to generate vectors with random numbers in Octave

In this lesson I'll explain how to create a vector (array) composed by random numbers on Octave.

I'll give you a practical example

Creates a horizontal vector of 5 elements with random values between 0 and 1

Type the command rand(1,5)

>> rand(1,5)
ans = 0.49304 0.44118 0.76854 0.67157 0.90157

If you want to create the same vector with the elements arranged vertically, type rand(5,1)

>> rand(5,1)
ans =
0.832438
0.132569
0.036763
0.953994
0.483982

Note. A vertical vector [5,1] is like a matrix with many rows (5) and a single column (1). Conversely, a row vector [1,5] is like a matrix consisting of a single row (1) and many columns (5).

To create a vector composed of 5 real numbers between 0 and 10 type rand(1,5)*10

>> rand(1,5)*10
ans =
6.1685 8.9548 6.4072 7.9498 3.9733

If you want to create a vector composed of 5 real numbers between -5 and 5, type rand(1,5)*10-5

>> rand(1,5)*10-5
ans =
2.93633 -0.58853 -1.37175 3.83107 4.31426

To create a horizontal vector consisting of 5 integer elements with values between 18 and 30, type randi([18,30],1,5)

>> randi([18,30],1,5)
ans =
26 21 24 28 21

To create the same vector vertically type randi([18,30],5,1)

>> randi([18,30],5,1)
ans =
18
28
30
29
20

Alternatively, you can also create vectors composed of random integers by combining the random number generation function rand() with the rounding function round()

For example, to create an array of 5 integers with values between 18 and 30, type round(rand(5,1)*12+18)

>> round(rand(5,1)*12+18)
ans =
26
27
29
24
25




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin