Tutorial

How to Create a Matrix of Random Floating-Point Numbers Within a Range in MATLAB

The functions rand and randn create matrices of random floating-point numbers, but do not allow to specify a range.

Formula

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()\]

Function

The function 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.

The file ‘randwithinrange.m’ must be in the current directory or in the MATLAB search path.
% Random floating-point number in the range (0,1.5)
resultExample1 = randwithinrange([0,1.5]);
% Square matrix of random floating-point numbers in the range (1,2)
resultExample2 = randwithinrange([1,2],3);
% Vector of random floating-point numbers in the range (-5,5)
resultExample3 = randwithinrange([-5,5],1,7);

Drawback

The function 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);
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 the other tutorials in this series.

Source code

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.

Share

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