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
% Random permutation of the integers in the range [1,10] resultExample1 = randperm(10);
resultExample1 = 6 1 7 4 9 5 8 3 10 2
% Select four random integers from the range [1,15] resultExample2 = randperm(15,4);
resultExample2 = 4 15 12 9
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.
% Random permutation of the integers in the range [-2,5] resultExample3 = randpermfree(-2,5);
resultExample3 = -1 0 1 5 4 2 3 -2
% Select two random integers from the range [-10,10] resultExample4 = randpermfree(-10,10,2);
resultExample4 = 1 -5
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 randomly permute the integers of a range in MATLAB. The source code developed in this tutorial is available at this page.