MATLAB Answers


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

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!

  0 件のコメント

サインイン to comment.

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 2015 年 11 月 5 日
Thank you very much! That solution works perfectly for my work :)
Image Analyst
2015 年 11 月 5 日
Can you vote for it and mark it as Accepted then to give David reputation points?

サインイン to comment.

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))

  0 件のコメント

サインイン to comment.

Translated by