How to Generate a 4-digit Random Unique Number Using Matlab?

Hello Friends Today, through this tutorial, I will tell you how to generate a 4-digit random unique OTP number using MATLAB Program?

Here’s how to generate a 4-digit random unique number using the MATLAB program:

function unique_otp = generateUniqueOTP()
% Define pool of digits
pool = 0:9;

% Generate random number with leading zeros
random_number = randi(10^4 - 1, 1) + 1000;

% Check for uniqueness (optional)
while ismember(random_number, unique_otp)
random_number = randi(10^4 - 1, 1) + 1000;
end

% Convert to string and return
unique_otp = num2str(random_number);
end

% Generate and display a unique OTP
unique_otp = generateUniqueOTP();
disp(['Generated Unique OTP: ', unique_otp]);

Explanation:-

`generateUniqueOTP` function:-

1. Defines a `pool` variable containing the digits (0 to 9) used for the OTP.
2. Generates a random number using `randi` within the range of 1 to 9999 (inclusive) and adds 1000 to ensure leading zeros.
3. Optionally, it implements a loop to check for uniqueness. While the generated number exists in an array of previously generated OTPs (initially empty), a new random number is generated.
4. Converts the final number to a string using `num2str` and returns it.
5. Calls the `generateUniqueOTP` function to get a unique OTP.
6. Displays the generated OTP using `disp`.