Tutorial

How to Create a Matrix of Non-Repeated Random Integers in MATLAB

The function randi generates random integers, but they can repeat.

Procedure

Apply this procedure to create a matrix of non-repeated random integers within a range:

  1. Randomly permute the integers of the range
  2. Select \(N\) integers from the result obtained in Step 1, where \(N\) is the number of elements determined by the size of the matrix
  3. 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.

Function

The function randiunique encapsulates the procedure described above. It is properly documented and available for download here.

The file ‘randiunique.m’ and its dependencies must be in the current directory or in the MATLAB search path.
% Square matrix of non-repeated random integers in the range [-5,7]
resultExample1 = randiunique([-5,7],2);
% Vector of non-repeated random integers in the range [-100,100]
resultExample2 = randiunique([-100,100],1,7);
% Matrix of non-repeated random integers in the range [0,25]
resultExample3 = randiunique([0,25],2,3);

Note: Your result in the preceding examples could be different due to the random nature of the operations.

Further reading

I recommend the following books to learn more on random numbers in MATLAB.

  1. MATLAB: A Practical Introduction to Programming and Problem Solving (4th Edition)

    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.

  2. 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.

Source code

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.

Share

Your friends may need this knowledge to complete a task. Share this tutorial.