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

조회 수: 5 (최근 30일)
Seb Gilbert
Seb Gilbert 2015년 11월 3일
답변: Image Analyst 2015년 11월 5일
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!

답변 (2개)

David Young
David Young 2015년 11월 3일
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?
  댓글 수: 2
Seb Gilbert
Seb Gilbert 2015년 11월 5일
Thank you very much! That solution works perfectly for my work :)
Image Analyst
Image Analyst 2015년 11월 5일
편집: Image Analyst 2015년 11월 5일
Can you vote for it and mark it as Accepted then to give David reputation points?

댓글을 달려면 로그인하십시오.


Image Analyst
Image Analyst 2015년 11월 5일
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