Matlab

How to Use the rand() Function in MATLAB?

MATLAB facilitates us with multiple functions to generate a scalar, a vector, or a matrix of random numbers. These functions generate different random numbers in different distributions according to their functionalities. One function among these is the rand() function which allows us to generate uniformly distributed random numbers.

In this article, we will learn how to generate random numbers using the rand() function in MATLAB.

How to Use the rand() Function in MATLAB?

The rand() is a built-in function in MATLAB that allows us to generate uniformly distributed random numbers lying between 0 and 1. This function can be used for generating a vector, a scalar, or a matrix of random numbers.

This function follows a simple syntax that is given below:

X = rand
X = rand(n)
X = rand(sz1,...,szN)

Here:

X = rand returns a random scalar selected from the uniform distribution lying between 0 and 1.

X = rand(n) yields an n-by-n matrix of randomly generated numbers with a uniform distribution having all entries lying between 0 and 1.

X = rand(sz1,…,szN) returns a random number array with uniform distribution having all entries lying between 0 and 1 and having a size of sz1 by… by szN where sz1,…,szN denotes the dimensions’ sizes.

For example, rand(4,3) returns a 4-by-3 matrix.

Consider some examples that demonstrate the use of the rand() function in MATLAB.

Example 1
The given example generates a scalar random number that lies between 0 and 1 using the rand function.

rand

Example 2
In this example, we generate a 4-by-4 matrix of random numbers that lie between 0 and 1 using the rand(n) function. Here, we consider n = 4.

rand(4)

Example 3
In this MATLAB code, we generate a 4-by-3 matrix of random numbers that lie between 0 and 1 using the rand(sz1,sz2) function by considering sz1 = 4 and sz2 = 3.

rand(4,3)

Conclusion

The rand() is a MATLAB built-in function that is used for generating uniformly distributed random numbers lying between the range (0,1). This function can be used for generating a vector, a scalar, or a matrix of random numbers. This tutorial taught us how to generate random numbers in MATLAB between 0 and 1 using the rand() function.

About the author

Komal Batool Batool

I am passionate to research technologies and new ideas and that has brought me here to write for the LinuxHint. My major focus is to write on programming languages and computer science related topics.