lettura simple

Generating Random Numbers in Matlab Arrays

In this lesson, I'll show you how to create an array of random numbers in Matlab.

Let's dive into an example.

To create a row vector with five random values between 0 and 1, simply type the function rand(1,5)

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

Similarly, to create a column vector with five random values, type rand(5,1)

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

Note that the vertical vector [5,1] can be viewed as a matrix with five rows (5) and one column (1). Conversely, the row vector [1,5] can be considered as a matrix with one row (1) and five columns (5).

You can also generate a vector of random real numbers.

For instance, to create a vector with five 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

To create a vector with five 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 the command randi([18,30],1,5) to create a row vector with 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 create vectors with random integer numbers using the random number generation function rand() and the rounding function round().

For example, you can obtain the same result as in the previous example by executing the command 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