Matlab

randi(Random integer) in MatLab

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:

R = randi([a, b], m, n)

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

randomInteger = randi([1, 10]);

disp(randomInteger);

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

randomMatrix = randi([50, 100], 3, 4);

disp(randomMatrix);

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.

A screenshot of a computer Description automatically generated with low confidence

Example 3: Generate a Vector of Random Integers within a Range

randomVector = randi([1, 50], 1, 7);

disp(randomVector);

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.

A screenshot of a computer Description automatically generated with medium confidence

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.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.