# multiple digit number in to individual digits

551 views (last 30 days)
Raza on 22 Jul 2014
Edited: Adam Danz on 29 Apr 2020 at 18:07
i want to change the number 1123 in 1 1 2 3, want to split combine number into into individual numbers

Azzi Abdelmalek on 22 Jul 2014
a=1234
b=str2double(regexp(num2str(a),'\d','match'))

naveen selvan on 7 Feb 2017
Hi, I have a follow-up question to ask. if you have a postfix expression like 123*+ then how do you split them into individual characters. For example, a = 123*+ then i need to get b = 1 2 3 * + pls help!
Walter Roberson on 7 Feb 2017
a = '123*+'
for K = 1 : length(a)
fprintf('character #%d of "%s" is "%c"\n', K, a, a(K));
end
Adam Danz on 29 Apr 2020 at 18:02
For large values such as a=11122333345555566 this will not work since num2str will convert the value to '1.112233334555557e+16'. Otherwise nice solution.

John D'Errico on 22 Jul 2014
N = 1123;
Ndigits = dec2base(N,10) - '0'
Ndigits =
1 1 2 3

#### 1 Comment

Adam Danz on 29 Apr 2020 at 17:52
Great solution. Note that N must be smaller than flintmax.

Jan on 7 Feb 2017
Edited: Jan on 14 Feb 2017
For getting the digits, a conversion to a string is an indirection. Staying at numerical values is usually faster:
N = 1123;
m = floor(log10(N)); % [EDITED] Thanks Stephen
D = mod(floor(N ./ 10 .^ (m:-1:0)), 10);

Stephen Cobeldick on 14 Feb 2017
Almost right, but not quite:
>> N = 10;
>> m = ceil(log10(N));
>> D = mod(floor(N ./ 10 .^ (m-1:-1:0)), 10)
D =
0
It ate my ten!!!!
Using floor not ceil works:
>> N = 10;
>> m = floor(log10(N));
>> D = mod(floor(N ./ 10 .^ (m:-1:0)), 10)
D =
1 0
Jan on 14 Feb 2017
Thanks, Stephen. I've fixed it. Perhaps I need some holidays.
Adam Danz on 29 Apr 2020 at 18:04
Quite robust!

Ramon Villamangca on 20 Nov 2018
Edited: Ramon Villamangca on 20 Nov 2018
a simple single line solution:
>> num = 12345042117;
>> arrayfun(@(x) mod(floor(num/10^x),10),floor(log10(num)):-1:0)
ans =
1 2 3 4 5 0 4 2 1 1 7