In MATLAB, generating random numbers is a common requirement for various applications, simulations, and statistical analyses. The randi () function is a versatile tool that allows you to generate random integers within a specified range. In this article, we will explore the syntax of the randi() function in MATLAB and provide multiple examples to showcase its practical usage in generating random integer values.
The randi() Function in MATLAB
The following is the syntax for MATLAB’s randi() function, which produces random integers within a predetermined range:
Here, [a, b] represents the inclusive range within which the random integers are generated, and the m and n specify the dimensions of the resulting matrix or array.
Example 1: Generate a Single Random Integer
In this example, the randi() function generates a single random integer between 1 and 10. The generated integer is stored in the variable randomInteger and then displayed using the disp() function.
Example 2: Generate a Matrix of Random Integers within a Range
In this example, the randi() function generates a 3×4 matrix of random integers between 50 and 100. The generated matrix is then displayed by using the disp() function after being saved in the randomMatrix variable.
Example 3: Generate a Vector of Random Integers within a Range
In this example, the randi() function generates a vector of 7 random integers between 1 and 50. The generated vector is stored in the variable randomVector and then displayed using the disp() function.
Conclusion
In MATLAB, the randi() function offers a simple and effective approach to producing random integers within a given range. By utilizing the syntax [a, b] for range specification, you can generate single random integers, matrices, or vectors of random integers to suit your specific requirements. The randi() function is a valuable tool for various applications, including simulations, statistical analyses, and random sampling.