How to Randomly Permute the Integers of a Range in MATLAB

The function randperm randomly permutes the integers of a range.


p = randperm(n) stores in the row vector p a random permutation of the integers in the range \([1,n]\). p = randperm(n,k) selects k unique integers from the range \([1,n]\), and stores them in p.

% Random permutation of the integers in the range [1,10]
resultExample1 = randperm(10);
% Select four random integers from the range [1,15]
resultExample2 = randperm(15,4);


randperm is restricted to integers greater than or equal to 1. I developed the function randpermfree to randomly permute the integers of any range. This function is properly documented and available for download here.

The file ‘randpermfree.m’ must be in the current directory or in the MATLAB search path.
% Random permutation of the integers in the range [-2,5]
resultExample3 = randpermfree(-2,5);
% Select two random integers from the range [-10,10]
resultExample4 = randpermfree(-10,10,2);

Note that 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 following page in the MATLAB help documentation, and the other tutorials in this series.

doc randperm;

Source code

I hope you have learned how to randomly permute the integers of a range in MATLAB. The source code developed in this tutorial is available at this page.


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