Separating digits in decimal representation of integer

后端 未结 3 347
我在风中等你
我在风中等你 2021-01-17 05:10

I want to take user input entered as an integer, for example (45697), and store the first two digits in an array, vector, or something else such as ( 4 5

相关标签:
3条回答
  • 2021-01-17 05:36

    Since you are interested in individual digits, you don't even need to invoke str2num. One way is enough as in x_str = num2str(x);, then you subtract '0' with y = x_str(1:2)-'0';.

    0 讨论(0)
  • 2021-01-17 05:40

    You can do it easily using conversions to/from strings:

    >> x = 45697; % or whatever positive value
    >> str = num2str(x);
    >> y = [str2num(str(1)) str2num(str(2))]
    
    y =
    
         4     5
    

    This assumes that the number x is positive (if it were negative the first character would not be a digit). That seems to be the case, since according to your comments it represents an electrical resistance.

    0 讨论(0)
  • 2021-01-17 05:45

    There is nothing wrong with a string-based approach, but here is a mathematical solution to getting all of the digits:

    >> x = 45697
    x =
    
           45697
    
    >> numDigits = floor(log10(x)+1)
    numDigits =
    
         5
    
    >> tens = 10.^(1:numDigits);
    >> digitArray = fliplr(floor(mod(x,tens)./(tens/10)))
    digitArray =
    
         4     5     6     9     7
    

    The crux of this method is to use mod to chip off the high digits one at a time, shifting the new first digit down to the ones place, and finally truncating down to the get the integer value at that position.

    In the case of the OP, the required values are digitArray(1:2).

    0 讨论(0)
提交回复
热议问题