lettura simple

How to make vectors with random numbers in Octave

In this lesson I'll explain how to create a vector (array) composed of random numbers in 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. You can see a vertical vector [5,1] as a matrix consisting of many rows (5) and only one column (1). Similarly, you can see a row vector [1,5] as a matrix consisting of only one 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 with 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

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

>> 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, type round(rand(5,1)*12+18) to create an array consisting of 5 integers with values between 18 and 30

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

If you like this Nigiara tutorial and it's useful, keep following us.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin