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