lettura simple

Random Matrices in Matlab

In this lesson, I will explain how to create a matrix with random values in Matlab using the rand() function.

rand(rows, columns)

The rand() function has two parameters:

  • The number of rows in the matrix
  • The number of columns in the matrix

This function generates a random matrix composed of random values ranging from 0 to 1.

Note. By default, Matlab generates random values with a uniformly distributed probability among all possible values. However, it is also possible to use other probability distributions to generate random numbers.

Here's a practical example.

Type rand(2,3) to generate a 2x3 rectangular matrix with random values.

>> rand(2,3)

Matlab generates a 2x3 random matrix by inserting random values between 0 and 1.

By default, the random numbers are uniformly distributed in the interval (0,1), meaning they have the same probability of being generated.

ans =
0.495435 0.651593 0.093860
0.449491 0.788723 0.028347

To create a random matrix with numbers between 0 and 10, multiply the rand() function by 10.

The result is a random matrix composed of random real numbers between 0 and 10.

>> rand(2,3)*10
ans =
1.35346 1.04275 0.73193
5.51170 0.39138 8.66168

To obtain a random matrix with integer numbers between 0 and 10, use the rounding function round().

For example, type round(rand(2,3)*10) to generate a 2x3 matrix with integer numbers between 0 and 10.

>> round(rand(2,3)*10)
ans =
3 9 10
3 6 9

Alternatively, you can generate a matrix with random integer values using the randi() function.

randi(max value, rows, columns)

The randi() function generates exclusively random integer values and has three parameters:

  • The maximum random value that can be generated
  • The number of rows in the matrix
  • The number of columns in the matrix

For example, type randi(10,2,3)

>> randi(10,2,3)
ans =
1 9 3
2 1 10

In this case as well, Matlab generates a random matrix composed of integer numbers.

How does Matlab generate random values? In reality, these values are not truly random. They are "pseudo-random" values because an algorithm generates the random numbers using the current time of the computer as a parameter. It is also possible to produce the same sequence of random numbers every time if desired. We will discuss this further later on.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin