MATLAB facilitates us with multiple functions to generate a scalar, a vector, a matrix, or an array of random numbers. These functions generate different random numbers in different distributions according to their functionalities. In this article, we are going to discuss how to create an array of random numbers using different functions in MATLAB.
How to Create an Array of Random Numbers in MATLAB?
MATLAB has multiple functions for creating an array of random numbers that are listed below:
Now we are going to discuss the working of these functions to generate an array of random numbers.
1: Using rand() Function
The rand() is a built-in function in MATLAB that allows us to generate uniformly distributed random numbers lying between 0 and 1. This function can generate a vector, a scalar, a matrix, or an array of random numbers. For example:
In the above given MATLAB code, we generate a 2-by-3-by-3 array of random numbers between 0 and 1 using the rand(sz1,sz2,sz3) function. Here, we consider sz1 = 2, sz2 = 3, sz3 = 3.
2: Using randi() Function
The randi() is a built-in function in MATLAB that is used for generating discrete uniformly distributed pseudorandom integers lying between 1 and specified value imax. This function can generate a vector, a scalar, a matrix, or an array of random numbers. For example:
In the above example, we generate a 2-by-3-by-2 array of random numbers between 1 and imax using the randi(imax,sz1,sz2,sz3) function. Here, we consider imax = 10, sz1 = 2, sz2=3, sz3 = 2.
3: Using randn() Function
The randn() is a built-in function in MATLAB that is used for generating normally distributed random numbers with a mean of 0 and a standard deviation of 1. This function can generate a vector, a scalar, a matrix, or an array of random numbers. The random numbers generated by this function can be any real positive or negative values. For example:
In the above example, we generate a 2-by-3-by-2 array of normally distributed random numbers using the randn(sz1,sz2,sz3) function. Here, we consider sz1 = 2, sz2 = 3, and sz3 = 2.
Conclusion
MATLAB facilitates us with built-in functions that are used for generating random numbers according to their functionalities. These functions are rand(), randi(), and, randn() These functions can be used for generating a vector, a scalar, a matrix, or an array of random numbers. This tutorial taught us how to generate an array of random numbers using all these functions.