Apply this procedure to create a matrix of non-repeated random integers within a range:
- Randomly permute the integers of the range
- Select \(N\) integers from the result obtained in Step 1, where \(N\) is the number of elements determined by the size of the matrix
- Reshape the result obtained in Step 2 according to the size of the matrix
Note that the number of integers in the range must be greater than or equal to the number of elements determined by the size of the matrix.
% Square matrix of non-repeated random integers in the range [-5,7] resultExample1 = randiunique([-5,7],2);
resultExample1 = 7 2 -2 -1
% Vector of non-repeated random integers in the range [-100,100] resultExample2 = randiunique([-100,100],1,7);
resultExample2 = -65 -29 -89 3 -34 -66 -60
% Matrix of non-repeated random integers in the range [0,25] resultExample3 = randiunique([0,25],2,3);
resultExample3 = 23 11 2 16 20 15
Note: 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 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 create a matrix of non-repeated random integers in MATLAB. The source code developed in this tutorial is available at this page.