There are a host of problems on Cody that require manipulation of the digits of a number. Examples include summing the digits of a number, separating the number into its powers, and adding very large numbers together.
If you haven't come across this trick yet, you might want to write it down (or save it electronically):
digits = num2str(4207) - '0'
That code results in the following:
digits =
4 2 0 7
Now, summing the digits of the number is easy:
sum(digits)
ans =
13
7 Comments
So far this discussion has listed 3 unique ways to separate digits in a number. Someone should write up a comparison to see how all three handle edge cases.
- large integers
- negative values
- fractional value
- array of values
- complex numbers
- different numeric data types
This is the best way to convert string to num for single demand.
However, if you want to string array which is huge to number, the method is not efficient.
You can use another way like this:
x =
123 5676
>> mod(floor(x'./10.^(3:-1:0)),10)
ans =
0 1 2 3
5 6 7 6
Thansk for sharing this trick!
I love this one!
Alternatively, without using num2str,
N = 4207;
digstr = dec2base(N,10) - '0'
digstr =
4 2 0 7