Open In App

Random Numbers in MATLAB

Last Updated : 22 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Random numbers, as the name suggests, are numbers chosen randomly from a set of numbers. In practical application, classical computers cannot create truly random numbers as they are developed on binary logic thus, they require some sort of algorithm to generate random numbers, this type of random number is called a pseudorandom number. They are random numbers generated by an algorithm in the core of a given programming language by using some variable such as system time, which will never be the same, as a seed to produce different numbers every time.

In MATLAB, there are plenty of options to generate random numbers of different types. This article will discuss how to generate random numbers with various options available in MATLAB.

Generating Random Numbers:

The rand function in MATLAB generates random numbers in MATLAB. 

Syntax:

num = rand(<optional parameters>)

The rand function generates uniformly distributed random numbers (real numbers) in the range of (0,1).

Example 1:

Matlab




% MATLAB code 
for i = 1:5
    ran_num = rand;
    disp(ran_num)
end


Output:

 

The above code generates 5 random numbers and displays them using the disp() function.

Square Matrix of Random Numbers:

To generate an n-order matrix of random numbers in the range (0,1), we use the following method.

mat = rand(n)

where n is the order of required matrix.

Example 2:

Matlab




% MATLAB code 
matrix = rand(3);
disp(matrix)


Output:

 

This will generate a 3 by 3 matrix of random numbers in the range of (0,1).

Generating an Array of Random Numbers of Any Size:

MATLAB provides the option to generate an array of any size and shape by using the same rand() function and passing the size of the array as a row vector to it.

Syntax:

arr = rand([<size of required array>])

We will create an array of 4-by-3-by-2 sizes and display it.

Example 3:

Matlab




% MATLAB code 
s = [4 3 2];
arr = rand(s);
disp(arr)


Output:

 

Generating Random Numbers in Any Range (min, max):

We can create random numbers in any range of real numbers (min, max) using the standard formula:

min + (max-min)*rand

The following code creates a 3-order matrix in the range (-2.3, 2.3).

Example 4:

Matlab




% MATLAB code 
% Defining max and min of required range
min = -2.3;
max = 2.3;
  
% Creating a 3x3 matrix inf range (min, max)
arr = min + (max-min)*rand(3);
  
% Displaying the generated array.
disp(arr)


Output:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads