# How can I add a digit to a pre-existing number randomly ?

6 views (last 30 days)
Seb Gilbert on 3 Nov 2015
Answered: Image Analyst on 5 Nov 2015
I want to be able to choose from a set of numbers (e.g. {2,3,9,12}) and odd that digit onto the end of a number x. Also each digit is randomly chosen. What I mean is if x=269 and 2 was selected randomly from my predesignated set then my number would be 2692. If 9 was now randomly selected then the number would now be 26929, and if 3 were randomly selected then my new number would now be 269293 etc.... I know about randsample but I can't make it only choose numbers from a defined set. For the function to add a digit to a number x I've looked for three hours on the internet and cannot find anything, my problem appears to be unique!

David Young on 3 Nov 2015
To take a random sample from a vector, just use randi - no need for randsample. Example:
numbers = [2, 3, 9, 7];
randomNumber = numbers(randi(length(numbers)));
To add a digit to the end of another number, assuming the digit is represented by an integer value in the range 0 to 9, just multiply by 10 and add. Example:
x = 269;
x = 10*x + randomNumber;
... and repeat as necessary.
You can also convert x and the extra digit to strings and concatenate them. That's a little more fiddly, but depending on what you really want to end up with might be a useful technique.
By the way, you say you want to add a digit to the number, but your set of "digits" includes 12. Is that a mistake, or do you actually want to do something more general than adding a single digit to the decimal representation?

Seb Gilbert on 5 Nov 2015
Thank you very much! That solution works perfectly for my work :)
Image Analyst on 5 Nov 2015
Can you vote for it and mark it as Accepted then to give David reputation points?

Image Analyst on 5 Nov 2015
You can try this common "trick", which will work for any number of digits in x and the set of numbers:
numbers = [2, 3, 9, 7, 1234];
randomNumber = randsample(numbers, 1)
x = 269;
% Convert to string then back to number.
output = str2double(sprintf('%d%d', x, randomNumber))

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by