A random floating-point number \(R\) in the open interval \((fmin,fmax)\) can be generated using the formula stated below, where \(abs(i)\) returns the absolute value of \(i\), and \(rand()\) returns a random floating-point number in the open interval \((0,1)\).\[R = fmin + abs(fmax-fmin) * rand()\]
randwithinrange uses the preceding formula to generate a matrix of random floating-point numbers within an open interval. It is properly documented and available for download here.
% Random floating-point number in the range (0,1.5) resultExample1 = randwithinrange([0,1.5]);
resultExample1 = 0.0231
% Square matrix of random floating-point numbers in the range (1,2) resultExample2 = randwithinrange([1,2],3);
resultExample2 = 1.1890 1.3685 1.0811 1.6868 1.6256 1.9294 1.1835 1.7802 1.7757
% Vector of random floating-point numbers in the range (-5,5) resultExample3 = randwithinrange([-5,5],1,7);
resultExample3 = 2.9483 1.4432 -1.2139 3.1158 0.3283 -1.4927 4.3900
randwithinrange has a drawback consisting in that integers are unlikely to occur in the result, and will not occur if the limits of the range are integers.
For example, if you use the function to generate random numbers in the range \((0,100)\), the integers in this range will not occur.
% Integers will not occur in the result resultExample4 = randwithinrange([0,100],5);
resultExample4 = 52.1650 14.9865 80.0331 13.3171 6.0471 9.6730 65.9605 45.3798 17.3389 39.9258 81.8149 51.8595 43.2392 39.0938 52.6876 81.7547 97.2975 82.5314 83.1380 41.6799 72.2440 64.8991 8.3470 80.3364 65.6860
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 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 floating-point numbers within a range in MATLAB. The source code developed in this tutorial is available at this page.