Hello Friends Today, through this tutorial, I will tell you how to generate a 6 digit Unique random number in MATLAB.
Generating a truly unique random number in MATLAB is challenging as it relies on factors like the computer’s internal state and seed values, which can lead to repetitions for different runs. However, you can achieve a ‘high degree of “practical” uniqueness’ by combining several techniques:
Using `randperm` and `tic-toc`.
function uniqueNumber = generateUniqueSixDigitNumber() % Use tic-toc for time-based seed tic; currentTime = toc; % Generate random permutation with large pool (improves uniqueness) randomNumbers = randperm(1000000); % Select the first 6 digits uniqueNumber = randomNumbers(1:6); % Convert to a single integer (optional) if nargout == 1 % Check if output argument is requested uniqueNumber = sum(uniqueNumber .* 10.^(5:-1:0)); end end uniqueNumber = generateUniqueSixDigitNumber(); disp("Generated unique 6-digit number:"); disp(uniqueNumber);
Explanation.
1. The function uses `tic` to start a timer, capturing the current time.
2. It generates a random permutation of 1 million numbers using `randperm`, increasing the pool for selection and improving uniqueness compared to smaller ranges.
3. It selects the first 6 digits from the permutation as the “unique” number.
4. The code includes an optional conversion to a single integer by multiplying each digit with its corresponding power of 10 and summing them. This is useful if you need to perform calculations on the number.
5. Calling the function generates a supposedly unique 6-digit number and displays it.