rand generates random numbers in the open interval \((0,1)\) drawn from the standard uniform distribution.
randn uses the standard normal distribution. Find in this book a complete explanation of both distributions, and others.
X = rand stores in
X a random number.
X = rand(n) creates an n-by-n matrix
X of random values.
X = rand(sz1,…,szN) creates a matrix
X of random values, whose size is determined by the arguments of the function.
randnshare the same syntax.
% Random numbers drawn from the standard uniform distribution resultExample1 = rand(3);
resultExample1 = 0.8147 0.9134 0.2785 0.9058 0.6324 0.5469 0.1270 0.0975 0.9575
% Random numbers drawn from the standard normal distribution resultExample2 = randn(3);
resultExample2 = 2.7694 0.7254 -0.2050 -1.3499 -0.0631 -0.1241 3.0349 0.7147 1.4897
% Vector of random numbers resultExample3 = rand(1,5);
resultExample3 = 0.7922 0.9595 0.6557 0.0357 0.8491
% Matrix of random numbers, with two rows and four columns resultExample4 = rand(2,4);
resultExample4 = 0.0318 0.0462 0.8235 0.3171 0.2769 0.0971 0.6948 0.9502
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 pages in the MATLAB help documentation, and the other tutorials in this series.
doc rand; doc randn;
- 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 in MATLAB. The source code developed in this tutorial is available at this page.