randi generates random integers drawn from the discrete uniform distribution. Find in this book a complete explanation of this distribution, and others.
X = randi([imin,imax],n) creates an n-by-n matrix
X of random integers within the range \([imin,imax]\).
Another use is
X = randi([imin,imax],sz1,…,szN), in which the size of the result is determined by the arguments
randimay contain repeated values.
% Random integer in the range [-5,5] resultExample1 = randi([-5,5],1);
resultExample1 = 4
% Vector of random integers in the range [-10,0] resultExample2 = randi([-10,0],1,5);
resultExample2 = -9 0 -4 -9 -7
% Square matrix of random integers in the range [0,10] resultExample3 = randi([0,10],3);
resultExample3 = 6 1 5 10 10 8 10 10 1
% Matrix of random integers in the range [0,100], with two rows and four columns resultExample4 = randi([0,100],2,4);
resultExample4 = 68 75 66 71 76 39 17 3
Note that your result in the preceding examples could be different due to the random nature of the operations.
I recommend the following books to learn more on random numbers in MATLAB.
This book was the winner of a 2017 Textbook Excellence Award. The first chapter covers random numbers, logical operators, and common elementary math functions, among other topics.
MATLAB for Engineers (5th Edition)
This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. The third chapter covers random numbers, matrix sorting, and several data analysis functions, among other topics.
I also recommend the following page in the MATLAB help documentation, and the other tutorials in this series.
- How to Create a Matrix of Random Floating-Point Numbers in MATLAB
- How to Create a Matrix of Random Integers in MATLAB
- How to Randomly Permute the Integers of a Range in MATLAB
- How to Create a Matrix of Non-Repeated Random Integers in MATLAB
- How to Create a Matrix of Random Floating-Point Numbers Within a Range in MATLAB
- How to Control the Generation of Random Numbers in MATLAB
- Why Does MATLAB Generate the Same Random Numbers in Each Session?
I hope you have learned how to generate random integers in MATLAB. The source code developed in this tutorial is available at this page.