lettura simple

How to make a random matrix in Octave

In this lesson I'll show you how to create a matrix with random values in Octave.

I'll give you a practical example

To create a 2x3 matrix randomly use the function rand(rows,columns)

>> rand(2,3)

Octave generates a random array with values between 0 and 1

ans =
0.495435 0.651593 0.093860
0.449491 0.788723 0.028347

The generated numbers are different each time and uniformly distributed in the interval (0,1).

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

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

If you want to create a random matrix with integers combine the rand() function with the round() function

For example, type round(rand(2,3)*10) to create a 2x3 matrix with values between 0 and 10

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

Alternatively, you can use this command randi(max value, rows, columns) to achieve the same result

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

Octave outputs a random matrix of 2 rows and 3 columns with random integer values in the range (0;10).

How does Octave generate random values? Most of the algorithms that generate random numbers use very long lists with different types of distributions. So, they are not real random numbers but pseudorandom. Octave initializes the algorithm based on the time on the computer clock. Therefore the numbers are always different. However, Octave also allows you to always use the same sequence of random numbers.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin