How can I add a digit to a pre-existing number randomly ?
4 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
回答(2 个)
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 个评论
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
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))
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!